Simple helper to postprocess angular outputs from StatsCollectors in the
    way we want.
8174
def postproc (stats_result):
    
    n, mean, scat = stats_result
    mean *= 180 / np.pi # rad => deg
    scat /= n # variance-of-samples => variance-of-mean
    scat **= 0.5 # variance => stddev
    scat *= 180 / np.pi # rad => deg
    return mean, scat
21505
def postprocess(self, calc, with_module=None, dry_run=None):
        '''
        
        '''
        for appname, appclass in self.Apps.items():
            if with_module and with_module != appname: continue

            run_permitted = False

            # scope-conditions
            if appclass['apptarget']:
                for key in appclass['apptarget']:
                    negative = False
                    if str(appclass['apptarget'][key]).startswith('!'):
                        negative = True
                        scope_prop = appclass['apptarget'][key][1:]
                    else:
                        scope_prop = appclass['apptarget'][key]

                    if key in calc.info:
                        # non-strict comparison ("CRYSTAL" matches "CRYSTAL09 v2.0")
                        if (str(scope_prop) in str(calc.info[key]) or scope_prop == calc.info[key]) != negative: # true if only one, but not both
                            run_permitted = True
                        else:
                            run_permitted = False
                            break

            else: run_permitted = True

            # module code running
            if run_permitted:
                calc.apps[appname] = {'error': None, 'data': None}
                if dry_run:
                    continue
                try:
                    AppInstance = appclass['appmodule'](calc)
                except:
                    exc_type, exc_value, exc_tb = sys.exc_info()
                    errmsg = "Fatal error in %s module:\n %s" % ( appname, " ".join(traceback.format_exception( exc_type, exc_value, exc_tb )) )
                    calc.apps[appname]['error'] = errmsg
                    calc.warning( errmsg )
                else:
                    try:
                        calc.apps[appname]['data'] = getattr(AppInstance, appclass['appdata'])
                    except AttributeError:
                        errmsg = 'No appdata-defined property found for %s module!' % appname
                        calc.apps[appname]['error'] = errmsg
                        calc.warning( errmsg )
        return calc
1128531
def collect(self):
        
        stats_config = self.config['stats']
        if USE_PYTHON_BINDING:
            collect_metrics = self.collect_via_pynvml
        else:
            collect_metrics = self.collect_via_nvidia_smi

        collect_metrics(stats_config)
1252604
def stats_timing(stats_key, stats_logger):
    """"""
    start_ts = now_as_float()
    try:
        yield start_ts
    except Exception as e:
        raise e
    finally:
        stats_logger.timing(stats_key, now_as_float() - start_ts)
1370029
private void populateCumulatedStats(final ProducerDecoratorBean decorator) {
        if (decorator == null || decorator.getProducers().isEmpty()) {
            LOGGER.warn("Producer's are empty");
            return;
        }

        // Used to calculate cumulated Avg stat
        int cumulatedStatsCounter = 0;

        // Aggregating values
        for (ProducerAO producer : decorator.getProducers()) {
            for (StatLineAO line : producer.getLines()) {
                if (!CUMULATED_STAT_NAME_VALUE.equals(line.getStatName())) {
                    final StatLineAO cumulatedStatLine = new StatLineAO();
                    cumulatedStatLine.setStatName(CUMULATED_STAT_NAME_VALUE);

                    if (decorator.getCumulatedStat() != null) {
                        cumulatedStatLine.setValues(mergeStatValues(decorator.getCumulatedStat().getValues(), line.getValues()));
                    } else {
                        cumulatedStatLine.setValues(line.getValues());
                    }

                    decorator.setCumulatedStat(cumulatedStatLine);
                    cumulatedStatsCounter++;
                }
            }
        }

        // Calculating specific values like ERate and Avg
        if (decorator.getCumulatedStat() != null) {
            // Finding Err and Req stats to calculate ERate
            StatValueAO reqStat = null;
            StatValueAO errStat = null;

            for (StatValueAO value : decorator.getCumulatedStat().getValues()) {
                if ("req".equalsIgnoreCase(value.getName())) {
                    reqStat = value;
                } else if ("err".equalsIgnoreCase(value.getName())) {
                    errStat = value;
                }
            }

            // After merging cumulated stats recalculate ERate and Avg
            List<StatValueAO> cumulatedValues = new ArrayList<>();
            for (StatValueAO value : decorator.getCumulatedStat().getValues()) {
                try {
                    if ("avg".equalsIgnoreCase(value.getName())) {
                        Number averageSumNumber = NumberFormat.getNumberInstance(Locale.US).parse(value.getValue());
                        final DoubleValueAO average = new DoubleValueAO(value.getName(), averageSumNumber.doubleValue() / cumulatedStatsCounter);
                        cumulatedValues.add(average);
                    } else if ("erate".equalsIgnoreCase(value.getName()) && reqStat != null && errStat != null) {
                        Number errNumber = NumberFormat.getNumberInstance(Locale.US).parse(errStat.getValue());
                        Number reqNumber = NumberFormat.getNumberInstance(Locale.US).parse(reqStat.getValue());
                        final DoubleValueAO erate = new DoubleValueAO(value.getName(), errNumber.doubleValue() * 100 / reqNumber.doubleValue());
                        cumulatedValues.add(erate);
                    } else {
                        cumulatedValues.add(value);
                    }
                }
                catch (ParseException ex) {
                    LOGGER.warn("Can't parse stat values", ex);
                }
            }

            decorator.getCumulatedStat().setValues(cumulatedValues);
        }
    }
1330846
static void collectStats(final StatsCollector collector) {
    final RpcManager manager = INSTANCE.get();
    if (manager != null) {
      if (manager.rpc_plugins != null) {
        try {
          collector.addExtraTag("plugin", "rpc");
          for (final RpcPlugin rpc : manager.rpc_plugins) {
            rpc.collectStats(collector);
          }
        } finally {
          collector.clearExtraTag("plugin");
        }
      }

      if (manager.http_plugin_commands != null) {
        try {
          collector.addExtraTag("plugin", "httprpc");
          for (final Map.Entry<String, HttpRpcPlugin> entry
              : manager.http_plugin_commands.entrySet()) {
            entry.getValue().collectStats(collector);
          }
        } finally {
          collector.clearExtraTag("plugin");
        }
      }
    }
  }
895872
function postProcess (output) {
  var self = this;
  this.rules.forEach(function (rule) {
    if (typeof rule.append === 'function') {
      output = join(output, rule.append(self.options));
    }
  });

  return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
}
728416
function extract_program_stats(prog) {
    var stats = {};
    var sources_array = source_stats(prog);

    stats.inputs = input_stats(prog);
    stats.input_total = count_procs(stats.inputs);
    stats.sources = sources_array;
    stats.source_total = sources_array.length;
    stats.reducers = reducer_stats(prog);
    stats.reducer_total = count_procs(stats.reducers);
    stats.functions = function_stats(prog);
    stats.procs = proc_stats(prog);
    stats.proc_total = count_procs(stats.procs);
    stats.views = view_stats(prog);
    stats.view_total = count_procs(stats.views);
    stats.subs = sub_stats(prog);
    stats.imports = import_stats(prog);
    return stats;
}
965326
def render_stats(stats, sort, format):
    
    output = StdoutWrapper()
    if hasattr(stats, "stream"):
        stats.stream = output.stream
    stats.sort_stats(*sort)
    getattr(stats, format)()
    return output.stream
1209970
function procStat( proc, callback ){
    var type = isNumber( proc ) ? 'PID' : 'IMAGENAME',
        arg = '/fi \"' + type + ' eq ' + proc + '\" /fo CSV',
        row = null,
        processes = {
            array: [],
            object: []
        };

    taskList( arg, function( err, stdout ){
        csv.parse( stdout, function( err, rows ){
            if ( rows.length > 0 ){
                for ( var i = 1; i < rows.length; i++ ){
                    row = rows[ i ];

                    processes.array.push( row );
                    processes.object.push({
                        name: row[ 0 ],
                        pid: row[ 1 ],
                        sessionName: row[ 2 ],
                        sessionNumber: row[ 3 ],
                        memUsage: row[ 4 ]
                    })
                }
            } else {
                var noun = isNumber( proc ) ? 'PIDs' : 'process names';
                err = new Error( 'There were no ' + noun + ' found when searching for \"' + proc + '\"' )
            }

            callback( err, processes )
        })
    })
}
1034718
function postResults() {
    if (IS_JSON_FORMAT) {
        const reportPath = `${path.join(PLUGIN_CONFIG.cucumberResultsPath, PLUGIN_CONFIG.cucumberReportName)}.json`;
        const pidReportPath = `${path.join(
            PLUGIN_CONFIG.cucumberResultsPath,
            PLUGIN_CONFIG.cucumberReportName
        )}.${PID_INSTANCE_DATA.pid}.json`;

        if ((!PLUGIN_CONFIG.uniqueReportFileName && fs.existsSync(reportPath))
            || (PLUGIN_CONFIG.uniqueReportFileName && fs.existsSync(pidReportPath))
        ) {
            const currentReportPath = PLUGIN_CONFIG.uniqueReportFileName ? pidReportPath : reportPath;
            const currentReport = fs.readJsonSync(currentReportPath);

            currentReport.map((singleReport) => {
                const featureName = singleReport.name.replace(/\s+/g, '_').replace(/\W/g, '').toLowerCase() || 'noName';
                const browserVersion = PID_INSTANCE_DATA.metadata.browser.version === ''
                    ? ''
                    : `.${PID_INSTANCE_DATA.metadata.browser.version}`;
                const plaformName = PID_INSTANCE_DATA.metadata.platform.name === ''
                    ? ''
                    : `.${PID_INSTANCE_DATA.metadata.platform.name}`;
                const plaformVersion = PID_INSTANCE_DATA.metadata.platform.version === ''
                    ? ''
                    : `.${PID_INSTANCE_DATA.metadata.platform.version}`;
                let fileName = `${featureName}.${PID_INSTANCE_DATA.metadata.browser.name}`;

                fileName += browserVersion + plaformName + plaformVersion;
                const filePath = path.join(PLUGIN_CONFIG.jsonOutputPath, `${fileName}_${Date.now()}.json`);

                /**
                 * If needed remove the previous file if it exists to prevent double reports of 1 feature + browser execution
                 */
                if (PLUGIN_CONFIG.removeExistingJsonReportFile) {
                    fs.readdirSync(PLUGIN_CONFIG.jsonOutputPath)
                        .filter((file) => file.match(new RegExp(fileName, 'ig')))
                        .forEach((file) => fs.removeSync(path.resolve(PLUGIN_CONFIG.jsonOutputPath, file)));
                }

                /**
                 * Add the metadata from the running instance to the report
                 */
                singleReport.metadata = PID_INSTANCE_DATA.metadata;

                /**
                 * Save the file
                 */
                fs.writeJsonSync(filePath, JSON.parse(`[${ JSON.stringify(singleReport) }]`), { spaces: 2 });
            });

            /**
             * Remove the original json report file, defined in the `cucumberOpts.format` if needed
             */
            if (PLUGIN_CONFIG.removeOriginalJsonReportFile) {
                fs.removeSync(currentReportPath);
            }

            if ((PLUGIN_CONFIG.customData || PLUGIN_CONFIG.reportName) && !PLUGIN_CONFIG.automaticallyGenerateReport) {
                console.warn(`
===========================================================================
    YOU ADDED A CUSTOM reportName AND OR ADDED A cucsomerData-object
    WITHOUT SETTING 'automaticallyGenerateReport: true'.
    
    !!!THIS WILL NOT RESULT IN SETTING THE CUSTOM DATA IN THE REPORT!!!                
===========================================================================`);
            }

            /**
             * Generate the HTML report if needed
             */
            if (PLUGIN_CONFIG.automaticallyGenerateReport) {
                /**
                 * If the reportPath is still default, then add the default folder to the same folder
                 * where the results are stored
                 */
                if (PLUGIN_CONFIG.reportPath === REPORT_FOLDER) {
                    PLUGIN_CONFIG.reportPath = path.join(PLUGIN_CONFIG.cucumberResultsPath, REPORT_FOLDER);
                }

                const multiCucumberHTLMReporterConfig = {
                    customMetadata: PLUGIN_CONFIG.customMetadata,
                    displayDuration: PLUGIN_CONFIG.displayDuration,
                    durationInMS: PLUGIN_CONFIG.durationInMS,
                    disableLog: PLUGIN_CONFIG.disableLog,
                    jsonDir: PLUGIN_CONFIG.jsonOutputPath,
                    openReportInBrowser: PLUGIN_CONFIG.openReportInBrowser,
                    reportPath: PLUGIN_CONFIG.reportPath,
                    saveCollectedJSON: PLUGIN_CONFIG.saveCollectedJSON
                };

                /**
                 * Add the custom data if needed
                 */
                if (PLUGIN_CONFIG.customData) {
                    multiCucumberHTLMReporterConfig.customData = PLUGIN_CONFIG.customData;
                }

                /**
                 * Add the custom css if needed
                 */
                if (PLUGIN_CONFIG.customStyle !== '') {
                    multiCucumberHTLMReporterConfig.customStyle = PLUGIN_CONFIG.customStyle;
                }

                /**
                 * Add the override css if needed
                 */
                if (PLUGIN_CONFIG.overrideStyle !== '') {
                    multiCucumberHTLMReporterConfig.overrideStyle = PLUGIN_CONFIG.overrideStyle;
                }

                /**
                 * Add the pageFooter if needed
                 */
                if (PLUGIN_CONFIG.pageFooter) {
                    multiCucumberHTLMReporterConfig.pageFooter = PLUGIN_CONFIG.pageFooter;
                }

                /**
                 * Add the pageTitle if needed
                 */
                if (PLUGIN_CONFIG.pageTitle) {
                    multiCucumberHTLMReporterConfig.pageTitle = PLUGIN_CONFIG.pageTitle;
                }

                /**
                 * Add the custom report name if needed
                 */
                if (PLUGIN_CONFIG.reportName) {
                    multiCucumberHTLMReporterConfig.reportName = PLUGIN_CONFIG.reportName;
                }

                multiCucumberHTLMReporter.generate(multiCucumberHTLMReporterConfig);
            }
        } else {
            console.warn(`\n### File: '${reportPath}' or '${pidReportPath}' is not present! ###\n`);
        }
    }
}
119402
def transform_aglistener_output(result):
    '''
    
    '''
    from collections import OrderedDict
    from msrestazure.tools import parse_resource_id
    try:
        resource_group = getattr(result, 'resource_group', None) or parse_resource_id(result.id)['resource_group']
        # Create a dictionary with the relevant parameters
        output = OrderedDict([('id', result.id),
                              ('name', result.name),
                              ('provisioningState', result.provisioning_state),
                              ('port', result.port),
                              ('resourceGroup', resource_group)])

        # Note, wsfcDomainCredentials will not display
        if result.load_balancer_configurations is not None:
            output['loadBalancerConfigurations'] = format_load_balancer_configuration_list(result.load_balancer_configurations)

        return output
    except AttributeError:
        # Return the response object if the formating fails
        return result
925750
def spread_stats    
      @items = basic_collection.between_dates(@stat_from, @stat_thru)
      
      handle_special_fields
       
      data = {
        alternatives: [
          {
            type: 'spread'
          },
          {
            type: 'process',
            uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true)
          }
        ],   
        from: @stat_from.to_time.utc.to_i * 1000,
        thru: @stat_thru.to_time.utc.to_i * 1000,
        total: @items.count(:id),
        data: @items.count_by(params[:field])
      }
      
      if further_details.keys.include? params[:field]
        filters = (params[:filters] || {})
        filters[params[:field]] = '%{self}'
        
        data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true)
      end
      
      render json: data
    end
1268175
def handle_stats(name, obj):
    
    return {'total_deletions': obj.total['deletions'],
            'total_insertions': obj.total['insertions'],
            'total_lines': obj.total['lines'],
            'total_files': obj.total['files'],
            'changes': obj.files}
532778
@Override
    public <T> void postProcess(T anyContext) {
        Tuple2<List<String>, List<String>> dimsAndMetrics = (Tuple2<List<String>, List<String>>)anyContext;
        List<String> dims = dimsAndMetrics._1();
        List<String> metrics = dimsAndMetrics._2();
        Iterator<Map.Entry<String, String>> colIter = fetchDimensions.entrySet().iterator();
        while (colIter.hasNext()) {
            Map.Entry<String, String> entry = colIter.next();
            if (dims.contains(entry.getKey())) {
                //No action.
            } else if (metrics.contains(entry.getKey())) {
                fetchMetrics.add(entry.getKey());
                colIter.remove();
            } else {//TODO: Handle error
                
            }
        }
    }
1026978
def finalize(self):
        """"""
        super(StochasticProcessStatisticsConsumer, self).finalize()

        class StochasticProcessStatistics(self.statistics):
            """local version to store statistics"""

            def __str__(self):
                s = [k.rjust(12) + str(getattr(self, k)) for k in dir(self) if not k.startswith('_')]
                return '\n'.join(s)

        sps = StochasticProcessStatistics([0, 0])
        keys = list()
        for k in dir(sps):
            if not k.startswith('_'):
                a = getattr(sps, k)
                if isinstance(a, (int, float, str)):
                    keys.append(k)
                else:
                    delattr(sps, k)
        for k in keys:
            setattr(sps, k, list())
        grid = list()
        for g, r in self.result:
            grid.append(g)
            for k in keys:
                a = getattr(sps, k)
                a.append(getattr(r, k))
        self.result = grid, sps
1075280
function postProcessing(tokens, options, source){

  function tokenName(token){
    return (token.prefix ? token.prefix + ':' : '') + token.name;
  }

  function getTokenAttrs(token){
    return token.attrs.reduce(function(res, attr){
      res[tokenName(attr)] = attr.value;
      return res;
    }, {});
  }

  function buildLocationIndex(){
    var line = 1;
    var column = 0;

    lineIdx = new Array(source.length);
    columnIdx = new Array(source.length);

    for (var i = 0; i < source.length + 1; i++)
    {
      lineIdx[i] = line;
      columnIdx[i] = column;

      if (source[i] === '\n')
      {
        line++;
        column = 0;
      }
      else
        column++;
    }
  }


  function findLocationByOffset(offset){
    return {
      line: lineIdx[offset],
      column: columnIdx[offset]
    };
  }

  function getLocationFromRange(range){
    return {
      start: findLocationByOffset(range.start_),
      end: findLocationByOffset(range.end_)
    };
  }

  function convertRange(token){
    if (options.loc)
    {
      token.loc = getLocationFromRange(token.range);
      if (token.valueRange)
        token.valueLoc = getLocationFromRange(token.valueRange);
    }

    if (options.range)
    {
      token.range = [token.range.start_, token.range.end_];
      if (token.valueRange)
        token.valueRange = [token.valueRange.start_, token.valueRange.end_];
    }
    else
    {
      delete token.range;
      delete token.valueRange;
    }
  }

  function walk(tokens){
    var token;
    var prev;

    for (var i = 0; token = tokens[i++]; prev = token)
    {
      // process element
      if (token.type == TYPE_ELEMENT)
      {
        // process attribute content
        var attrs = getTokenAttrs(token);
        for (var j = 0, attr; attr = token.attrs[j++];)
        {
          var mode = attr.name;

          // special case modification instruction in <b:include>
          if (token.prefix == 'b' && attr.name == 'value')
          {
            // parse value attribute in
            //   <b:class>/<b:append-class>/<b:set-class>/<b:remove-class>
            //   <b:attr name="name">/<b:append-attr name="name">/<b:set-attr name="name">/<b:remove-attr name="name">
            var m = token.name.match(ATTRIBUTE_MODE);
            if (m)
              mode = m[1] == 'class' ? 'class' : attrs.name;
          }

          // process bindings and decode HTML tokens
          processAttr(attr, mode, convertRange);

          convertRange(attr);
        }

        // walk recursive
        walk(token.children);
      }

      // process text
      if (token.type == TYPE_TEXT)
      {
        // decode HTML tokens in value
        token.value = decodeHTMLTokens(token.value);

        // try join text tokens
        if (!token.refs && prev && prev.type == TYPE_TEXT && !prev.refs)
        {
          prev.value += token.value;
          prev.end_ = token.end_;
          tokens.splice(--i, 1);
        }
      }

      // process comment
      if (token.type == TYPE_COMMENT)
      {
        // decode HTML tokens in value
        token.value = decodeHTMLTokens(token.value);
      }

      convertRange(token);
    }
  }

  var lineIdx;
  var columnIdx;

  if (options.loc)
    buildLocationIndex();

  walk(tokens);
}