Calculate the effective sample size for a histogram
    the same way as ROOT does.
504739
def effective_sample_size(h):
    
    sum = 0
    ew = 0
    w = 0
    for bin in h.bins(overflow=False):
        sum += bin.value
        ew = bin.error
        w += ew * ew
    esum = sum * sum / w
    return esum
1023741
def calculate_size(name, expected):
    
    data_size = 0
    data_size += calculate_size_str(name)
    data_size += BOOLEAN_SIZE_IN_BYTES
    if expected is not None:
        data_size += calculate_size_data(expected)
    return data_size
1151815
def ess(sim, n):
    
    try:
        ess = _chains.effective_sample_size(sim, n)
    except (ValueError, ZeroDivisionError):
        ess = nan
    return ess
903721
def run_all(logdir, verbose=False, num_summaries=400):
  """"""
  del verbose

  tf.compat.v1.set_random_seed(0)

  k = tf.compat.v1.placeholder(tf.float32)

  # Make a normal distribution, with a shifting mean
  mean_moving_normal = tf.random.normal(shape=[1000], mean=(5*k), stddev=1)
  # Record that distribution into a histogram summary
  histogram_summary.op("normal/moving_mean",
                       mean_moving_normal,
                       description="A normal distribution whose mean changes "
                                   "over time.")

  # Make a normal distribution with shrinking variance
  shrinking_normal = tf.random.normal(shape=[1000], mean=0, stddev=1-(k))
  # Record that distribution too
  histogram_summary.op("normal/shrinking_variance", shrinking_normal,
                       description="A normal distribution whose variance "
                                   "shrinks over time.")

  # Let's combine both of those distributions into one dataset
  normal_combined = tf.concat([mean_moving_normal, shrinking_normal], 0)
  # We add another histogram summary to record the combined distribution
  histogram_summary.op("normal/bimodal", normal_combined,
                       description="A combination of two normal distributions, "
                                   "one with a moving mean and one with  "
                                   "shrinking variance. The result is a "
                                   "distribution that starts as unimodal and "
                                   "becomes more and more bimodal over time.")

  # Add a gamma distribution
  gamma = tf.random.gamma(shape=[1000], alpha=k)
  histogram_summary.op("gamma", gamma,
                       description="A gamma distribution whose shape "
                                   "parameter, α, changes over time.")

  # And a poisson distribution
  poisson = tf.compat.v1.random_poisson(shape=[1000], lam=k)
  histogram_summary.op("poisson", poisson,
                       description="A Poisson distribution, which only "
                                   "takes on integer values.")

  # And a uniform distribution
  uniform = tf.random.uniform(shape=[1000], maxval=k*10)
  histogram_summary.op("uniform", uniform,
                       description="A simple uniform distribution.")

  # Finally, combine everything together!
  all_distributions = [mean_moving_normal, shrinking_normal,
                       gamma, poisson, uniform]
  all_combined = tf.concat(all_distributions, 0)
  histogram_summary.op("all_combined", all_combined,
                       description="An amalgamation of five distributions: a "
                                   "uniform distribution, a gamma "
                                   "distribution, a Poisson distribution, and "
                                   "two normal distributions.")

  summaries = tf.compat.v1.summary.merge_all()

  # Setup a session and summary writer
  sess = tf.compat.v1.Session()
  writer = tf.summary.FileWriter(logdir)

  # Setup a loop and write the summaries to disk
  N = num_summaries
  for step in xrange(N):
    k_val = step/float(N)
    summ = sess.run(summaries, feed_dict={k: k_val})
    writer.add_summary(summ, global_step=step)
922815
def fit(self, X):
        """"""
        min_ = X.min() - EPSILON
        max_ = X.max() + EPSILON
        self.mean = X.mean()
        self.std = X.std()

        super().fit(X, min_, max_)
707587
def DatabaseDirectorySize(root_path, extension):
  """"""
  directories = collections.deque([root_path])
  total_size = 0
  total_files = 0
  while directories:
    directory = directories.popleft()
    try:
      items = os.listdir(directory)
    except OSError:
      continue
    for comp in items:
      path = os.path.join(directory, comp)
      try:
        statinfo = os.lstat(path)
        if stat.S_ISLNK(statinfo.st_mode):
          continue
        if stat.S_ISDIR(statinfo.st_mode):
          directories.append(path)
        elif stat.S_ISREG(statinfo.st_mode):
          if comp.endswith(extension):
            total_size += statinfo.st_size
            total_files += 1
      except OSError:
        continue
  return total_size, total_files
1081573
def get_size(self):
        """"""
        self.curses.setupterm()
        return self.curses.tigetnum('cols'), self.curses.tigetnum('lines')
1143328
def sample_hgd(in_range, out_range, nsample, seed_coins):
    """"""
    in_size = in_range.size()
    out_size = out_range.size()
    assert in_size > 0 and out_size > 0
    assert in_size <= out_size
    assert out_range.contains(nsample)

    # 1-based index of nsample in out_range
    nsample_index = nsample - out_range.start + 1
    if in_size == out_size:
        # Input and output domains have equal size
        return in_range.start + nsample_index - 1

    in_sample_num = HGD.rhyper(nsample_index, in_size, out_size - in_size, seed_coins)
    if in_sample_num == 0:
        return in_range.start
    else:
        in_sample = in_range.start + in_sample_num - 1
        assert in_range.contains(in_sample)
        return in_sample
204166
def rweibull(alpha, beta, size=None):
    
    tmp = -np.log(runiform(0, 1, size))
    return beta * (tmp ** (1. / alpha))
164289
function sample(alpha, beta) {
    var u = jStat.randg(alpha);
    return u / (u + jStat.randg(beta));
  }
565501
def stratified_sample_raster(strata_data, target_sample_size=30, min_sample_proportion=0.1):
    
    with rasterio.open(strata_data) as src:
        strata = src.read().flatten()
    index_array = np.arange(strata.size)

    # construct a dictionary of lists,
    # keys are stratum ids
    # values are list of indices
    sample = dict([(int(s),[]) for s in np.unique(strata)])
    satisfied = []

    # counts for proportion-based constraints
    bins = np.bincount(strata)
    ii = np.nonzero(bins)[0]
    stratum_count = dict(zip(ii,bins[ii]))

    # shuffle the indices and loop until the sample satisfied our constraints
    np.random.shuffle(index_array)
    for idx in index_array:
        stratum = strata[index_array[idx]]
        if stratum in satisfied:
            continue
        sample[stratum].append(idx)
        nsamples = len(sample[stratum])
        # constraints -> hit the target sample size OR proportion of total
        # (whichever is highest)
        target = stratum_count[stratum] * min_sample_proportion
        if target < target_sample_size:
            target = target_sample_size
        if nsamples >= target:
            satisfied.append(stratum)
        if len(satisfied) == len(sample.keys()):
            break

    # convert sampled indicies into a list of indicies
    selected = []
    for k, v in sample.items():
        # check for stratum with < target sample size
        if len(v) < target_sample_size:
            # if we have too few samples, drop them
            #warnings.warn("Stratum %s has only %d samples, dropped" % (k, len(v)))
            pass
        else:
            selected.extend(v)

    return np.array(selected)
1160423
def calculate_size(name, include_value, local_only):
    
    data_size = 0
    data_size += calculate_size_str(name)
    data_size += BOOLEAN_SIZE_IN_BYTES
    data_size += BOOLEAN_SIZE_IN_BYTES
    return data_size
1192375
def _PopulateQuantilesHistogram(self, hist, nums):
    
    if not nums:
      return
    num_quantile_buckets = 10
    quantiles_to_get = [
        x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1)
    ]
    quantiles = np.percentile(nums, quantiles_to_get)
    hist.type = self.histogram_proto.QUANTILES
    quantiles_sample_count = float(len(nums)) / num_quantile_buckets
    for low, high in zip(quantiles, quantiles[1:]):
      hist.buckets.add(
          low_value=low, high_value=high, sample_count=quantiles_sample_count)
529059
def calculate_size(name, batch_size):
    
    data_size = 0
    data_size += calculate_size_str(name)
    data_size += INT_SIZE_IN_BYTES
    return data_size
1035077
def _sample(self, position, stepsize):
        

        # Re-sampling momentum
        momentum = np.random.normal(0, 1, len(position))

        # Initializations
        depth = 0
        position_backward, position_forward = position, position
        momentum_backward, momentum_forward = momentum, momentum
        candidate_set_size = accept_set_bool = 1
        _, log_pdf = self.grad_log_pdf(position, self.model).get_gradient_log_pdf()

        # Resample slice variable `u`
        slice_var = np.random.uniform(0, np.exp(log_pdf - 0.5 * np.dot(momentum, momentum)))

        while accept_set_bool == 1:
            direction = np.random.choice([-1, 1], p=[0.5, 0.5])
            if direction == -1:
                # Build a tree in backward direction
                (position_backward, momentum_backward, _, _, position_bar,
                 candidate_set_size2, accept_set_bool2) = self._build_tree(position_backward, momentum_backward,
                                                                           slice_var, direction, depth, stepsize)
            else:
                # Build tree in forward direction
                (_, _, position_forward, momentum_forward, position_bar,
                 candidate_set_size2, accept_set_bool2) = self._build_tree(position_forward, momentum_forward,
                                                                           slice_var, direction, depth, stepsize)
            if accept_set_bool2 == 1:
                if np.random.rand() < candidate_set_size2 / candidate_set_size:
                    position = position_bar.copy()

            accept_set_bool, candidate_set_size = self._update_acceptance_criteria(position_forward, position_backward,
                                                                                   momentum_forward, momentum_backward,
                                                                                   accept_set_bool2, candidate_set_size,
                                                                                   candidate_set_size2)
            depth += 1

        return position
688513
def _calc_size(self):
        
        return sum(os.path.getsize(filename)
            for filename in self.walk()
        )
160630
def branchScale(self):
        """"""
        bs = -(self.Phi_x * scipy.diagonal(self.Pxy[0])).sum() * self.mu
        assert bs > 0
        return bs