Minimal StatsD wrapper
503187
function makeStatsD(options, logger) {
    let statsd;
    const srvName = options._prefix ? options._prefix : normalizeName(options.name);
    const statsdOptions = {
        host: options.host,
        port: options.port,
        prefix: `${srvName}.`,
        suffix: '',
        globalize: false,
        cacheDns: false,
        mock: false
    };

    // Batch metrics unless `batch` option is `false`
    if (typeof options.batch !== 'boolean' || options.batch) {
        options.batch = options.batch || {};
        statsdOptions.maxBufferSize = options.batch.max_size || DEFAULT_MAX_BATCH_SIZE;
        statsdOptions.bufferFlushInterval = options.batch.max_delay || 1000;
    }

    if (options.type === 'log') {
        statsd = new LogStatsD(logger, srvName);
    } else {
        statsd = new StatsD(statsdOptions);
    }

    // Support creating sub-metric clients with a fixed prefix. This is useful
    // for systematically categorizing metrics per-request, by using a
    // specific logger.
    statsd.makeChild = (name) => {
        const child = statsd.childClient();
        // We can't use the prefix in clientOptions,
        // because it will be prepended to existing prefix.
        child.prefix = statsd.prefix + normalizeName(name) + '.';

        // Attach normalizeName to make the childClient instance backwards-compatible
        // with the previously used StatsD instance
        child.normalizeName = normalizeName;

        return child;
    };

    // Add a static utility method for stat name normalization
    statsd.normalizeName = normalizeName;

    return statsd;
}
407354
def statistics(self, start=None, end=None, namespace=None):
        """"""
        return self.make_context(start=start, end=end,
                                 namespace=namespace).statistics()
562608
def Stat(self, ext_attrs=None):
    """"""
    del ext_attrs  # Unused.
    return self.MakeStatResponse(self.fd, tsk_attribute=self.tsk_attribute)
1312455
def _sd_of_runs(stats, mean, key='runs'):
    

    num_runs = len(stats[key])
    first = stats[key][0]

    standard_deviation = {}
    for stat_key in first:
        # Skip non numberic attributes
        if isinstance(first[stat_key], numbers.Number):
            standard_deviation[stat_key] = math.sqrt(
                sum((run[stat_key] - mean[stat_key])**2
                    for run in stats[key]) / float(num_runs))

    return standard_deviation
105858
function wrap(stats, callback) {
  return function(err, content) {
    if (err) {
      return callback(err);
    }
    stats.content = content;
    return callback(null, stats);
  };
}
508753
def statsId(obj):
  """"""
  if hasattr(obj, ID_KEY):
    return getattr(obj, ID_KEY)
  newId = next(NEXT_ID)
  setattr(obj, ID_KEY, newId)
  return newId
981445
def insert_size_stats(dists):
    
    med = numpy.median(dists)
    filter_dists = list(filter(lambda x: x < med + 10 * med, dists))
    median = numpy.median(filter_dists)
    return {"mean": float(numpy.mean(filter_dists)), "std": float(numpy.std(filter_dists)),
            "median": float(median),
            "mad": float(numpy.median([abs(x - median) for x in filter_dists]))}
600722
def persist_compilestats(run, session, stats):
    
    for stat in stats:
        stat.run_id = run.id
        session.add(stat)
313490
def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist,
                     workingdir=None, mpiexedir=None, exedir=None,
                     log_file=None, runtime_file=None, hostfile=None):
        """"""
        in_params = {'-m': '%s %s' % (TauDEM.convertstatsmethod(statsm),
                                      TauDEM.convertdistmethod(distm))}
        if StringClass.string_match(edgecontamination, 'false') or edgecontamination is False:
            in_params['-nc'] = None
        fname = TauDEM.func_name('dinfdistdown')
        return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir),
                          {'-fel': fel, '-slp': slp, '-ang': ang, '-src': src, '-wg': wg},
                          workingdir,
                          in_params,
                          {'-dd': dist},
                          {'mpipath': mpiexedir, 'hostfile': hostfile, 'n': np},
                          {'logfile': log_file, 'runtimefile': runtime_file})
649624
def quantile(expr, prob=None, **kw):
    

    prob = kw.get('_prob', prob)
    output_type = _stats_type(expr)
    if isinstance(prob, (list, set)) and not isinstance(expr, GroupBy):
        output_type = types.List(output_type)
    return _reduction(expr, Quantile, output_type, _prob=prob)
1119013
def stat_smt_query(func: Callable):
    """"""
    stat_store = SolverStatistics()

    def function_wrapper(*args, **kwargs):
        if not stat_store.enabled:
            return func(*args, **kwargs)

        stat_store.query_count += 1
        begin = time()

        result = func(*args, **kwargs)

        end = time()
        stat_store.solver_time += end - begin

        return result

    return function_wrapper
1058553
def process_fastq_minimal(fastq, **kwargs):
    """"""
    infastq = handle_compressed_input(fastq)
    try:
        df = pd.DataFrame(
            data=[rec for rec in fq_minimal(infastq) if rec],
            columns=["timestamp", "lengths"]
        )
    except IndexError:
        logging.error("Fatal: Incorrect file structure for fastq_minimal")
        sys.exit("Error: file does not match expected structure for fastq_minimal")
    return ut.reduce_memory_usage(df)
1007112
def update_stats(stats, start_time, data):
    '''
    
    '''
    end_time = time.time()
    cmd = data['cmd']
    # the jid is used as the create time
    try:
        jid = data['jid']
    except KeyError:
        try:
            jid = data['data']['__pub_jid']
        except KeyError:
            log.info('jid not found in data, stats not updated')
            return stats
    create_time = int(time.mktime(time.strptime(jid, '%Y%m%d%H%M%S%f')))
    latency = start_time - create_time
    duration = end_time - start_time

    stats[cmd]['runs'] += 1
    stats[cmd]['latency'] = (stats[cmd]['latency'] * (stats[cmd]['runs'] - 1) + latency) / stats[cmd]['runs']
    stats[cmd]['mean'] = (stats[cmd]['mean'] * (stats[cmd]['runs'] - 1) + duration) / stats[cmd]['runs']

    return stats
1023255
def ts_stats_significance(ts, ts_stat_func, null_ts_func, B=1000, permute_fast=False):
    
    stats_ts = ts_stat_func(ts)
    if permute_fast:
        # Permute it in 1 shot
        null_ts = map(np.random.permutation, np.array([ts, ] * B))
    else:
        null_ts = np.vstack([null_ts_func(ts) for i in np.arange(0, B)])
    stats_null_ts = np.vstack([ts_stat_func(nts) for nts in null_ts])
    pvals = []
    nums = []
    for i in np.arange(0, len(stats_ts)):
        num_samples = np.sum((stats_null_ts[:, i] >= stats_ts[i]))
        nums.append(num_samples)
        pval = num_samples / float(B)
        pvals.append(pval)

    return stats_ts, pvals, nums
795326
def convert2pstats(stats):
    
    if not isinstance(stats, YFuncStats):
        raise YappiError("Source stats must be derived from YFuncStats.")
    
    import pstats
    class _PStatHolder:
        def __init__(self, d):
            self.stats = d
        def create_stats(self):
            pass                
    def pstat_id(fs):
        return (fs.module, fs.lineno, fs.name)
    
    _pdict = {}
    
    # convert callees to callers
    _callers = {}
    for fs in stats:
        if not fs in _callers:
            _callers[fs] = {}
            
        for ct in fs.children:
            if not ct in _callers:
                _callers[ct] = {}
            _callers[ct][pstat_id(fs)] = (ct.ncall, ct.nactualcall, ct.tsub ,ct.ttot)
    
    # populate the pstat dict.
    for fs in stats:
        _pdict[pstat_id(fs)] = (fs.ncall, fs.nactualcall, fs.tsub, fs.ttot, _callers[fs], )        
     
    return pstats.Stats(_PStatHolder(_pdict))
1275601
def stats(self):
        
        return OrderedDict([
            ("Intervals", len(self.array)),
            ("Mean", self.format_time(self.mean or 0)),
            ("Min", self.format_time(self.min or 0)),
            ("Median", self.format_time(self.median or 0)),
            ("Max", self.format_time(self.max or 0)),
            ("St. Dev.", self.format_time(self.stdev or 0)),
            ("Total", self.format_time(self.exectime or 0)),
        ])
8796
def installStatsLoop(statsFile, statsDelay):
  """"""

  def dumpStats():
    """Actual stats dump function."""
    scales.dumpStatsTo(statsFile)
    reactor.callLater(statsDelay, dumpStats)

  def startStats():
    """Starts the stats dump in "statsDelay" seconds."""
    reactor.callLater(statsDelay, dumpStats)

  reactor.callWhenRunning(startStats)