Generate code for a universal import of imports from imp_from on target.
    imports = [[imp1], [imp2, as], ...]
162056
def universal_import(imports, imp_from=None, target=""):
    """"""
    importmap = []  # [((imp | old_imp, imp, version_check), imp_as), ...]
    for imps in imports:
        if len(imps) == 1:
            imp, imp_as = imps[0], imps[0]
        else:
            imp, imp_as = imps
        if imp_from is not None:
            imp = imp_from + "./" + imp  # marker for from ... import ...
        old_imp = None
        path = imp.split(".")
        for i in reversed(range(1, len(path) + 1)):
            base, exts = ".".join(path[:i]), path[i:]
            clean_base = base.replace("/", "")
            if clean_base in py3_to_py2_stdlib:
                old_imp, version_check = py3_to_py2_stdlib[clean_base]
                if exts:
                    old_imp += "."
                    if "/" in base and "/" not in old_imp:
                        old_imp += "/"  # marker for from ... import ...
                    old_imp += ".".join(exts)
                break
        if old_imp is None:
            paths = (imp,)
        elif not target:  # universal compatibility
            paths = (old_imp, imp, version_check)
        elif get_target_info_len2(target) >= version_check:  # if lowest is above, we can safely use new
            paths = (imp,)
        elif target.startswith("2"):  # "2" and "27" can safely use old
            paths = (old_imp,)
        elif get_target_info(target) < version_check:  # "3" should be compatible with all 3+
            paths = (old_imp, imp, version_check)
        else:  # "35" and above can safely use new
            paths = (imp,)
        importmap.append((paths, imp_as))

    stmts = []
    for paths, imp_as in importmap:
        if len(paths) == 1:
            more_stmts = single_import(paths[0], imp_as)
            stmts.extend(more_stmts)
        else:
            first, second, version_check = paths
            stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
            first_stmts = single_import(first, imp_as)
            first_stmts[0] = openindent + first_stmts[0]
            first_stmts[-1] += closeindent
            stmts.extend(first_stmts)
            stmts.append("else:")
            second_stmts = single_import(second, imp_as)
            second_stmts[0] = openindent + second_stmts[0]
            second_stmts[-1] += closeindent
            stmts.extend(second_stmts)
    return "\n".join(stmts)
567551
def _mk_imp_override(srcname, replacement):
    
    class DummyImporter(object):
        def find_module(self, fullname, path):
            if fullname == srcname:
                return self

            return None

        def load_module(self, fullname):
            if fullname != srcname:
                raise ImportError
            sys.modules[fullname] = replacement
            return replacement

    obj = DummyImporter()
    sys.meta_path.append(obj)
305649
public static void addImport( Instance instance, String componentOrFacetName, Import imp ) {

		Collection<Import> imports = instance.getImports().get( componentOrFacetName );
		if(imports == null) {
			imports = new LinkedHashSet<Import> ();
			instance.getImports().put( componentOrFacetName, imports );
		}

		if( ! imports.contains( imp ))
			imports.add( imp );
	}
1056343
function convertImports(imports) {
		    	for (var file in imports) {
				    if (imports.hasOwnProperty(file)) {
				        postCssInputs[file] = new Input(imports[file], file !== "input" ? { from: file } : undefined);
				    }
				}
			}
307836
def pyfrom(mod_name, import: nil)
      raise ArgumentError, "missing identifier(s) to be imported" unless import

      mod_name = mod_name.to_str if mod_name.respond_to? :to_str
      mod_name = mod_name.to_s if mod_name.is_a? Symbol

      import = Array(import)
      fromlist = import.map.with_index do |import_name, i|
        case import_name
        when assoc_array_matcher
          import_name[0]
        when Symbol, String
          import_name
        else
          raise ArgumentError, "wrong type of import name #{import_name.class} (expected String or Symbol)"
        end
      end
      from_list = PyCall.tuple(from_list)

      main_dict_ptr = PyCall.import_module('__main__').__dict__.__pyptr__
      globals = main_dict_ptr # FIXME: this should mimic to `import_name` function defined in `Python/ceval.c`.
      locals = main_dict_ptr # FIXME: this should mimic to `import_name` function defined in `Python/ceval.c`.
      level = 0 # TODO: support prefixed dots (#25)
      mod = LibPython::Helpers.import_module(mod_name, globals, locals, fromlist, level)

      import.each do |import_name|
        case import_name
        when assoc_array_matcher
          name, asname = *import_name
        when Symbol, String
          name, asname = import_name, import_name
        end

        if PyCall::LibPython::Helpers.hasattr?(mod.__pyptr__, name)
          pyobj = PyCall::LibPython::Helpers.getattr(mod.__pyptr__, name)
          define_name(asname, pyobj)
          next
        end

        if mod.respond_to? :__name__
          pkgname = mod.__name__
          fullname = "#{pkgname}.#{name}"
          sys_modules = PyCall.import_module('sys').modules
          if sys_modules.has_key?(fullname)
            pyobj = module_dict[fullname]
            define_name(asname, pyobj)
            next
          end
        end

        raise ArgumentError, "cannot import name #{fullname}" unless pyobj
      end
    end
148713
def set_implementation(impl):
    
    global __impl__
    if impl.lower() == 'python':
        __impl__ = __IMPL_PYTHON__
    elif impl.lower() == 'c':
        __impl__ = __IMPL_C__
    else:
        import warnings
        warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.')
        __impl__ = __IMPL_PYTHON__
193651
def get_imported_modules(self, module):
    """"""
    for name, member in inspect.getmembers(module):
      if inspect.ismodule(member):
        yield name, member
999842
def visit_Import(self, node, frame):
        """"""
        if node.with_context:
            self.unoptimize_scope(frame)
        self.writeline('l_%s = ' % node.target, node)
        if frame.toplevel:
            self.write('context.vars[%r] = ' % node.target)
        self.write('environment.get_template(')
        self.visit(node.template, frame)
        self.write(', %r).' % self.name)
        if node.with_context:
            self.write('make_module(context.parent, True, locals())')
        else:
            self.write('module')
        if frame.toplevel and not node.target.startswith('_'):
            self.writeline('context.exported_vars.discard(%r)' % node.target)
        frame.assigned_names.add(node.target)
12039
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) {
    ImmutableList.Builder<ImportTree> result = ImmutableList.builder();
    for (ImportTree tree : imports) {
      // javac represents on-demand imports as a member select where the selected name is '*'.
      Tree ident = tree.getQualifiedIdentifier();
      if (!(ident instanceof MemberSelectTree)) {
        continue;
      }
      MemberSelectTree select = (MemberSelectTree) ident;
      if (select.getIdentifier().contentEquals("*")) {
        result.add(tree);
      }
    }
    return result.build();
  }
1092971
def _get_imported_module(self, module_name):
        """"""
        # if imported module on module_set add to list
        imp_mod = self.by_name.get(module_name)
        if imp_mod:
            return imp_mod

        # last part of import section might not be a module
        # remove last section
        no_obj = module_name.rsplit('.', 1)[0]
        imp_mod2 = self.by_name.get(no_obj)
        if imp_mod2:
            return imp_mod2

        # special case for __init__
        if module_name in self.pkgs:
            pkg_name = module_name  + ".__init__"
            return self.by_name[pkg_name]

        if no_obj in self.pkgs:
            pkg_name = no_obj +  ".__init__"
            return self.by_name[pkg_name]
670978
def import_file(name, loc):
    
    loc = path2str(loc)
    if is_python_pre_3_5:
        import imp

        return imp.load_source(name, loc)
    else:
        import importlib.util

        spec = importlib.util.spec_from_file_location(name, str(loc))
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        return module
1370729
def enumerate_dynamic_imports(tokens):
    
    imported_modules = []
    import_line = False
    for index, tok in enumerate(tokens):
        token_type = tok[0]
        token_string = tok[1]
        if token_type == tokenize.NEWLINE:
            import_line = False
        elif token_string == "import":
            try:
                if tokens[index-1][0] == tokenize.NEWLINE:
                    import_line = True
            except IndexError:
                import_line = True # Just means this is the first line
        elif import_line:
            if token_type == tokenize.NAME and tokens[index+1][1] != 'as':
                if token_string not in reserved_words:
                    if token_string not in imported_modules:
                        imported_modules.append(token_string)
    return imported_modules
1234816
def enumerate_import_methods(tokens):
    
    global_imports = enumerate_global_imports(tokens)
    out = []
    for item in global_imports:
        for index, tok in enumerate(tokens):
            try:
                next_tok = tokens[index+1]
                try:
                    next_next_tok = tokens[index+2]
                except IndexError:
                    # Pretend it is a newline
                    next_next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
            except IndexError: # Last token, no biggie
                # Pretend it is a newline here too
                next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
            token_type = tok[0]
            token_string = tok[1]
            if token_string == item:
                if next_tok[1] == '.': # We're calling a method
                    module_method = "%s.%s" % (token_string, next_next_tok[1])
                    if module_method not in out:
                        out.append(module_method)
    return out
566594
def visit_Import(self, node):
        
        for alias in node.names:
            alias_name = tuple(alias.name.split('.'))
            self.imports.add(alias_name[0])
            if alias.asname:
                self.symbols[alias.asname] = alias_name
            else:
                self.symbols[alias_name[0]] = alias_name[:1]
            self.update = True
        return None
655668
function generateImportDeclaration(stmt, semicolon) {
        var result, cursor;

        // If no ImportClause is present,
        // this should be `import ModuleSpecifier` so skip `from`
        // ModuleSpecifier is StringLiteral.
        if (stmt.specifiers.length === 0) {
            // import ModuleSpecifier ;
            return [
                'import',
                space,
                // ModuleSpecifier
                generateExpression(stmt.source, {
                    precedence: Precedence.Sequence,
                    allowIn: true,
                    allowCall: true
                }),
                semicolon
            ];
        }

        // import ImportClause FromClause ;
        result = [
            'import'
        ];
        cursor = 0;

        // ImportedBinding
        if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
            result = join(result, [
                    generateExpression(stmt.specifiers[cursor], {
                        precedence: Precedence.Sequence,
                        allowIn: true,
                        allowCall: true
                    })
            ]);
            ++cursor;
        }

        if (stmt.specifiers[cursor]) {
            if (cursor !== 0) {
                result.push(',');
            }

            if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
                // NameSpaceImport
                result = join(result, [
                        space,
                        generateExpression(stmt.specifiers[cursor], {
                            precedence: Precedence.Sequence,
                            allowIn: true,
                            allowCall: true
                        })
                ]);
            } else {
                // NamedImports
                result.push(space + '{');

                if ((stmt.specifiers.length - cursor) === 1) {
                    // import { ... } from "...";
                    result.push(space);
                    result.push(generateExpression(stmt.specifiers[cursor], {
                        precedence: Precedence.Sequence,
                        allowIn: true,
                        allowCall: true
                    }));
                    result.push(space + '}' + space);
                } else {
                    // import {
                    //    ...,
                    //    ...,
                    // } from "...";
                    withIndent(function (indent) {
                        var i, iz;
                        result.push(newline);
                        for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
                            result.push(indent);
                            result.push(generateExpression(stmt.specifiers[i], {
                                precedence: Precedence.Sequence,
                                allowIn: true,
                                allowCall: true
                            }));
                            if (i + 1 < iz) {
                                result.push(',' + newline);
                            }
                        }
                    });
                    if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                        result.push(newline);
                    }
                    result.push(base + '}' + space);
                }
            }
        }

        result = join(result, [
            'from' + space,
            // ModuleSpecifier
            generateExpression(stmt.source, {
                precedence: Precedence.Sequence,
                allowIn: true,
                allowCall: true
            }),
            semicolon
        ]);
        return result;
    }
554096
def imported_targets(self):
    
    libs = []
    for spec in self.imported_target_specs(payload=self.payload):
      resolved_target = self._build_graph.get_target_from_spec(spec,
                                                               relative_to=self.address.spec_path)
      if not resolved_target:
        raise self.UnresolvedImportError(
          'Could not find target {spec} referenced from {relative_to}'
          .format(spec=spec, relative_to=self.address.spec))
      try:
        libs.append(self.expected_target_constraint.validate_satisfied_by(resolved_target))
      except TypeConstraintError as e:
        raise self.WrongTargetTypeError(
          'Wrong target type {spec} referenced from remote sources target {relative_to}: {err}'
          .format(spec=spec, relative_to=self.address.spec, err=str(e)),
          e)
    return libs
214626
def _ImportHookBySuffix(
    name, globals=None, locals=None, fromlist=None, level=None):
  
  _IncrementNestLevel()

  if level is None:
    # A level of 0 means absolute import, positive values means relative
    # imports, and -1 means to try both an absolute and relative import.
    # Since imports were disambiguated in Python 3, -1 is not a valid value.
    # The default values are 0 and -1 for Python 3 and 3 respectively.
    # https://docs.python.org/2/library/functions.html#__import__
    # https://docs.python.org/3/library/functions.html#__import__
    level = 0 if six.PY3 else -1

  try:
    # Really import modules.
    module = _real_import(name, globals, locals, fromlist, level)
  finally:
    # This _real_import call may raise an exception (e.g., ImportError).
    # However, there might be several modules already loaded before the
    # exception was raised. For instance:
    #   a.py
    #     import b  # success
    #     import c  # ImportError exception.
    # In this case, an 'import a' statement would have the side effect of
    # importing module 'b'. This should trigger the import hooks for module
    # 'b'. To achieve this, we always search/invoke import callbacks (i.e.,
    # even when an exception is raised).
    #
    # Important Note: Do not use 'return' inside the finally block. It will
    # cause any pending exception to be discarded.
    _ProcessImportBySuffix(name, fromlist, globals)

  return module