Initialize a OriginalClearSkyCondition from an analysis_period
2755
def from_analysis_period(cls, analysis_period, clearness=1,
                             daylight_savings_indicator='No'):
        """""""
        _check_analysis_period(analysis_period)
        return cls(analysis_period.st_month, analysis_period.st_day, clearness,
                   daylight_savings_indicator)
456252
@Override
    public MethodGen analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
        Method method = getMethod(analysisCache, descriptor);

        if (method.getCode() == null) {
            return null;
        }
        XMethod xmethod =  XFactory.createXMethod(descriptor);
        if (xmethod.usesInvokeDynamic() && false) {
            AnalysisContext.currentAnalysisContext().analysisSkippedDueToInvokeDynamic(xmethod);
            return null;
        }

        try {
            AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
            JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
            ConstantPoolGen cpg = getConstantPoolGen(analysisCache, descriptor.getClassDescriptor());

            String methodName = method.getName();
            int codeLength = method.getCode().getCode().length;
            String superclassName = jclass.getSuperclassName();
            if (codeLength > 6000 && Const.STATIC_INITIALIZER_NAME.equals(methodName) && "java.lang.Enum".equals(superclassName)) {
                analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                        new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                return null;
            }
            if (analysisContext.getBoolProperty(AnalysisFeatures.SKIP_HUGE_METHODS)) {
                if (codeLength > 6000 || (Const.STATIC_INITIALIZER_NAME.equals(methodName) || "getContents".equals(methodName)) && codeLength > 2000) {
                    analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                            new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                    return null;
                }
            }

            return new MethodGen(method, jclass.getClassName(), cpg);
        } catch (Exception e) {
            AnalysisContext.logError("Error constructing methodGen", e);
            return null;
        }
    }
932006
def init(self):
        """"""
        if not self.export_enable:
            return None

        self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
        template_body =  {
          "mappings": {
            "glances": {
              "dynamic_templates": [
                {
                  "integers": {
                    "match_mapping_type": "long",
                    "mapping": {
                      "type": "integer"
                    }
                  }
                },
                {
                  "strings": {
                    "match_mapping_type": "string",
                    "mapping": {
                      "type": "text",
                      "fields": {
                        "raw": {
                          "type":  "keyword",
                          "ignore_above": 256
                        }
                      }
                    }
                  }
                }
              ]
            }
          }
        }

        try:
            es = Elasticsearch(hosts=['{}:{}'.format(self.host, self.port)])
        except Exception as e:
            logger.critical("Cannot connect to ElasticSearch server %s:%s (%s)" % (self.host, self.port, e))
            sys.exit(2)
        else:
            logger.info("Connected to the ElasticSearch server %s:%s" % (self.host, self.port))

        try:
            index_count = es.count(index=self.index)['count']
        except Exception as e:
            # Index did not exist, it will be created at the first write
            # Create it...
            es.indices.create(index=self.index,body=template_body)
        else:
            logger.info("The index %s exists and holds %s entries." % (self.index, index_count))

        return es
341487
@Override
    public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        LOGGER.debug("Initializing Artifactory analyzer");
        final boolean enabled = isEnabled();
        LOGGER.debug("Artifactory analyzer enabled: {}", enabled);
        if (enabled) {
            searcher = new ArtifactorySearch(getSettings());
            final boolean preflightRequest = searcher.preflightRequest();
            if (!preflightRequest) {
                setEnabled(false);
                throw new InitializationException("There was an issue connecting to Artifactory . Disabling analyzer.");
            }
        }
    }
883296
void initializeIfNeeded(final UUID objectId) {
        if (auditLogsCache.get(objectId) == null) {
            auditLogsCache.put(objectId, new LinkedList<AuditLog>());
        }
    }
1001373
def from_json(cls, data):
        
        # Check required and optional keys
        required_keys = ('solar_model', 'month', 'day_of_month')
        for key in required_keys:
            assert key in data, 'Required key "{}" is missing!'.format(key)

        if data['solar_model'] == 'ASHRAEClearSky':
            return OriginalClearSkyCondition.from_json(data)
        if data['solar_model'] == 'ASHRAETau':
            return RevisedClearSkyCondition.from_json(data)

        if 'daylight_savings_indicator' not in data:
            data['daylight_savings_indicator'] = 'No'
        optional_keys = ('beam_shced', 'diff_sched')
        for key in optional_keys:
            if key not in data:
                data[key] = ''

        return cls(data['month'], data['day_of_month'], data['clearness'],
                   data['daylight_savings_indicator'],
                   data['beam_shced'], data['diff_sched'])
878485
@Override
    protected void analyzeDependency(Dependency dependency, Engine engine)
            throws AnalysisException {
        if (needToDisableGemspecAnalyzer) {
            boolean failed = true;
            final String className = RubyGemspecAnalyzer.class.getName();
            for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) {
                if (analyzer instanceof RubyBundlerAnalyzer) {
                    ((RubyBundlerAnalyzer) analyzer).setEnabled(false);
                    LOGGER.info("Disabled {} to avoid noisy duplicate results.", RubyBundlerAnalyzer.class.getName());
                } else if (analyzer instanceof RubyGemspecAnalyzer) {
                    ((RubyGemspecAnalyzer) analyzer).setEnabled(false);
                    LOGGER.info("Disabled {} to avoid noisy duplicate results.", className);
                    failed = false;
                }
            }
            if (failed) {
                LOGGER.warn("Did not find {}.", className);
            }
            needToDisableGemspecAnalyzer = false;
        }
        final File parentFile = dependency.getActualFile().getParentFile();
        final Process process = launchBundleAudit(parentFile);
        final int exitValue;
        try {
            exitValue = process.waitFor();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new AnalysisException("bundle-audit process interrupted", ie);
        }
        if (exitValue < 0 || exitValue > 1) {
            final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue);
            throw new AnalysisException(msg);
        }
        try {
            try (BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
                while (errReader.ready()) {
                    final String error = errReader.readLine();
                    LOGGER.warn(error);
                }
            }
            try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                processBundlerAuditOutput(dependency, engine, rdr);
            }
        } catch (IOException | CpeValidationException ioe) {
            LOGGER.warn("bundle-audit failure", ioe);
        }
    }
829201
def _pre_analysis(self):
        

        l.debug("Starting from %#x", self._start)

        # initialize the task stack
        self._task_stack = [ ]

        # initialize the execution counter dict
        self._execution_counter = defaultdict(int)

        # Generate a CFG if no CFG is provided
        if not self._cfg:
            l.debug("Generating a CFG, since none was given...")
            # TODO: can we use a fast CFG instead? note that fast CFG does not care of context sensitivity at all, but
            # TODO: for state merging, we also don't really care about context sensitivity.
            self._cfg = self.project.analyses.CFGEmulated(context_sensitivity_level=self._context_sensitivity_level,
                starts=(self._start,)
            )

        if not self._cfg.normalized:
            l.warning("The given CFG is not normalized, which might impact the performance/accuracy of the VFG "
                      "analysis.")

        # Prepare the state
        initial_state = self._prepare_initial_state(self._start, self._initial_state)
        initial_state.ip = self._start

        if self.project.arch.name.startswith('MIPS'):
            initial_state.regs.t9 = self._start

        # clear function merge points cache
        self._function_merge_points = {}

        # Create the initial state
        state = initial_state.copy()

        if self._start_at_function:
            # set the return address to an address so we can catch it and terminate the VSA analysis
            # TODO: Properly pick an address that will not conflict with any existing code and data in the program
            self._final_address = 0x4fff0000
            self._set_return_address(state, self._final_address)

        call_stack = None
        if not self._start_at_function:
            # we should build a custom call stack
            call_stack = CallStack()
            call_stack = call_stack.call(None, self._function_start, retn_target=self._final_address)

        job = VFGJob(state.addr, state, self._context_sensitivity_level,
                     jumpkind='Ijk_Boring', final_return_address=self._final_address,
                     call_stack=call_stack
                     )
        block_id = BlockID.new(state.addr, job.get_call_stack_suffix(), job.jumpkind)
        job._block_id = block_id

        self._insert_job(job)

        # create the task
        function_analysis_task = FunctionAnalysis(self._function_start, self._final_address)
        function_analysis_task.jobs.append(job)
        self._task_stack.append(function_analysis_task)
1108379
def sg_init(sess):
     
    """
    # initialize variables
    sess.run(tf.group(tf.global_variables_initializer(),
                      tf.local_variables_initializer()))
1203973
def _init_objgoea(self, pop, assoc):
        """"""
        propagate_counts = not self.args.no_propagate_counts
        return GOEnrichmentStudy(pop, assoc, self.godag,
                                 propagate_counts=propagate_counts,
                                 relationships=False,
                                 alpha=self.args.alpha,
                                 pvalcalc=self.args.pvalcalc,
                                 methods=self.methods)
899268
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)
        obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
                                       expCube=args.expcube,
                                       srcMaps=args.cmap,
                                       binnedExpMap=args.bexpmap)

        if args.no_psf:
            performConvolution = False
        else:
            performConvolution = True

        config = BinnedAnalysis.BinnedConfig(performConvolution=performConvolution)
        like = BinnedAnalysis.BinnedAnalysis(obs,
                                             optimizer='MINUIT',
                                             srcModel=GtSrcmapsDiffuse.NULL_MODEL,
                                             wmap=None,
                                             config=config)

        source_factory = pyLike.SourceFactory(obs.observation)
        source_factory.readXml(args.srcmdl, BinnedAnalysis._funcFactory,
                               False, True, True)

        source = source_factory.releaseSource(args.source)

        try:
            diffuse_source = pyLike.DiffuseSource.cast(source)
        except TypeError:
            diffuse_source = None

        if diffuse_source is not None:
            try:
                diffuse_source.mapBaseObject().projmap().setExtrapolation(False)
            except RuntimeError:
                pass

        like.logLike.saveSourceMap_partial(args.outfile, source, args.kmin, args.kmax)

        if args.gzip:
            os.system("gzip -9 %s" % args.outfile)
1177530
def analyze_section(section: SoS_Step,
                    default_input: Optional[sos_targets] = None,
                    default_output: Optional[sos_targets] = None,
                    context={},
                    vars_and_output_only: bool = False) -> Dict[str, Any]:
    ''''''
    # analysis_key = (section.md5, section.step_name(),
    #     default_input.target_name() if hasattr(default_input, 'target_name') else '',
    #     default_output.target_name() if hasattr(default_output, 'target_name') else '', vars_and_output_only)
    #if analysis_key in analysis_cache:
    #    return analysis_cache[analysis_key]

    # use a fresh env for analysis
    new_env, old_env = env.request_new()
    try:
        prepare_env(section.global_def, section.global_vars, context)

        env.sos_dict.set('step_name', section.step_name())
        env.sos_dict.set('__null_func__', __null_func__)
        if 'STEP' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
            env.log_to_file(
                'STEP',
                f'Analyzing {section.step_name()} {"(output only)" if vars_and_output_only else ""}'
            )

        res = {
            'step_name': section.step_name(),
            'step_output': get_step_output(section, default_output),
            # variables starting with __ are internals...
            'environ_vars': get_environ_vars(section),
            'signature_vars': get_signature_vars(section),
            'changed_vars': get_changed_vars(section)
        }
        if not vars_and_output_only:
            inps = get_step_input(section, default_input)
            res['step_input'] = inps[0]
            res['dynamic_input'] = inps[1]
            deps = get_step_depends(section)
            res['step_depends'] = deps[0]
            res['dynamic_depends'] = deps[1]
    # analysis_cache[analysis_key] = res
    finally:
        # restore env
        env.restore_to_old(new_env, old_env)

    # #1225
    # The global section can contain a lot of variables, some of which can be large. Here we
    # found all variables that will be used in the step, including ones used in substep (signature_vars)
    # and ones that will be used in input statement etc.
    section.global_vars = {
        x: y
        for x, y in section.global_vars.items()
        if x in get_all_used_vars(section)
    }
    return res
205547
function buildInitStatement(metadata, exportNames, initExpr) {
  return t.expressionStatement(
    exportNames.reduce(
      (acc, exportName) =>
        template.expression`EXPORTS.NAME = VALUE`({
          EXPORTS: metadata.exportName,
          NAME: exportName,
          VALUE: acc,
        }),
      initExpr,
    ),
  );
}
859595
public void initializeRuntime( IExecutionEnvironment execEnv, List<? extends GosuPathEntry> pathEntries, String... discretePackages ) {
    ((ExecutionEnvironment)execEnv).initializeDefaultSingleModule( pathEntries, Collections.emptyList(), discretePackages );
  }
63155
def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir):
    
    if prepared_analyses == None:
        prepared_analyses = prepare_analyses()
    state_collection = funtool.state_collection.StateCollection([],{})
    for analysis in prepared_analyses:
        if analysis.name == named_analysis:
            state_collection= funtool.analysis.run_analysis(analysis, state_collection, log_dir)
    return state_collection
1262015
@Override
    public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        final File location;
        try (InputStream in = FileUtils.getResourceAsStream("GrokAssembly.zip")) {
            if (in == null) {
                throw new InitializationException("Unable to extract GrokAssembly.dll - file not found");
            }
            location = FileUtils.createTempDirectory(getSettings().getTempDirectory());
            ExtractionUtil.extractFiles(in, location);
        } catch (ExtractionException ex) {
            throw new InitializationException("Unable to extract GrokAssembly.dll", ex);
        } catch (IOException ex) {
            throw new InitializationException("Unable to create temp directory for GrokAssembly", ex);
        }

        grokAssembly = new File(location, "GrokAssembly.dll");

        // Now, need to see if GrokAssembly actually runs from this location.
        baseArgumentList = buildArgumentList();
        //TODO this creates an "unreported" error - if someone doesn't look
        // at the command output this could easily be missed (especially in an
        // Ant or Maven build.
        //
        // We need to create a non-fatal warning error type that will
        // get added to the report.
        //TODO this idea needs to get replicated to the bundle audit analyzer.
        if (baseArgumentList == null) {
            setEnabled(false);
            LOGGER.error("----------------------------------------------------");
            LOGGER.error(".NET Assembly Analyzer could not be initialized and at least one "
                    + "'exe' or 'dll' was scanned. The 'dotnet' executable could not be found on "
                    + "the path; either disable the Assembly Analyzer or configure the path dotnet core.");
            LOGGER.error("----------------------------------------------------");
            return;
        }
        try {
            final ProcessBuilder pb = new ProcessBuilder(baseArgumentList);
            final Process p = pb.start();
            // Try evacuating the error stream
            IOUtils.copy(p.getErrorStream(), NullOutputStream.NULL_OUTPUT_STREAM);

            final GrokParser grok = new GrokParser();
            final AssemblyData data = grok.parse(p.getInputStream());
            if (p.waitFor() != 1 || data == null || StringUtils.isEmpty(data.getError())) {
                LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
                LOGGER.debug("GrokAssembly.dll is not working properly");
                grokAssembly = null;
                setEnabled(false);
                throw new InitializationException("Could not execute .NET AssemblyAnalyzer");
            }
        } catch (InitializationException e) {
            setEnabled(false);
            throw e;
        } catch (IOException | InterruptedException e) {
            LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n"
                    + "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.");
            LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
            setEnabled(false);
            throw new InitializationException("An error occurred with the .NET AssemblyAnalyzer", e);
        }
    }
311102
def set_base_initial_condition(model, monomer, value):
    """"""
    # Build up monomer pattern dict
    sites_dict = {}
    for site in monomer.sites:
        if site in monomer.site_states:
            if site == 'loc' and 'cytoplasm' in monomer.site_states['loc']:
                sites_dict['loc'] = 'cytoplasm'
            else:
                sites_dict[site] = monomer.site_states[site][0]
        else:
            sites_dict[site] = None
    mp = monomer(**sites_dict)
    pname = monomer.name + '_0'
    try:
        p = model.parameters[pname]
        p.value = value
    except KeyError:
        p = Parameter(pname, value)
        model.add_component(p)
        model.initial(mp, p)