text:
"""funcutils.py -- Subroutines that tabulate a function's values.

Convenience functions that evaluate a python function on a grid of
points and tabulate the output to be used with Gnuplot.

"""

__cvs_version__ = '$Revision: 2.5 $'

import Numeric

import gplot as Gnuplot, utils

def tabulate_function(f, xvals, yvals=None, typecode=None, ufunc=0):
    """Evaluate and tabulate a function on a 1- or 2-D grid of points.

    f should be a function taking one or two floating-point
    parameters.

    If f takes one parameter, then xvals should be a 1-D array and
    yvals should be None.  The return value is a Numeric array
    '[f(x[0]), f(x[1]), ..., f(x[-1])]'.

    If f takes two parameters, then 'xvals' and 'yvals' should each be
    1-D arrays listing the values of x and y at which 'f' should be
    tabulated.  The return value is a matrix M where 'M[i,j] =
    f(xvals[i],yvals[j])', which can for example be used in the
    'GridData' constructor.

    If 'ufunc=0', then 'f' is evaluated at each point using a Python
    loop.  This can be slow if the number of points is large.  If
    speed is an issue, you should write 'f' in terms of Numeric ufuncs
    and use the 'ufunc=1' feature described next.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs (i.e., a function that can operate
    element-by-element on whole matrices).  It will be passed the
    xvals and yvals as rectangular matrices.

    """

    if yvals is None:
        # f is a function of only one variable:
        xvals = Numeric.asarray(xvals, typecode)

        if ufunc:
            return f(xvals)
        else:
            if typecode is None:
                typecode = xvals.typecode()

            m = Numeric.zeros((len(xvals),), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                m[xi] = f(x)
            return m
    else:
        # f is a function of two variables:
        xvals = Numeric.asarray(xvals, typecode)
        yvals = Numeric.asarray(yvals, typecode)

        if ufunc:
            return f(xvals[:,Numeric.NewAxis], yvals[Numeric.NewAxis,:])
        else:
            if typecode is None:
                # choose a result typecode based on what '+' would return
                # (yecch!):
                typecode = (Numeric.zeros((1,), xvals.typecode()) +
                            Numeric.zeros((1,), yvals.typecode())).typecode()

            m = Numeric.zeros((len(xvals), len(yvals)), typecode)
            for xi in range(len(xvals)):
                x = xvals[xi]
                for yi in range(len(yvals)):
                    y = yvals[yi]
                    m[xi,yi] = f(x,y)
            return m

# For backwards compatibility:
grid_function = tabulate_function

def compute_Data(xvals, f, ufunc=0, **keyw):
    """Evaluate a function of 1 variable and store the results in a Data.

    Computes a function f of one variable on a set of specified points
    using 'tabulate_function', then store the results into a 'Data' so
    that it can be plotted.  After calculation, the data are written
    to a file; no copy is kept in memory.  Note that this is quite
    different than 'Func' (which tells gnuplot to evaluate the
    function).

    Arguments:

        'xvals' -- a 1-d array with dimension 'numx'

        'f' -- the function to plot--a callable object for which
            f(x) returns a number.

        'ufunc=<bool>' -- evaluate 'f' as a ufunc?

    Other keyword arguments are passed through to the Data
    constructor.

    'f' should be a callable object taking one argument.  'f(x)' will
    be computed at all values in xvals.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs, and it will be passed the 'xvals' and
    'yvals' as rectangular matrices.

    Thus if you have a function 'f', a vector 'xvals', and a Gnuplot
    instance called 'g', you can plot the function by typing
    'g.splot(compute_Data(xvals, f))'.

    """

    xvals = utils.float_array(xvals)

    # evaluate function:
    data = tabulate_function(f, xvals, ufunc=ufunc)

    return apply(Gnuplot.Data, (xvals, data), keyw)

def compute_GridData(xvals, yvals, f, ufunc=0, **keyw):
    """Evaluate a function of 2 variables and store the results in a GridData.

    Computes a function 'f' of two variables on a rectangular grid
    using 'tabulate_function', then store the results into a
    'GridData' so that it can be plotted.  After calculation the data
    are written to a file; no copy is kept in memory.  Note that this
    is quite different than 'Func' (which tells gnuplot to evaluate
    the function).

    Arguments:

        'xvals' -- a 1-d array with dimension 'numx'

        'yvals' -- a 1-d array with dimension 'numy'

        'f' -- the function to plot--a callable object for which
            'f(x,y)' returns a number.

        'ufunc=<bool>' -- evaluate 'f' as a ufunc?

     Other keyword arguments are passed to the 'GridData' constructor.

    'f' should be a callable object taking two arguments.
    'f(x,y)' will be computed at all grid points obtained by
    combining elements from 'xvals' and 'yvals'.

    If called with 'ufunc=1', then 'f' should be a function that is
    composed entirely of ufuncs, and it will be passed the 'xvals' and
    'yvals' as rectangular matrices.

    Thus if you have a function 'f' and two vectors 'xvals' and
    'yvals' and a Gnuplot instance called 'g', you can plot the
    function by typing 'g.splot(compute_GridData(f, xvals, yvals))'.

    """

    xvals = utils.float_array(xvals)
    yvals = utils.float_array(yvals)

    # evaluate function:
    data = tabulate_function(f, xvals, yvals, ufunc=ufunc)

    return apply(Gnuplot.GridData, (data, xvals, yvals), keyw)

# For backwards compatibility:
def GridFunc(f, xvals, yvals, **keyw):
    return apply(compute_GridData, (xvals, yvals, f,), keyw)


text:
#pragma once

namespace folly {

template <typename T, typename CT, typename C>
TimeseriesHistogram<T, CT, C>::TimeseriesHistogram(
    ValueType bucketSize,
    ValueType min,
    ValueType max,
    const ContainerType& copyMe)
    : buckets_(bucketSize, min, max, copyMe) {}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::addValue(
    TimePoint now, const ValueType& value) {
  buckets_.getByValue(value).addValue(now, value);
}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::addValue(
    TimePoint now, const ValueType& value, uint64_t times) {
  buckets_.getByValue(value).addValue(now, value, times);
}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::addValues(
    TimePoint now, const folly::Histogram<ValueType>& hist) {
  CHECK_EQ(hist.getMin(), getMin());
  CHECK_EQ(hist.getMax(), getMax());
  CHECK_EQ(hist.getBucketSize(), getBucketSize());
  CHECK_EQ(hist.getNumBuckets(), getNumBuckets());

  for (size_t n = 0; n < hist.getNumBuckets(); ++n) {
    const typename folly::Histogram<ValueType>::Bucket& histBucket =
        hist.getBucketByIndex(n);
    Bucket& myBucket = buckets_.getByIndex(n);
    myBucket.addValueAggregated(now, histBucket.sum, histBucket.count);
  }
}

template <typename T, typename CT, typename C>
T TimeseriesHistogram<T, CT, C>::getPercentileEstimate(
    double pct, size_t level) const {
  return buckets_.getPercentileEstimate(
      pct / 100.0, CountFromLevel(level), AvgFromLevel(level));
}

template <typename T, typename CT, typename C>
T TimeseriesHistogram<T, CT, C>::getPercentileEstimate(
    double pct, TimePoint start, TimePoint end) const {
  return buckets_.getPercentileEstimate(
      pct / 100.0,
      CountFromInterval(start, end),
      AvgFromInterval<T>(start, end));
}

template <typename T, typename CT, typename C>
size_t TimeseriesHistogram<T, CT, C>::getPercentileBucketIdx(
    double pct, size_t level) const {
  return buckets_.getPercentileBucketIdx(pct / 100.0, CountFromLevel(level));
}

template <typename T, typename CT, typename C>
size_t TimeseriesHistogram<T, CT, C>::getPercentileBucketIdx(
    double pct, TimePoint start, TimePoint end) const {
  return buckets_.getPercentileBucketIdx(
      pct / 100.0, CountFromInterval(start, end));
}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::clear() {
  for (size_t i = 0; i < buckets_.getNumBuckets(); i++) {
    buckets_.getByIndex(i).clear();
  }
}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::update(TimePoint now) {
  for (size_t i = 0; i < buckets_.getNumBuckets(); i++) {
    buckets_.getByIndex(i).update(now);
  }
}

template <typename T, typename CT, typename C>
std::string TimeseriesHistogram<T, CT, C>::getString(size_t level) const {
  std::string result;

  for (size_t i = 0; i < buckets_.getNumBuckets(); i++) {
    if (i > 0) {
      toAppend(",", &result);
    }
    const ContainerType& cont = buckets_.getByIndex(i);
    toAppend(
        buckets_.getBucketMin(i),
        ":",
        cont.count(level),
        ":",
        cont.template avg<ValueType>(level),
        &result);
  }

  return result;
}

template <typename T, typename CT, typename C>
std::string TimeseriesHistogram<T, CT, C>::getString(
    TimePoint start, TimePoint end) const {
  std::string result;

  for (size_t i = 0; i < buckets_.getNumBuckets(); i++) {
    if (i > 0) {
      toAppend(",", &result);
    }
    const ContainerType& cont = buckets_.getByIndex(i);
    toAppend(
        buckets_.getBucketMin(i),
        ":",
        cont.count(start, end),
        ":",
        cont.avg(start, end),
        &result);
  }

  return result;
}

template <class T, class CT, class C>
void TimeseriesHistogram<T, CT, C>::computeAvgData(
    ValueType* total, uint64_t* nsamples, size_t level) const {
  for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
    const auto& levelObj = buckets_.getByIndex(b).getLevel(level);
    *total += levelObj.sum();
    *nsamples += levelObj.count();
  }
}

template <class T, class CT, class C>
void TimeseriesHistogram<T, CT, C>::computeAvgData(
    ValueType* total,
    uint64_t* nsamples,
    TimePoint start,
    TimePoint end) const {
  for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
    const auto& levelObj = buckets_.getByIndex(b).getLevel(start);
    *total += levelObj.sum(start, end);
    *nsamples += levelObj.count(start, end);
  }
}

template <typename T, typename CT, typename C>
void TimeseriesHistogram<T, CT, C>::computeRateData(
    ValueType* total, Duration* elapsed, size_t level) const {
  for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
    const auto& levelObj = buckets_.getByIndex(b).getLevel(level);
    *total += levelObj.sum();
    *elapsed = std::max(*elapsed, levelObj.elapsed());
  }
}

template <class T, class CT, class C>
void TimeseriesHistogram<T, CT, C>::computeRateData(
    ValueType* total, Duration* elapsed, TimePoint start, TimePoint end) const {
  for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
    const auto& level = buckets_.getByIndex(b).getLevel(start);
    *total += level.sum(start, end);
    *elapsed = std::max(*elapsed, level.elapsed(start, end));
  }
}

} // namespace folly

redpajama_set_name: RedPajamaGithub


text:
(function(ns) {
    var ast = require("./ast");

    function Builder() {
        this.init();
    }

    Object.defineProperties(Builder.prototype, {
        _root: {value: null, writable: true},
        _stack: {value: null, writable: true},
        // _references structure is:
        // {
        //     <label>: [<reference>*]
        // }
        _references: {value: null, writable: true},
        _placeholderProperty: {value: Object.create(null)},

        init: {
            value: function() {
                this._references = Object.create(null);
                this._root = new ast.Root();
                this._stack = [this._root];

                return this;
            }
        },

        cleanup: {
            value: function() {
                this._references = null;
                this._root = null;
                this._stack = null;
            }
        },

        getExternalReferences: {
            value: function(oldLabel, newLabel) {
                var references = this._references,
                    root = this._root,
                    externalReferences = [];

                for (var label in references) {
                    // placeholder properties are not created at reference creation
                    // time, so we need to check for both states, before a
                    // placeholder is created and after.
                    if (!root.hasProperty(label) ||
                        root.getProperty(label) === this._placeholderProperty) {
                        externalReferences.push(label);
                    }
                }

                return externalReferences;
            }
        },

        relabelReferences: {
            value: function(oldLabel, newLabel) {
                var references = this._references[oldLabel];

                if (references) {
                    references = references.slice(0);
                    for (var i = 0, ii = references.length; i < ii; i++) {
                        references[i].value = newLabel;
                    }
                }
            }
        },

        _registerReference: {
            value: function(reference) {
                var references = this._references,
                    label = reference.value;

                if (references[label]) {
                    references[label].push(reference);
                } else {
                    references[label] = [reference];
                }
            }
        },

        _unregisterReference: {
            value: function(reference) {
                var label = reference.label,
                    labelReferences = this._references[label],
                    ix;

                if (labelReferences.length === 1) {
                    delete this._references[label];
                } else {
                    ix = labelReferences.indexOf(reference);

                    if (ix === -1) {
                        console.log("BUG: reference '" + label + "' not found in registry.");
                    } else {
                        labelReferences.splice(ix, 1);
                    }
                }
            }
        },

        _createPlaceholdersForReferences: {
            value: function() {
                var references = this._references,
                    root = this._root;

                for (var label in references) {
                    if (!root.hasProperty(label)) {
                        root.setProperty(label, this._placeholderProperty);
                    }
                }
            }
        },

        getSerialization: {
            value: function(indent) {
                this._createPlaceholdersForReferences();

                return this._root.serialize(indent);
            }
        },

        root: {
            get: function() {
                return this._root;
            }
        },

        top: {
            get: function() {
                return this._stack[0];
            }
        },

        push: {
            value: function(value) {
                return this._stack.unshift(value);
            }
        },

        pop: {
            value: function() {
                return this._stack.shift();
            }
        },

        createObjectLiteral: {
            value: function() {
                return new ast.ObjectLiteral(this._root, Object.create(null));
            }
        },

        createArray: {
            value: function() {
                return new ast.ObjectLiteral(this._root, []);
            }
        },

        createObjectReference: {
            value: function(label) {
                var reference = new ast.ObjectReference(this._root, label);

                this._registerReference(reference);

                return reference;
            }
        },

        createRegExp: {
            value: function(regexp) {
                return new ast.RegExpObject(this._root, regexp);
            }
        },

        createString: {
            value: function(string) {
                return new ast.Value(this._root, string);
            }
        },

        createNumber: {
            value: function(number) {
                return new ast.Value(this._root, number);
            }
        },

        createBoolean: {
            value: function(boolean) {
                return new ast.Value(this._root, boolean);
            }
        },

        createNull: {
            value: function(boolean) {
                return new ast.Value(this._root, null);
            }
        },

        createCustomObject: {
            value: function() {
                return new ast.CustomObject(this._root);
            }
        }
    });

    ns.Builder = Builder;
})(exports);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="5dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/reply_textView"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="5dp"
        android:fadeScrollbars="false"
        android:scrollHorizontally="true"
        android:text="@string/reply_group"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textSize="14sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/replyLocation"
            android:layout_width="10dp"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/reply_time_textView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/reply_time_textView"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/reply_time_textView"
            android:layout_width="151dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:gravity="right"
            android:text="@string/time"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="13sp" />

    </RelativeLayout>

    <TextView
        android:id="@+id/replyAuthor_textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:text="@string/author_name"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


text:
from django.contrib import messages
from django.core.paginator import InvalidPage
from django.utils.http import urlquote
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import DetailView, TemplateView
from django.utils.translation import ugettext_lazy as _
from oscar.core.loading import get_class, get_model
from oscar.apps.catalogue.signals import product_viewed
from django.http import HttpResponse

Product = get_model('catalogue', 'product')
ProductReview = get_model('reviews', 'ProductReview')
Category = get_model('catalogue', 'category')
ProductAlert = get_model('customer', 'ProductAlert')
ProductAlertForm = get_class('customer.forms', 'ProductAlertForm')
get_product_search_handler_class = get_class(
    'catalogue.search_handlers', 'get_product_search_handler_class')

class ProductDetailView(DetailView):
    context_object_name = 'product'
    model = Product
    view_signal = product_viewed
    template_folder = "catalogue"

    # Whether to redirect to the URL with the right path
    enforce_paths = True

    # Whether to redirect child products to their parent's URL
    enforce_parent = True

    def get(self, request, **kwargs):
        """
        Ensures that the correct URL is used before rendering a response
        """
        self.object = product = self.get_object()

        redirect = self.redirect_if_necessary(request.path, product)
        if redirect is not None:
            return redirect

        response = super(ProductDetailView, self).get(request, **kwargs)
        self.send_signal(request, response, product)
        return response

    def get_object(self, queryset=None):
        # Check if self.object is already set to prevent unnecessary DB calls
        if hasattr(self, 'object'):
            return self.object
        else:
            return super(ProductDetailView, self).get_object(queryset)

    def redirect_if_necessary(self, current_path, product):
        if self.enforce_parent and product.is_child:
            return HttpResponsePermanentRedirect(
                product.parent.get_absolute_url())

        if self.enforce_paths:
            expected_path = product.get_absolute_url()
            if expected_path != urlquote(current_path):
                return HttpResponsePermanentRedirect(expected_path)

    def get_context_data(self, **kwargs):
        ctx = super(ProductDetailView, self).get_context_data(**kwargs)

        products = Product.objects.order_by('-rating')[:6]
        ctx['top_products'] = products

        ctx['reviews'] = self.get_reviews()
        ctx['alert_form'] = self.get_alert_form()
        ctx['has_active_alert'] = self.get_alert_status()
        return ctx

    def get_alert_status(self):
        # Check if this user already have an alert for this product
        has_alert = False
        if self.request.user.is_authenticated():
            alerts = ProductAlert.objects.filter(
                product=self.object, user=self.request.user,
                status=ProductAlert.ACTIVE)
            has_alert = alerts.exists()
        return has_alert

    def get_alert_form(self):
        return ProductAlertForm(
            user=self.request.user, product=self.object)

    def get_reviews(self):
        return self.object.reviews.filter(status=ProductReview.APPROVED)

    def send_signal(self, request, response, product):
        self.view_signal.send(
            sender=self, product=product, user=request.user, request=request,
            response=response)

    def get_template_names(self):
        """
        Return a list of possible templates.

        If an overriding class sets a template name, we use that. Otherwise,
        we try 2 options before defaulting to catalogue/detail.html:
            1). detail-for-upc-<upc>.html
            2). detail-for-class-<classname>.html

        This allows alternative templates to be provided for a per-product
        and a per-item-class basis.
        """
        if self.template_name:
            return [self.template_name]

        return [
            '%s/detail-for-upc-%s.html' % (
                self.template_folder, self.object.upc),
            '%s/detail-for-class-%s.html' % (
                self.template_folder, self.object.get_product_class().slug),
            '%s/detail.html' % (self.template_folder)]

class CatalogueView(TemplateView):

    """
    Browse all products in the catalogue
    """

    context_object_name = "products"
    template_name = 'catalogue/browse.html'

    def get(self, request, *args, **kwargs):
        try:
            self.search_handler = self.get_search_handler(
                self.request.GET, request.get_full_path(), [])
        except InvalidPage:
            # Redirect to page one.
            messages.error(request, _('The given page number was invalid.'))
            return redirect('catalogue:index')
        return super(CatalogueView, self).get(request, *args, **kwargs)

    def get_search_handler(self, *args, **kwargs):
        return get_product_search_handler_class()(*args, **kwargs)

    def get_context_data(self, **kwargs):
        products = Product.objects.order_by('-rating')[:6]
        ctx = {}
        ctx['top_products'] = products
        ctx['summary'] = "All products"
        search_context = self.search_handler.get_search_context_data(
            self.context_object_name)
        ctx.update(search_context)
        return ctx

class ProductCategoryView(TemplateView):

    """
    Browse products in a given category
    """
    context_object_name = "products"
    template_name = 'catalogue/category.html'
    enforce_paths = True

    def get(self, request, *args, **kwargs):

       # return HttpResponse(get_category())

        # Fetch the category; return 404 or redirect as needed
        self.category = self.get_category()

        potential_redirect = self.redirect_if_necessary(
            request.path, self.category)
        if potential_redirect is not None:
            return potential_redirect

        try:
            self.search_handler = self.get_search_handler(
                request.GET, request.get_full_path(), self.get_categories())
        except InvalidPage:
            messages.error(request, _('The given page number was invalid.'))
            return redirect(self.category.get_absolute_url())

        return super(ProductCategoryView, self).get(request, *args, **kwargs)

    def get_category(self):
        if 'pk' in self.kwargs:
            # Usual way to reach a category page. We just look at the primary
            # key in case the slug changed. If it did, get() will redirect
            # appropriately
            filters = {'pk': self.kwargs['pk']}
        else:
            # For SEO reasons, we allow chopping off bits of the URL. If that
            # happened, no primary key will be available.
            filters = {'slug': self.kwargs['category_slug']}
        return get_object_or_404(Category, **filters)

    def redirect_if_necessary(self, current_path, category):
        if self.enforce_paths:
            # Categories are fetched by primary key to allow slug changes.
            # If the slug has changed, issue a redirect.
            expected_path = category.get_absolute_url()
            if expected_path != urlquote(current_path):
                return HttpResponsePermanentRedirect(expected_path)

    def get_search_handler(self, *args, **kwargs):
        return get_product_search_handler_class()(*args, **kwargs)

    def get_categories(self):
        """
        Return a list of the current category and its ancestors
        """
        return self.category.get_descendants_and_self()

    def get_context_data(self, **kwargs):
        context = super(ProductCategoryView, self).get_context_data(**kwargs)

        products = Product.objects.order_by('-rating')[:6]
        context['top_products'] = products

        context['category'] = self.category
        search_context = self.search_handler.get_search_context_data(
            self.context_object_name)
        context.update(search_context)
        return context


text:
@interface BBBEmbeddedRequestHandlerTests : XCTestCase
@end

@implementation BBBEmbeddedRequestHandlerTests

+ (void) setUp{
    [NSURLProtocol registerClass:[BBBHTTPURLProtocol class]];
}

+ (void) tearDown{
    [NSURLProtocol unregisterClass:[BBBHTTPURLProtocol class]];
}

- (void) testReaderRequest{
    NSURL *readerJSURL = [NSURL URLWithString:@"http://localhost:55555/lib/reader.js"];

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:readerJSURL];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response
                                      error:&error];

    XCTAssertEqual(response.statusCode, 200);
    XCTAssertNil(error);

}

- (void) testMissingEmbeddedRequest {
    NSURL *readerJSURL = [NSURL URLWithString:@"http://localhost:55555/lib/unknown.file"];

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:readerJSURL];

    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response
                                      error:&error];

    XCTAssertEqual(response.statusCode, BBBURLProtocolStatusCodeNotFound);

}

@end


text:
from django.apps import AppConfig

from nodeconductor.structure import SupportedServices

class SaltStackConfig(AppConfig):
    name = 'nodeconductor_saltstack.sharepoint'
    verbose_name = 'SaltStack SharePoint'
    service_name = 'SaltStack'

    def ready(self):
        from .backend import SharepointBackend
        SupportedServices.register_backend(SharepointBackend, nested=True)


text:
package jp.kotmw.splatoon.commands;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import jp.kotmw.splatoon.gamedatas.ArenaData;
import jp.kotmw.splatoon.gamedatas.DataStore;
import jp.kotmw.splatoon.gamedatas.DataStore.RankingPattern;
import jp.kotmw.splatoon.gamedatas.WaitRoomData;
import jp.kotmw.splatoon.maingame.MainGame;

public class PlayerCommands extends CommandLib {

	@Override
	public boolean onCommand(CommandSender sender, Command command, String arg2, String[] args) {
		if(!(sender instanceof Player))
			return false;
		player = (Player)sender;
		if(args.length == 0) {
			sendMsg(MainGame.Prefix);
			sendMsgs("-----Player Command List-----"
			,"/splat join <room> [player]"
			,"/splat leave"
			,"/splat roomlist"
			,"/splat arenalist"
			,"/splat rank <win/lose/rank/rate/totalpaint/maxwinstreak>"
			,"------------------------------");
			return true;
		} else if(args.length == 1) {
			if("leave".equalsIgnoreCase(args[0]))
				MainGame.leave(player);
			else if("roomlist".equalsIgnoreCase(args[0])) {
				sendPMsg(ChatColor.GREEN+"待機部屋一覧");
				for(WaitRoomData room : DataStore.getRoomList())
					sendMsg("- "+room.getName()+ChatColor.GREEN+" | "
				+ChatColor.WHITE+
				DataStore.getRoomPlayersList(room.getName()).size()+" / "+(room.isLimitBreak() ? "∞ "+ChatColor.RED.toString()+ChatColor.BOLD.toString()+ChatColor.UNDERLINE.toString()+ChatColor.ITALIC+"LIMIT BREAKING ROOM" : "8"));
			} else if("arenalist".equalsIgnoreCase(args[0])) {
				sendPMsg(ChatColor.GREEN+"ステージ一覧");
				for(ArenaData room : DataStore.getArenaList()) sendMsg("- "+room.getName()+" "+room.getGameStatus().getStats());
			}
		} else if(args.length == 2) {
			if("join".equalsIgnoreCase(args[0])) {
				if(!DataStore.hasRoomData(args[1])) {
					sendPMsg(ChatColor.RED+"その待機部屋は存在しません");
					return false;
				}
				MainGame.join(player, DataStore.getRoomData(args[1]));
				return true;
			} else if("rank".equalsIgnoreCase(args[0])) {
				RankingPattern pattern = getPattern(args[1]);
				if(pattern == null) {
					sendPMsg(ChatColor.RED+"そのランキングは存在しません");
					return false;
				}
				int i = 1;
				sendMsg(ChatColor.GREEN.toString()+ChatColor.STRIKETHROUGH+"---------------"+ChatColor.WHITE+"[ Ranking ]"+ChatColor.GREEN.toString()+ChatColor.STRIKETHROUGH+"---------------");
				sendMsg(ChatColor.AQUA.toString()+ ChatColor.BOLD + pattern.getText() +ChatColor.WHITE+ " のランキングは以下の通りです");
				for(String ranking : DataStore.getRanking(pattern)) {
					if(i >= 10)
						break;
					sendMsg(ranking);
					i++;
				}
				sendMsg(ChatColor.GREEN.toString()+ChatColor.STRIKETHROUGH+"----------------------------------------");
			} else if("spectate".equalsIgnoreCase(args[0])) {

			}
		} else if(args.length == 3) {
			if("join".equalsIgnoreCase(args[0])) {
				if(!DataStore.hasRoomData(args[1])) {
					sendPMsg(ChatColor.RED+"その待機部屋は存在しません");
					return false;
				}
				String target = args[2];
				Player targetPlayer = getPlayer(target);
				if(target.equalsIgnoreCase("@p"))
					targetPlayer = player;
				else if(target.equalsIgnoreCase("@r"))
					targetPlayer = getRandomPlayer();
				else if(target.equalsIgnoreCase("@a")) {
					sendPMsg(ChatColor.GREEN+"人数がはみ出た場合はそのプレイヤーは弾かれます");
					Bukkit.getOnlinePlayers().forEach(players -> MainGame.join(players, DataStore.getRoomData(args[1])));
					return true;
				}
				if(targetPlayer == null) {
					sendPMsg(ChatColor.RED+"指定したプレイヤーが存在しません");
					return false;
				}
				MainGame.join(targetPlayer, DataStore.getRoomData(args[1]));
				return false;
			}
		}
		return false;
	}

	public RankingPattern getPattern(String pattern) {
		for(RankingPattern pattern2 : RankingPattern.values())
			if(pattern2.toString().equalsIgnoreCase(pattern))
				return pattern2;
		return null;
	}
}


text:
package directory

import (
	"context"
	"time"

	"github.com/golang/protobuf/proto" //nolint:staticcheck
	tpb "github.com/google/trillian"
	"github.com/google/trillian/crypto/keyspb"
)

// Directory stores configuration information for a single Key Transparency instance.
type Directory struct {
	DirectoryID string
	Map         *tpb.Tree
	Log         *tpb.Tree
	VRF         *keyspb.PublicKey

	VRFPriv                  proto.Message
	MinInterval, MaxInterval time.Duration
	// TODO(gbelvin): specify mutation function
	Deleted          bool
	DeletedTimestamp time.Time
}

// Storage is an interface for storing multi-tenant configuration information.
type Storage interface {
	// List returns the full list of directories.
	List(ctx context.Context, deleted bool) ([]*Directory, error)
	// Write stores a new instance to storage.
	Write(ctx context.Context, d *Directory) error
	// Read a configuration from storage.
	Read(ctx context.Context, directoryID string, showDeleted bool) (*Directory, error)
	// Soft-delete or undelete the directory
	SetDelete(ctx context.Context, directoryID string, isDeleted bool) error
	// HardDelete the directory.
	Delete(ctx context.Context, directoryID string) error
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SourceAttribute (AWS SDK for Java - 1.10.27)</title>
<meta name="date" content="2015-10-15">
<link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Index

Help

        <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/>
        <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/>

              Search

            <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java">

                    <input id="nav-searchfield" name="searchQuery">

                <input alt="" id="nav-search-button-inner" type="image">

              <input name="searchPath" type="hidden" value="documentation-guide" />
              <input name="this_doc_product" type="hidden" value="AWS SDK for Java" />
              <input name="this_doc_guide" type="hidden" value="API Reference" />
              <input name="doc_locale" type="hidden" value="en_us" />
            </form>

Did this page help you?

                  Yes
            No
            Tell us about it...

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.amazonaws.services.cloudsearch.model

Class SourceAttribute

java.lang.Object

com.amazonaws.services.cloudsearch.model.SourceAttribute

All Implemented Interfaces:

java.io.Serializable

Deprecated.

@Deprecated
public class SourceAttribute
extends java.lang.Object
implements java.io.Serializable

 Identifies the source data for an index field. An optional data transformation can be applied to the source data when populating the index field. By
 default, the value of the source attribute is copied to the index field.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

SourceAttribute()

Deprecated.

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

Deprecated.

SourceData
getSourceDataCopy()

Deprecated.

Copies data from a source document attribute to an
 IndexField.

java.lang.String
getSourceDataFunction()

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

SourceDataMap
getSourceDataMap()

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

SourceDataTrimTitle
getSourceDataTrimTitle()

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField.

int
hashCode()

Deprecated.

void
setSourceDataCopy(SourceData sourceDataCopy)

Deprecated.

Copies data from a source document attribute to an
 IndexField.

void
setSourceDataFunction(SourceDataFunction sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

void
setSourceDataFunction(java.lang.String sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

void
setSourceDataMap(SourceDataMap sourceDataMap)

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

void
setSourceDataTrimTitle(SourceDataTrimTitle sourceDataTrimTitle)

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField.

java.lang.String
toString()

Deprecated.

Returns a string representation of this object; useful for testing and
 debugging.

SourceAttribute
withSourceDataCopy(SourceData sourceDataCopy)

Deprecated.

Copies data from a source document attribute to an
 IndexField.

SourceAttribute
withSourceDataFunction(SourceDataFunction sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

SourceAttribute
withSourceDataFunction(java.lang.String sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

SourceAttribute
withSourceDataMap(SourceDataMap sourceDataMap)

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

SourceAttribute
withSourceDataTrimTitle(SourceDataTrimTitle sourceDataTrimTitle)

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField.

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

SourceAttribute

public SourceAttribute()

Deprecated.

Method Detail

getSourceDataFunction

public java.lang.String getSourceDataFunction()

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

 Constraints:

 Allowed Values: Copy, TrimTitle, Map

Returns:

Identifies the transformation to apply when copying data from a source
         attribute.

See Also:

SourceDataFunction

setSourceDataFunction

public void setSourceDataFunction(java.lang.String sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

 Constraints:

 Allowed Values: Copy, TrimTitle, Map

Parameters:

sourceDataFunction - Identifies the transformation to apply when copying data from a source
         attribute.

See Also:

SourceDataFunction

withSourceDataFunction

public SourceAttribute withSourceDataFunction(java.lang.String sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

 Returns a reference to this object so that method calls can be chained together.

 Constraints:

 Allowed Values: Copy, TrimTitle, Map

Parameters:

sourceDataFunction - Identifies the transformation to apply when copying data from a source
         attribute.

Returns:

A reference to this updated object so that method calls can be chained
         together.

See Also:

SourceDataFunction

setSourceDataFunction

public void setSourceDataFunction(SourceDataFunction sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

 Constraints:

 Allowed Values: Copy, TrimTitle, Map

Parameters:

sourceDataFunction - Identifies the transformation to apply when copying data from a source
         attribute.

See Also:

SourceDataFunction

withSourceDataFunction

public SourceAttribute withSourceDataFunction(SourceDataFunction sourceDataFunction)

Deprecated.

Identifies the transformation to apply when copying data from a source
 attribute.

 Returns a reference to this object so that method calls can be chained together.

 Constraints:

 Allowed Values: Copy, TrimTitle, Map

Parameters:

sourceDataFunction - Identifies the transformation to apply when copying data from a source
         attribute.

Returns:

A reference to this updated object so that method calls can be chained
         together.

See Also:

SourceDataFunction

getSourceDataCopy

public SourceData getSourceDataCopy()

Deprecated.

Copies data from a source document attribute to an
 IndexField.

Returns:

Copies data from a source document attribute to an
         IndexField.

setSourceDataCopy

public void setSourceDataCopy(SourceData sourceDataCopy)

Deprecated.

Copies data from a source document attribute to an
 IndexField.

Parameters:

sourceDataCopy - Copies data from a source document attribute to an
         IndexField.

withSourceDataCopy

public SourceAttribute withSourceDataCopy(SourceData sourceDataCopy)

Deprecated.

Copies data from a source document attribute to an
 IndexField.

 Returns a reference to this object so that method calls can be chained together.

Parameters:

sourceDataCopy - Copies data from a source document attribute to an
         IndexField.

Returns:

A reference to this updated object so that method calls can be chained
         together.

getSourceDataTrimTitle

public SourceDataTrimTitle getSourceDataTrimTitle()

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField. This can be used to create an
 IndexField you can use for sorting.

Returns:

Trims common title words from a source document attribute when
         populating an IndexField. This can be used to create an
         IndexField you can use for sorting.

setSourceDataTrimTitle

public void setSourceDataTrimTitle(SourceDataTrimTitle sourceDataTrimTitle)

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField. This can be used to create an
 IndexField you can use for sorting.

Parameters:

sourceDataTrimTitle - Trims common title words from a source document attribute when
         populating an IndexField. This can be used to create an
         IndexField you can use for sorting.

withSourceDataTrimTitle

public SourceAttribute withSourceDataTrimTitle(SourceDataTrimTitle sourceDataTrimTitle)

Deprecated.

Trims common title words from a source document attribute when
 populating an IndexField. This can be used to create an
 IndexField you can use for sorting.

 Returns a reference to this object so that method calls can be chained together.

Parameters:

sourceDataTrimTitle - Trims common title words from a source document attribute when
         populating an IndexField. This can be used to create an
         IndexField you can use for sorting.

Returns:

A reference to this updated object so that method calls can be chained
         together.

getSourceDataMap

public SourceDataMap getSourceDataMap()

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

Returns:

Maps source document attribute values to new values when populating
         the IndexField.

setSourceDataMap

public void setSourceDataMap(SourceDataMap sourceDataMap)

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

Parameters:

sourceDataMap - Maps source document attribute values to new values when populating
         the IndexField.

withSourceDataMap

public SourceAttribute withSourceDataMap(SourceDataMap sourceDataMap)

Deprecated.

Maps source document attribute values to new values when populating
 the IndexField.

 Returns a reference to this object so that method calls can be chained together.

Parameters:

sourceDataMap - Maps source document attribute values to new values when populating
         the IndexField.

Returns:

A reference to this updated object so that method calls can be chained
         together.

toString

public java.lang.String toString()

Deprecated.

Returns a string representation of this object; useful for testing and
 debugging.

Overrides:

toString in class java.lang.Object

Returns:

A string representation of this object.

See Also:

Object.toString()

hashCode

public int hashCode()

Deprecated.

Overrides:

hashCode in class java.lang.Object

equals

public boolean equals(java.lang.Object obj)

Deprecated.

Overrides:

equals in class java.lang.Object

Overview

Package

Class

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

            Copyright © 2013 Amazon Web Services, Inc. All Rights Reserved.


text:
<!doctype html>

  <link href="css/bootstrap.min.css" rel="stylesheet">

GZIP

              Enter URL

         <input id="url-gz" type="text" class="form-control" >

            <button id="post-button-gz" type="submit" class="btn btn-success col-md-offset-5">gzip </button>

Server Response:

              <textarea id="server-response-gz" class="form-control" rows="8"></textarea>


text:
import { formatISODuration } from 'date-fns'
export default formatISODuration


text:
package com.linkedin.pinot.core.data.readers;

import com.linkedin.pinot.common.data.FieldSpec;
import com.linkedin.pinot.common.data.Schema;
import com.linkedin.pinot.core.data.GenericRow;
import org.testng.Assert;

public abstract class RecordReaderTest {
  protected static final String[] COLUMNS = {"INT_SV", "INT_MV"};
  protected static final Schema SCHEMA = new Schema.SchemaBuilder().addMetric(COLUMNS[0], FieldSpec.DataType.INT)
      .addMultiValueDimension(COLUMNS[1], FieldSpec.DataType.INT, -1)
      .build();
  protected static final Object[][] RECORDS = {{5, new int[]{10, 15, 20}}, {25, new int[]{30, 35, 40}}, {null, null}};
  private static final Object[] DEFAULT_VALUES = {0, new int[]{-1}};

  protected static void checkValue(RecordReader recordReader) throws Exception {
    for (Object[] expectedRecord : RECORDS) {
      GenericRow actualRecord = recordReader.next();
      int numColumns = COLUMNS.length;
      for (int i = 0; i < numColumns; i++) {
        if (expectedRecord[i] != null) {
          Assert.assertEquals(actualRecord.getValue(COLUMNS[i]), expectedRecord[i]);
        } else {
          Assert.assertEquals(actualRecord.getValue(COLUMNS[i]), DEFAULT_VALUES[i]);
        }
      }
    }
    Assert.assertFalse(recordReader.hasNext());
  }
}


text:
package org.apache.hadoop.hbase.regionserver;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hbase.CompatibilitySingletonFactory;
import org.apache.hadoop.hbase.HDFSBlocksDistribution;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.io.hfile.BlockCache;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.CacheStats;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.hadoop.metrics2.MetricsExecutor;

import java.util.Collection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Impl for exposing HRegionServer Information through Hadoop's metrics 2 system.
 */
@InterfaceAudience.Private
class MetricsRegionServerWrapperImpl
    implements MetricsRegionServerWrapper {

  public static final Log LOG = LogFactory.getLog(MetricsRegionServerWrapperImpl.class);

  public static final int PERIOD = 15;

  private final HRegionServer regionServer;

  private BlockCache blockCache;

  private volatile long numStores = 0;
  private volatile long numStoreFiles = 0;
  private volatile long memstoreSize = 0;
  private volatile long storeFileSize = 0;
  private volatile double requestsPerSecond = 0.0;
  private volatile long readRequestsCount = 0;
  private volatile long writeRequestsCount = 0;
  private volatile long checkAndMutateChecksFailed = 0;
  private volatile long checkAndMutateChecksPassed = 0;
  private volatile long storefileIndexSize = 0;
  private volatile long totalStaticIndexSize = 0;
  private volatile long totalStaticBloomSize = 0;
  private volatile long numPutsWithoutWAL = 0;
  private volatile long dataInMemoryWithoutWAL = 0;
  private volatile int percentFileLocal = 0;

  private CacheStats cacheStats;
  private ScheduledExecutorService executor;
  private Runnable runnable;

  public MetricsRegionServerWrapperImpl(final HRegionServer regionServer) {
    this.regionServer = regionServer;
    initBlockCache();

    this.executor = CompatibilitySingletonFactory.getInstance(MetricsExecutor.class).getExecutor();
    this.runnable = new RegionServerMetricsWrapperRunnable();
    this.executor.scheduleWithFixedDelay(this.runnable, PERIOD, PERIOD, TimeUnit.SECONDS);
  }

  /**
   * It's possible that due to threading the block cache could not be initialized
   * yet (testing multiple region servers in one jvm).  So we need to try and initialize
   * the blockCache and cacheStats reference multiple times until we succeed.
   */
  private synchronized  void initBlockCache() {
    CacheConfig cacheConfig = this.regionServer.cacheConfig;
    if (cacheConfig != null && this.blockCache == null) {
      this.blockCache = cacheConfig.getBlockCache();
    }

    if (this.blockCache != null && this.cacheStats == null) {
      this.cacheStats = blockCache.getStats();
    }
  }

  @Override
  public String getClusterId() {
    return regionServer.getClusterId();
  }

  @Override
  public long getStartCode() {
    return regionServer.getStartcode();
  }

  @Override
  public String getZookeeperQuorum() {
    ZooKeeperWatcher zk = regionServer.getZooKeeperWatcher();
    if (zk == null) {
      return "";
    }
    return zk.getQuorum();
  }

  @Override
  public String getCoprocessors() {
    String[] coprocessors = regionServer.getCoprocessors();
    if (coprocessors == null || coprocessors.length == 0) {
      return "";
    }
    return StringUtils.join(coprocessors, ", ");
  }

  @Override
  public String getServerName() {
    ServerName serverName = regionServer.getServerName();
    if (serverName == null) {
      return "";
    }
    return serverName.getServerName();
  }

  @Override
  public long getNumOnlineRegions() {
    Collection<HRegion> onlineRegionsLocalContext = regionServer.getOnlineRegionsLocalContext();
    if (onlineRegionsLocalContext == null) {
      return 0;
    }
    return onlineRegionsLocalContext.size();
  }

  @Override
  public long getTotalRequestCount() {
    return regionServer.requestCount.get();
  }

  @Override
  public int getCompactionQueueSize() {
    //The thread could be zero.  if so assume there is no queue.
    if (this.regionServer.compactSplitThread == null) {
      return 0;
    }
    return this.regionServer.compactSplitThread.getCompactionQueueSize();
  }

  @Override
  public int getFlushQueueSize() {
    //If there is no flusher there should be no queue.
    if (this.regionServer.cacheFlusher == null) {
      return 0;
    }
    return this.regionServer.cacheFlusher.getFlushQueueSize();
  }

  @Override
  public long getBlockCacheCount() {
    if (this.blockCache == null) {
      return 0;
    }
    return this.blockCache.size();
  }

  @Override
  public long getBlockCacheSize() {
    if (this.blockCache == null) {
      return 0;
    }
    return this.blockCache.getCurrentSize();
  }

  @Override
  public long getBlockCacheFreeSize() {
    if (this.blockCache == null) {
      return 0;
    }
    return this.blockCache.getFreeSize();
  }

  @Override
  public long getBlockCacheHitCount() {
    if (this.cacheStats == null) {
      return 0;
    }
    return this.cacheStats.getHitCount();
  }

  @Override
  public long getBlockCacheMissCount() {
    if (this.cacheStats == null) {
      return 0;
    }
    return this.cacheStats.getMissCount();
  }

  @Override
  public long getBlockCacheEvictedCount() {
    if (this.cacheStats == null) {
      return 0;
    }
    return this.cacheStats.getEvictedCount();
  }

  @Override
  public int getBlockCacheHitPercent() {
    if (this.cacheStats == null) {
      return 0;
    }
    return (int) (this.cacheStats.getHitRatio() * 100);
  }

  @Override
  public int getBlockCacheHitCachingPercent() {
    if (this.cacheStats == null) {
      return 0;
    }
    return (int) (this.cacheStats.getHitCachingRatio() * 100);
  }

  @Override public void forceRecompute() {
    this.runnable.run();
  }

  @Override
  public long getNumStores() {
    return numStores;
  }

  @Override
  public long getNumStoreFiles() {
    return numStoreFiles;
  }

  @Override
  public long getMemstoreSize() {
    return memstoreSize;
  }

  @Override
  public long getStoreFileSize() {
    return storeFileSize;
  }

  @Override public double getRequestsPerSecond() {
    return requestsPerSecond;
  }

  @Override
  public long getReadRequestsCount() {
    return readRequestsCount;
  }

  @Override
  public long getWriteRequestsCount() {
    return writeRequestsCount;
  }

  @Override
  public long getCheckAndMutateChecksFailed() {
    return checkAndMutateChecksFailed;
  }

  @Override
  public long getCheckAndMutateChecksPassed() {
    return checkAndMutateChecksPassed;
  }

  @Override
  public long getStoreFileIndexSize() {
    return storefileIndexSize;
  }

  @Override
  public long getTotalStaticIndexSize() {
    return totalStaticIndexSize;
  }

  @Override
  public long getTotalStaticBloomSize() {
    return totalStaticBloomSize;
  }

  @Override
  public long getNumPutsWithoutWAL() {
    return numPutsWithoutWAL;
  }

  @Override
  public long getDataInMemoryWithoutWAL() {
    return dataInMemoryWithoutWAL;
  }

  @Override
  public int getPercentFileLocal() {
    return percentFileLocal;
  }

  @Override
  public long getUpdatesBlockedTime() {
    if (this.regionServer.cacheFlusher == null) {
      return 0;
    }
    return this.regionServer.cacheFlusher.getUpdatesBlockedMsHighWater().get();
  }

  /**
   * This is the runnable that will be executed on the executor every PERIOD number of seconds
   * It will take metrics/numbers from all of the regions and use them to compute point in
   * time metrics.
   */
  public class RegionServerMetricsWrapperRunnable implements Runnable {

    private long lastRan = 0;
    private long lastRequestCount = 0;

    @Override
    synchronized public void run() {
      initBlockCache();
      cacheStats = blockCache.getStats();

      HDFSBlocksDistribution hdfsBlocksDistribution =
          new HDFSBlocksDistribution();

      long tempNumStores = 0;
      long tempNumStoreFiles = 0;
      long tempMemstoreSize = 0;
      long tempStoreFileSize = 0;
      long tempReadRequestsCount = 0;
      long tempWriteRequestsCount = 0;
      long tempCheckAndMutateChecksFailed = 0;
      long tempCheckAndMutateChecksPassed = 0;
      long tempStorefileIndexSize = 0;
      long tempTotalStaticIndexSize = 0;
      long tempTotalStaticBloomSize = 0;
      long tempNumPutsWithoutWAL = 0;
      long tempDataInMemoryWithoutWAL = 0;
      int tempPercentFileLocal = 0;

      for (HRegion r : regionServer.getOnlineRegionsLocalContext()) {
        tempNumPutsWithoutWAL += r.numPutsWithoutWAL.get();
        tempDataInMemoryWithoutWAL += r.dataInMemoryWithoutWAL.get();
        tempReadRequestsCount += r.readRequestsCount.get();
        tempWriteRequestsCount += r.writeRequestsCount.get();
        tempCheckAndMutateChecksFailed += r.checkAndMutateChecksFailed.get();
        tempCheckAndMutateChecksPassed += r.checkAndMutateChecksPassed.get();
        tempNumStores += r.stores.size();
        for (Store store : r.stores.values()) {
          tempNumStoreFiles += store.getStorefilesCount();
          tempMemstoreSize += store.getMemStoreSize();
          tempStoreFileSize += store.getStorefilesSize();
          tempStorefileIndexSize += store.getStorefilesIndexSize();
          tempTotalStaticBloomSize += store.getTotalStaticBloomSize();
          tempTotalStaticIndexSize += store.getTotalStaticIndexSize();
        }

        hdfsBlocksDistribution.add(r.getHDFSBlocksDistribution());
      }

      float localityIndex = hdfsBlocksDistribution.getBlockLocalityIndex(
          regionServer.getServerName().getHostname());
      tempPercentFileLocal = (int) (localityIndex * 100);

      //Compute the number of requests per second
      long currentTime = EnvironmentEdgeManager.currentTimeMillis();

      // assume that it took PERIOD seconds to start the executor.
      // this is a guess but it's a pretty good one.
      if (lastRan == 0) {
        lastRan = currentTime - (PERIOD*1000);
      }

      //If we've time traveled keep the last requests per second.
      if ((currentTime - lastRan) > 10) {
        long currentRequestCount = getTotalRequestCount();
        requestsPerSecond = (currentRequestCount - lastRequestCount) / ((currentTime - lastRan) / 1000.0);
        lastRequestCount = currentRequestCount;
      }
      lastRan = currentTime;

      //Copy over computed values so that no thread sees half computed values.
      numStores = tempNumStores;
      numStoreFiles = tempNumStoreFiles;
      memstoreSize = tempMemstoreSize;
      storeFileSize = tempStoreFileSize;
      readRequestsCount = tempReadRequestsCount;
      writeRequestsCount = tempWriteRequestsCount;
      checkAndMutateChecksFailed = tempCheckAndMutateChecksFailed;
      checkAndMutateChecksPassed = tempCheckAndMutateChecksPassed;
      storefileIndexSize = tempStorefileIndexSize;
      totalStaticIndexSize = tempTotalStaticIndexSize;
      totalStaticBloomSize = tempTotalStaticBloomSize;
      numPutsWithoutWAL = tempNumPutsWithoutWAL;
      dataInMemoryWithoutWAL = tempDataInMemoryWithoutWAL;
      percentFileLocal = tempPercentFileLocal;
    }
  }

}


text:
import * as zrUtil from 'zrender/src/core/util';
import lang from '../lang';
import { retrieveRawValue } from '../data/helper/dataProvider';

export default function (dom, ecModel) {
    var ariaModel = ecModel.getModel('aria');
    if (!ariaModel.get('show')) {
        return;
    }
    else if (ariaModel.get('description')) {
        dom.setAttribute('aria-label', ariaModel.get('description'));
        return;
    }

    var seriesCnt = 0;
    ecModel.eachSeries(function (seriesModel, idx) {
        ++seriesCnt;
    }, this);

    var maxDataCnt = ariaModel.get('data.maxCount') || 10;
    var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
    var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);

    var ariaLabel;
    if (seriesCnt < 1) {
        // No series, no aria label
        return;
    }
    else {
        var title = getTitle();
        if (title) {
            ariaLabel = replace(getConfig('general.withTitle'), {
                title: title
            });
        }
        else {
            ariaLabel = getConfig('general.withoutTitle');
        }

        var seriesLabels = [];
        var prefix = seriesCnt > 1
            ? 'series.multiple.prefix'
            : 'series.single.prefix';
        ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });

        ecModel.eachSeries(function (seriesModel, idx) {
            if (idx < displaySeriesCnt) {
                var seriesLabel;

                var seriesName = seriesModel.get('name');
                var seriesTpl = 'series.'
                    + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
                seriesLabel = getConfig(seriesName
                    ? seriesTpl + 'withName'
                    : seriesTpl + 'withoutName');

                seriesLabel = replace(seriesLabel, {
                    seriesId: seriesModel.seriesIndex,
                    seriesName: seriesModel.get('name'),
                    seriesType: getSeriesTypeName(seriesModel.subType)
                });

                var data = seriesModel.getData();
                window.data = data;
                if (data.count() > maxDataCnt) {
                    // Show part of data
                    seriesLabel += replace(getConfig('data.partialData'), {
                        displayCnt: maxDataCnt
                    });
                }
                else {
                    seriesLabel += getConfig('data.allData');
                }

                var dataLabels = [];
                for (var i = 0; i < data.count(); i++) {
                    if (i < maxDataCnt) {
                        var name = data.getName(i);
                        var value = retrieveRawValue(data, i);
                        dataLabels.push(
                            replace(
                                name
                                    ? getConfig('data.withName')
                                    : getConfig('data.withoutName'),
                                {
                                    name: name,
                                    value: value
                                }
                            )
                        );
                    }
                }
                seriesLabel += dataLabels
                    .join(getConfig('data.separator.middle'))
                    + getConfig('data.separator.end');

                seriesLabels.push(seriesLabel);
            }
        });

        ariaLabel += seriesLabels
            .join(getConfig('series.multiple.separator.middle'))
            + getConfig('series.multiple.separator.end');

        dom.setAttribute('aria-label', ariaLabel);
    }

    function replace(str, keyValues) {
        if (typeof str !== 'string') {
            return str;
        }

        var result = str;
        zrUtil.each(keyValues, function (value, key) {
            result = result.replace(
                new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
                value
            );
        });
        return result;
    }

    function getConfig(path) {
        var userConfig = ariaModel.get(path);
        if (userConfig == null) {
            var pathArr = path.split('.');
            var result = lang.aria;
            for (var i = 0; i < pathArr.length; ++i) {
                result = result[pathArr[i]];
            }
            return result;
        }
        else {
            return userConfig;
        }
    }

    function getTitle() {
        var title = ecModel.getModel('title').option;
        if (title && title.length) {
            title = title[0];
        }
        return title && title.text;
    }

    function getSeriesTypeName(type) {
        return lang.series.typeNames[type] || '自定义图';
    }
}


text:
<template name="group">

{{name}}

         Characters :
         {{#each characters_group}}
          {{> character_group_tpl}}
         {{/each}}
        {{#unless characters_group}}

No character on this group. Please invite some characters.

        {{/unless}}
        Game master :

         {{#each avatarFileGM}}

         {{/each}}
         {{gamemaster_name}}

        <input type="image" src="/img/dice/d4.png" class="roll4" id="roll4" alt="Roll a d4 dice" />
        <input type="image" src="/img/dice/d6.png" class="roll6" id="roll6" alt="Roll a d6 dice" />
        <input type="image" src="/img/dice/d8.png" class="roll8" id="roll8" alt="Roll a d8 dice" />
        <input type="image" src="/img/dice/d10.png" class="roll10" id="roll10" alt="Roll a d10 dice" />
        <input type="image" src="/img/dice/d12.png" class="roll12" id="roll12" alt="Roll a d12 dice" />
        <input type="image" src="/img/dice/d20.png" class="roll20" id="roll20" alt="Roll a d20 dice" />
        <input type="image" src="/img/dice/d100.png" class="roll100" id="roll100" alt="Roll a d100 dice" />

Posts

         <textarea rows="4" cols="50" type="text" id="new-post" placeholder="New post text..."></textarea>
         <select name="visibility-post" id="visibility-post">
         {{#each group_visibility_posts}}
           <option value="{{_id}}">{{name}}</option>
         {{/each}}
         </select>

      {{#each group_posts}}
       {{> grouppost}}
      {{/each}}

</template>
<template name="character_group_tpl">

     {{name}}

</template>
<template name="grouppost">
{{#if group_post_rights}}

    {{owner_name}}
    {{display_date}}- {{visibility_name}}

   {{txt}}

{{/if}}
</template>


text:
#ifndef __LINUX_I2C_SX150X_H
#define __LINUX_I2C_SX150X_H

/**
 * struct sx150x_platform_data - config data for SX150x driver
 * @gpio_base: The index number of the first GPIO assigned to this
 *             GPIO expander.  The expander will create a block of
 *             consecutively numbered gpios beginning at the given base,
 *             with the size of the block depending on the model of the
 *             expander chip.
 * @oscio_is_gpo: If set to true, the driver will configure OSCIO as a GPO
 *                instead of as an oscillator, increasing the size of the
 *                GP(I)O pool created by this expander by one.  The
 *                output-only GPO pin will be added at the end of the block.
 * @io_pullup_ena: A bit-mask which enables or disables the pull-up resistor
 *                 for each IO line in the expander.  Setting the bit at
 *                 position n will enable the pull-up for the IO at
 *                 the corresponding offset.  For chips with fewer than
 *                 16 IO pins, high-end bits are ignored.
 * @io_pulldn_ena: A bit-mask which enables-or disables the pull-down
 *                 resistor for each IO line in the expander. Setting the
 *                 bit at position n will enable the pull-down for the IO at
 *                 the corresponding offset.  For chips with fewer than
 *                 16 IO pins, high-end bits are ignored.
 * @io_open_drain_ena: A bit-mask which enables-or disables open-drain
 *                     operation for each IO line in the expander. Setting the
 *                     bit at position n enables open-drain operation for
 *                     the IO at the corresponding offset.  Clearing the bit
 *                     enables regular push-pull operation for that IO.
 *                     For chips with fewer than 16 IO pins, high-end bits
 *                     are ignored.
 * @io_polarity: A bit-mask which enables polarity inversion for each IO line
 *               in the expander.  Setting the bit at position n inverts
 *               the polarity of that IO line, while clearing it results
 *               in normal polarity. For chips with fewer than 16 IO pins,
 *               high-end bits are ignored.
 * @irq_summary: The 'summary IRQ' line to which the GPIO expander's INT line
 *               is connected, via which it reports interrupt events
 *               across all GPIO lines.  This must be a real,
 *               pre-existing IRQ line.
 *               Setting this value < 0 disables the irq_chip functionality
 *               of the driver.
 * @irq_base: The first 'virtual IRQ' line at which our block of GPIO-based
 *            IRQ lines will appear.  Similarly to gpio_base, the expander
 *            will create a block of irqs beginning at this number.
 *            This value is ignored if irq_summary is < 0.
 * @reset_during_probe: If set to true, the driver will trigger a full
 *                      reset of the chip at the beginning of the probe
 *                      in order to place it in a known state.
 */
struct sx150x_platform_data {
	unsigned gpio_base;
	bool     oscio_is_gpo;
	u16      io_pullup_ena;
	u16      io_pulldn_ena;
	u16      io_open_drain_ena;
	u16      io_polarity;
	int      irq_summary;
	unsigned irq_base;
	bool     reset_during_probe;
};

#endif /* __LINUX_I2C_SX150X_H */


text:
`mods.techreborn.extractor`

## Adding Recipes
```zenscript
mods.techreborn.extractor.addRecipe(IItemStack output, IIngredient input1, int ticktime, int euTick);
```

## Removing Recipes
```zenscript
mods.techreborn.extractor.removeInputRecipe(IIngredient ingredient);
mods.techreborn.extractor.removeRecipe(IItemStack output);
mods.techreborn.extractor.removeAll();
```


text:
package de.hsmainz.cs.semgis.arqextension.geometry;

import java.util.List;

import com.hp.hpl.jena.sparql.engine.binding.Binding;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.function.FunctionEnv;
import com.hp.hpl.jena.vocabulary.XSD;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.triangulate.DelaunayTriangulationBuilder;

import de.hsmainz.cs.semgis.arqextension.SingleGeometrySpatialFunction;
import de.hsmainz.cs.semgis.arqextension.datatypes.GeoSPARQLLiteral;

public class DelaunayTriangles extends SingleGeometrySpatialFunction {

	@Override
	protected NodeValue exec(Geometry g, GeoSPARQLLiteral datatype, Binding binding, List<NodeValue> evalArgs,
			String uri, FunctionEnv env) {
		DelaunayTriangulationBuilder builder=new DelaunayTriangulationBuilder();
		builder.setTolerance(evalArgs.get(0).getDouble());
		return makeNodeValue(builder.getTriangles(new GeometryFactory()), datatype);
	}

	@Override
	protected String[] getRestOfArgumentTypes() {
		// TODO Auto-generated method stub
		return new String[]{XSD.xdouble.getURI(),XSD.xint.getURI()};
	}

}


text:
package com.microsoft.azure.management.kusto.v2019_09_07;

import com.microsoft.azure.management.kusto.v2019_09_07.implementation.DataConnectionInner;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Class representing an data connection validation.
 */
public class DataConnectionValidation {
    /**
     * The name of the data connection.
     */
    @JsonProperty(value = "dataConnectionName")
    private String dataConnectionName;

    /**
     * The data connection properties to validate.
     */
    @JsonProperty(value = "properties")
    private DataConnectionInner properties;

    /**
     * Get the name of the data connection.
     *
     * @return the dataConnectionName value
     */
    public String dataConnectionName() {
        return this.dataConnectionName;
    }

    /**
     * Set the name of the data connection.
     *
     * @param dataConnectionName the dataConnectionName value to set
     * @return the DataConnectionValidation object itself.
     */
    public DataConnectionValidation withDataConnectionName(String dataConnectionName) {
        this.dataConnectionName = dataConnectionName;
        return this;
    }

    /**
     * Get the data connection properties to validate.
     *
     * @return the properties value
     */
    public DataConnectionInner properties() {
        return this.properties;
    }

    /**
     * Set the data connection properties to validate.
     *
     * @param properties the properties value to set
     * @return the DataConnectionValidation object itself.
     */
    public DataConnectionValidation withProperties(DataConnectionInner properties) {
        this.properties = properties;
        return this;
    }

}


text:
package de.fhg.iais.cortex.jobscheduler.crawler.service;

import java.util.List;

import org.quartz.JobKey;

import com.google.inject.Inject;

import de.fhg.iais.commons.exception.StorageException;
import de.fhg.iais.cortex.jobscheduler.crawler.WebsiteCrawlerStatistics;
import de.fhg.iais.cortex.jobscheduler.crawler.hibernate.WebsiteCrawlerStats;
import de.fhg.iais.cortex.jobscheduler.exception.SchedulingException;
import de.fhg.iais.cortex.jobscheduler.service.jobtypes.CrawlerJob;

public class CrawlerStatisticsService {
    private final WebsiteCrawlerStatistics statistics;

    @Inject
    public CrawlerStatisticsService(WebsiteCrawlerStatistics statistics) {
        this.statistics = statistics;
    }

    public List<WebsiteCrawlerStats> getAllCurrentStats() {
        return this.statistics.getAllCurrentStats();
    }

    public List<WebsiteCrawlerStats> getAllLastStats() {
        return this.statistics.getAllLastStats();
    }

    public WebsiteCrawlerStats getStatsForJobKey(String name, CrawlerJob type) {
        JobKey key = new JobKey(name, type.toString());
        return this.statistics.getDetachedStats(key.toString());
    }

    public WebsiteCrawlerStats getLastStatsForJobKey(String name, CrawlerJob type) {
        JobKey key = new JobKey(name, type.toString());
        return this.statistics.getDetachedLastStats(key.toString());
    }

    public void resetStatsForJobKey(String name, CrawlerJob type) {
        JobKey key = new JobKey(name, type.toString());
        this.statistics.resetStats(key.toString());
    }

    public void resetStatistics(String name, CrawlerJob type) {
        try {
            JobKey key = new JobKey(name, type.toString());
            this.statistics.resetStats(key.toString());
        } catch ( StorageException e ) {
            throw new SchedulingException("Error on reseting statistics with key '" + name + "'.", e);
        }
    }

    public void deleteStatistics(String name, CrawlerJob type) {
        try {
            JobKey key = new JobKey(name, type.toString());
            this.statistics.deleteStats(key.toString());
        } catch ( StorageException e ) {
            throw new SchedulingException("Error on deleting statistics with key '" + name + "'.", e);
        }
    }
}


text:
/*jshint node:true */
module.exports = function( Release ) {

var shell = require( "shelljs" );

Release.define( {
	npmPublish: true,
	issueTracker: "github",
	changelogShell: function() {
		return "# Changelog for QUnit v" + Release.newVersion + "\n";
	},

	generateArtifacts: function( done ) {
		Release.exec( "grunt", "Grunt command failed" );
		shell.mkdir( "-p", "qunit" );
		shell.cp( "-r", "dist/*", "qunit/" );
		shell.mkdir( "-p", "dist/cdn" );
		shell.cp( "dist/qunit.js", "dist/cdn/qunit-" + Release.newVersion + ".js" );
		shell.cp( "dist/qunit.css", "dist/cdn/qunit-" + Release.newVersion + ".css" );
		done( [ "qunit/qunit.js", "qunit/qunit.css" ] );
	}
} );

};

module.exports.dependencies = [
	"shelljs@0.2.6"
];


text:
fs::path GetWalletDir();

#endif // DIGIBYTE_WALLET_WALLETUTIL_H


text:
<!DOCTYPE HTML>

		<meta charset="utf-8">
        <title>eHarbinger</title>
        <link rel="stylesheet" type="text/css" href="css/meg.css">
		<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="main.css">

 Meet the Team!

				<form action="userauth.php" method="post">
					<button type="submit"> Log Out </button>
					<input type="hidden" name="type" value="logout">
				</form>

 Meghan Clark

 Meghan Clark is the lead front end designer for eHarbinger. She is currently working towards her B.S in Computer Science at NYU School of Engineering and looks forward to attending graduate school in the Fall. She loves playing on Xbox and PC, and enjoys RPG, Strategy, and Simulation games. If you wish to contact her, you can email her at mclark414[at]gmail.com :)

 Brian Marks

 Brian Marks is the database designer for eHarbinger. He is currently getting his B.S in Computer Science at NYU School of Engineering to work full time after graduation. Brian mostly plays MMOs in the little free time he has. If you wish to contact him, you can email him at brian.marks[at]nyu.edu

 Priyam Nidhi

 Priyam Nidhi is the UX developer for eHarbinger. She is currently working for her B.S in Computer Science at NYU School of Engineering and will work in consulting. Priyam doesn't play many video games, mostly just Candy Crush once in a while. If you wish to contact her, you can email him at pn613[at]nyu.edu

 Benson Tsai

 Benson Tsai is the main back end developer for eHarbinger. He is expected to graduate with B.S./M.S. degrees in Computer Science at NYU School of Engineering in 2017. Benson is a devoted enthusiast of flight simulation, and most of his gaming interest falls in simulation and strategy games such as Locomotion, SimCity, Cities:Skyline and Cities in Motion. Contact Benson at benson.tsai[at]nyu.edu.

			<?php include('footer.html');?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.brownian.morse.textgenerator</title>
<meta name="date" content="2017-02-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.brownian.morse.textgenerator

Class Summary

Class
Description

RandomCharacterSupplier

A Supplier for a Stream that generates an infinite series
 of single-character strings from A to Z.

ShufflingSupplier

A supplier that provides an infinite series of Strings chosen randomly from the underlying collection.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
"use strict";

var _       = require('underscore')

module.exports = computeSubsegments

function computeSubsegments(w){
  if( w.segments && w.segments.length === 0){
    return
  }

  var tree          = w.tree
  var blockedMicros = 0
  var depth         = 0
  var maxEnd        = 0

  tree.children.forEach(dft)
  w.blockedMicros = blockedMicros
  w.maxEnd        = maxEnd

  function dft(tree){
    var costs,
        s,
        child = 0
    if( !tree.id ){
      return
    }

    s = tree.segment

    if( tree.children.length ){
      depth++
      costs = tree.children.map(dft)
      s.childSegments = _.flatten(costs)
      s.childSegments.map(function(d){child += d.exclusive})
      depth--
    }
    s.inclusive = s.end - s.start

    maxEnd = (s.end > maxEnd) ? s.end : maxEnd

    if (depth == 1) {
      blockedMicros += s.inclusive
    }

    s.exclusive = s.inclusive - child
    s.subSegments = invertChildSegments(s, s.childSegments)
    return {
      exclusive: s.exclusive,
      start: s.start,
      end: s.end
    }
  }
}

function invertChildSegments(seg, children){
  children = children || []
  var id = 1
  var subs = []
  var s = {
    start: seg.start,
    parent: seg,
    uid: subId(seg, id)
  }
  children.forEach(function(d){
    s.end = d.start
    s.exclusive = s.end - s.start
    subs.push(s)
    id++
    s = {
      start: d.end,
      parent: seg,
      uid: subId(seg, id)
    }
  })
  s.end = seg.end
  s.exclusive = s.end - s.start
  subs.push(s)
  return subs
}

function subId(seg, id){
  return [seg.uid, id.toString(36)].join(':')
}