Analyze `pymodule` for static object inference

    Analyzes scopes for collecting object information.  The analysis
    starts from inner scopes.
519577
def analyze_module(pycore, pymodule, should_analyze,
                   search_subscopes, followed_calls):
    
    _analyze_node(pycore, pymodule, should_analyze,
                  search_subscopes, followed_calls)
1282340
private void visitModuleDefs(List<PDefinition> defs, INode module)
			throws AnalysisException
	{
		DefinitionInfo defInfo = getStateDefs(defs, module);

		if (defInfo != null)
		{
			addLocalDefs(defInfo);
			handleExecutables(defs);
			removeLocalDefs(defInfo);
		} else
		{
			handleExecutables(defs);
		}
	}
1152703
@Override
    public UsagesRequiringNonNullValues analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
            throws CheckedAnalysisException {
        // ClassContext classContext = getClassContext(jclass);
        ClassContext classContext = analysisCache.getClassAnalysis(ClassContext.class, descriptor.getClassDescriptor());
        Method method = getMethod(analysisCache, descriptor);
        return DerefFinder.getAnalysis(classContext, method);
    }
1346061
public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
        final Model pom = PomUtils.readPom(pomFile);
        JarAnalyzer.setPomEvidence(dependency, pom, null, true);
    }
629781
<S extends StaticScope> void addScopes(Collection<S> scopes) {
    for (S scope : scopes) {
      createScopeFrom(scope);
    }
  }
218440
def lookup_object(spec):
    
    parts, target = spec.split(':') if ':' in spec else (spec, None)
    module = __import__(parts)

    for part in parts.split('.')[1:] + ([target] if target else []):
        module = getattr(module, part)

    return module
983041
void analyze(final MethodResult methodResult) {
        lock.lock();
        try {
            buildPackagePrefix(methodResult.getParentResource().getOriginalClass());

            final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());

            // find project defined methods in invoke occurrences
            final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);

            // add project methods to global method pool
            projectMethods.forEach(MethodPool.getInstance()::addProjectMethod);

            Element returnedElement = new MethodSimulator().simulate(visitedInstructions);
            final String returnType = methodResult.getOriginalMethodSignature().getReturnType();

            // void resource methods are interpreted later; stop analyzing on error
            if (Types.PRIMITIVE_VOID.equals(returnType)) {
                return;
            }

            if (returnedElement == null) {
                // happens for abstract methods or if there is no return
                return;
            }

            final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
                    .collect(Collectors.toSet());

            // for non-Response methods add a default if there are non-Response objects or none objects at all
            if (!Types.RESPONSE.equals(returnType)) {
                final HttpResponse defaultResponse = new HttpResponse();

                if (Types.OBJECT.equals(returnType))
                    defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
                else
                    defaultResponse.getEntityTypes().add(returnType);

                possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);

                defaultResponse.getContentTypes().addAll(methodResult.getResponseMediaTypes());

                methodResult.getResponses().add(defaultResponse);
            }

            // add Response results as well
            returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
        } finally {
            lock.unlock();
        }
    }
1282833
def objectprep(self):
        
        for sample in self.metadata:
            setattr(sample, self.analysistype, GenObject())
            # Set the destination folder
            sample[self.analysistype].outputdir = os.path.join(self.path, self.analysistype)
            # Make the destination folder
            make_path(sample[self.analysistype].outputdir)
            sample[self.analysistype].baitedfastq = os.path.join(
                sample[self.analysistype].outputdir,
                '{at}_targetMatches.fastq.gz'.format(at=self.analysistype))
            # Set the file type for the downstream analysis
            sample[self.analysistype].filetype = self.filetype
            if self.filetype == 'fasta':
                sample[self.analysistype].assemblyfile = sample.general.bestassemblyfile
16562
def beholder_ng(func):
    """"""
    @functools.wraps(func)
    def behold(file, length, *args, **kwargs):
        seek_cur = file.tell()
        try:
            return func(file, length, *args, **kwargs)
        except Exception:
            # from pcapkit.foundation.analysis import analyse
            from pcapkit.protocols.raw import Raw
            error = traceback.format_exc(limit=1).strip().split(os.linesep)[-1]
            # error = traceback.format_exc()

            file.seek(seek_cur, os.SEEK_SET)

            # raw = Raw(file, length, error=str(error))
            # return analyse(raw.info, raw.protochain, raw.alias)
            next_ = Raw(file, length, error=error)
            return next_
    return behold
559276
def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()):
    
    resources = project.get_python_files()
    job_set = task_handle.create_jobset('Analyzing Modules', len(resources))
    for resource in resources:
        job_set.started_job(resource.path)
        analyze_module(project, resource)
        job_set.finished_job()
508500
@Override
    public NonImplicitExceptionPostDominatorsAnalysis analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
            throws CheckedAnalysisException {
        CFG cfg = getCFG(analysisCache, descriptor);
        NonImplicitExceptionPostDominatorsAnalysis analysis = new NonImplicitExceptionPostDominatorsAnalysis(cfg,
                getReverseDepthFirstSearch(analysisCache, descriptor), getDepthFirstSearch(analysisCache, descriptor));
        Dataflow<BitSet, PostDominatorsAnalysis> dataflow = new Dataflow<>(cfg, analysis);
        dataflow.execute();

        return analysis;
    }
789745
function processScope(scope) {
  if (!isObject(scope) || scope._bsontype === 'ObjectID') {
    return scope;
  }

  const keys = Object.keys(scope);
  let key;
  const new_scope = {};

  for (let i = keys.length - 1; i >= 0; i--) {
    key = keys[i];
    if ('function' === typeof scope[key]) {
      new_scope[key] = new Code(String(scope[key]));
    } else {
      new_scope[key] = processScope(scope[key]);
    }
  }

  return new_scope;
}
1074758
function extract(ast, text, scopes, srcScope, destScope, start, end, isExpression) {
        var retObj               = analyzeCode(text, scopes, srcScope, destScope, start, end),
            passParams           = retObj.passParams,
            retParams            = retObj.retParams,
            thisPointerUsed      = retObj.thisPointerUsed,
            returnStatementUsed  = retObj.returnStatementUsed,
            variableDeclarations = retObj.variableDeclarations,
            doc                  = session.editor.document,
            fnBody               = text,
            fnName               = RefactoringUtils.getUniqueIdentifierName(scopes, "extracted"),
            fnDeclaration,
            fnCall;

        function appendVarDeclaration(identifier) {
            if (variableDeclarations.hasOwnProperty(identifier)) {
                 return variableDeclarations[identifier] + " " + identifier;
            }
            else {
                 return identifier;
            }
        }

        if (destScope.isClass) {
            fnCall = StringUtils.format(template.functionCall.class, fnName, passParams.join(", "));
        } else if (thisPointerUsed) {
            passParams.unshift("this");
            fnCall = StringUtils.format(template.functionCall.thisPointer, fnName, passParams.join(", "));
            passParams.shift();
        } else {
            fnCall = StringUtils.format(template.functionCall.normal, fnName, passParams.join(", "));
        }

        // Append return to the fnCall, if the extracted text contains return statement
        // Ideally in this case retParams should be empty.
        if (returnStatementUsed) {
            fnCall = "return " + fnCall;
        }

        if (isExpression) {
            fnBody = StringUtils.format(template.returnStatement.single, fnBody);
        } else {

            var retParamsStr = "";
            if (retParams.length > 1) {
                retParamsStr = StringUtils.format(template.returnStatement.multiple, retParams.join(", "));
                fnCall = "var ret = " + fnCall + ";\n";
                fnCall += retParams.map(function (param) {
                    return StringUtils.format(template.assignment, appendVarDeclaration(param),  "ret." + param);
                }).join("\n");
            } else if (retParams.length === 1) {
                retParamsStr = StringUtils.format(template.returnStatement.single, retParams.join(", "));
                fnCall = StringUtils.format(template.assignment, appendVarDeclaration(retParams[0]), fnCall);
            } else {
                fnCall += ";";
            }

            fnBody = fnBody + "\n" + retParamsStr;
        }

        if (destScope.isClass) {
            fnDeclaration = StringUtils.format(template.functionDeclaration.class, fnName, passParams.join(", "), fnBody);
        } else {
            fnDeclaration = StringUtils.format(template.functionDeclaration.normal, fnName, passParams.join(", "), fnBody);
        }

        start = session.editor.posFromIndex(start);
        end   = session.editor.posFromIndex(end);

        // Get the insertion pos for function declaration
        var insertPos = _.clone(start);
        var fnScopes = scopes.filter(RefactoringUtils.isFnScope);

        for (var i = 0; i < fnScopes.length; ++i) {
            if (fnScopes[i].id === destScope.id) {
                if (fnScopes[i - 1]) {
                     insertPos = session.editor.posFromIndex(fnScopes[i - 1].originNode.start);
                     // If the origin node of the destination scope is a function expression or a arrow function expression,
                     // get the surrounding statement to get the position
                     if (fnScopes[i - 1].originNode.type === "FunctionExpression" || fnScopes[i - 1].originNode.type === "ArrowFunctionExpression") {
                         var surroundStatement = RefactoringUtils.findSurroundASTNode(ast, { start: session.editor.indexFromPos(insertPos)}, ["Statement"]);
                         insertPos = session.editor.posFromIndex(surroundStatement.start);
                     }
                }
                break;
            }
        }

        insertPos.ch = 0;

        // Replace and multi-select and indent
        doc.batchOperation(function() {
            // Replace
            doc.replaceRange(fnCall, start, end);
            doc.replaceRange(fnDeclaration, insertPos);

            // Set selections
            start = doc.adjustPosForChange(start, fnDeclaration.split("\n"), insertPos, insertPos);
            end   = doc.adjustPosForChange(end, fnDeclaration.split("\n"), insertPos, insertPos);

            session.editor.setSelections([
                {
                    start: session.editor.posFromIndex(session.editor.indexFromPos(start) + fnCall.indexOf(fnName)),
                    end:   session.editor.posFromIndex(session.editor.indexFromPos(start) + fnCall.indexOf(fnName) + fnName.length)
                },
                {
                    start: session.editor.posFromIndex(session.editor.indexFromPos(insertPos) + fnDeclaration.indexOf(fnName)),
                    end:   session.editor.posFromIndex(session.editor.indexFromPos(insertPos) + fnDeclaration.indexOf(fnName) + fnName.length)
                }
            ]);

            // indent
            for (var i = start.line; i < start.line + RefactoringUtils.numLines(fnCall); ++i) {
                session.editor._codeMirror.indentLine(i, "smart");
            }
            for (var i = insertPos.line; i < insertPos.line + RefactoringUtils.numLines(fnDeclaration); ++i) {
                session.editor._codeMirror.indentLine(i, "smart");
            }
        });
    }
451262
def _call_scope(self, scope, *args, **kwargs):
        
        result = getattr(self._model, scope)(self, *args, **kwargs)

        return result or self
652574
def p_scope_pointer(self, p):
        ''
        scope = () if p[1].var.scope is None else p[1].var.scope.labellist
        p[0] = IdentifierScope(scope + (IdentifierScopeLabel(p[1].var.name,
                                                             p[1].ptr, lineno=p.lineno(1)),), lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
288256
function getScope(identifier) {
            for (let currentNode = identifier; currentNode; currentNode = currentNode.parent) {
                const scope = sourceCode.scopeManager.acquire(currentNode, true);

                if (scope) {
                    return scope;
                }
            }
            return null;
        }
612576
private static Iterable<Symbol> typesInEnclosingScope(
      Env<AttrContext> env, PackageSymbol javaLang) {
    // Collect all visible type names declared in this source file by ascending lexical scopes,
    // collecting all members, filtering to keep type symbols and exclude TypeVariableSymbols
    // (otherwise, every type parameter spuriously shadows itself)
    Iterable<Symbol> localSymbolsInScope =
        Streams.stream(env)
            .map(
                ctx ->
                    ctx.tree.getTag() == Tag.CLASSDEF
                        ? ((ClassSymbol) ASTHelpers.getSymbol(ctx.tree)).members().getSymbols()
                        : ctx.info.getLocalElements())
            .flatMap(
                symbols ->
                    Streams.stream(symbols)
                        .filter(
                            sym ->
                                sym instanceof TypeSymbol && !(sym instanceof TypeVariableSymbol)))
            .collect(ImmutableList.toImmutableList());

    // Concatenate with all visible type names declared in other source files:
    // Ignore wildcard imports here since we don't use them and they can cause issues (b/109867096)
    return Iterables.concat(
        localSymbolsInScope, // Local symbols
        env.toplevel.namedImportScope.getSymbols(), // Explicitly named imports
        javaLang.members().getSymbols(), // implicitly imported java.lang.* symbols
        env.toplevel.packge.members().getSymbols()); // Siblings in class hierarchy
  }