text:
package billing

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// ProductsClient is the billing client provides access to billing resources for Azure subscriptions.
type ProductsClient struct {
	BaseClient
}

// NewProductsClient creates an instance of the ProductsClient client.
func NewProductsClient(subscriptionID string) ProductsClient {
	return NewProductsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewProductsClientWithBaseURI creates an instance of the ProductsClient client.
func NewProductsClientWithBaseURI(baseURI string, subscriptionID string) ProductsClient {
	return ProductsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// Get get a single product by name.
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// productName - invoice Id.
func (client ProductsClient) Get(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string) (result ProductSummary, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, billingAccountName, invoiceSectionName, productName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client ProductsClient) GetPreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
		"productName":        autorest.Encode("path", productName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/products/{productName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) GetSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ProductsClient) GetResponder(resp *http.Response) (result ProductSummary, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByBillingAccountName lists products by billing account name.
// Parameters:
// billingAccountName - billing Account Id.
// filter - may be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'.
// It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and
// value is separated by a colon (:).
func (client ProductsClient) ListByBillingAccountName(ctx context.Context, billingAccountName string, filter string) (result ProductsListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.ListByBillingAccountName")
		defer func() {
			sc := -1
			if result.plr.Response.Response != nil {
				sc = result.plr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listByBillingAccountNameNextResults
	req, err := client.ListByBillingAccountNamePreparer(ctx, billingAccountName, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByBillingAccountName", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByBillingAccountNameSender(req)
	if err != nil {
		result.plr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByBillingAccountName", resp, "Failure sending request")
		return
	}

	result.plr, err = client.ListByBillingAccountNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByBillingAccountName", resp, "Failure responding to request")
	}

	return
}

// ListByBillingAccountNamePreparer prepares the ListByBillingAccountName request.
func (client ProductsClient) ListByBillingAccountNamePreparer(ctx context.Context, billingAccountName string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = autorest.Encode("query", filter)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByBillingAccountNameSender sends the ListByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) ListByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByBillingAccountNameResponder handles the response to the ListByBillingAccountName request. The method always
// closes the http.Response Body.
func (client ProductsClient) ListByBillingAccountNameResponder(resp *http.Response) (result ProductsListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listByBillingAccountNameNextResults retrieves the next set of results, if any.
func (client ProductsClient) listByBillingAccountNameNextResults(ctx context.Context, lastResults ProductsListResult) (result ProductsListResult, err error) {
	req, err := lastResults.productsListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "billing.ProductsClient", "listByBillingAccountNameNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByBillingAccountNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "billing.ProductsClient", "listByBillingAccountNameNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByBillingAccountNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "listByBillingAccountNameNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByBillingAccountNameComplete enumerates all values, automatically crossing page boundaries as required.
func (client ProductsClient) ListByBillingAccountNameComplete(ctx context.Context, billingAccountName string, filter string) (result ProductsListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.ListByBillingAccountName")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListByBillingAccountName(ctx, billingAccountName, filter)
	return
}

// ListByInvoiceSectionName lists products by invoice section name.
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// filter - may be used to filter by product type. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'.
// It does not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair string where key and
// value is separated by a colon (:).
func (client ProductsClient) ListByInvoiceSectionName(ctx context.Context, billingAccountName string, invoiceSectionName string, filter string) (result ProductsListResult, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.ListByInvoiceSectionName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ListByInvoiceSectionNamePreparer(ctx, billingAccountName, invoiceSectionName, filter)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByInvoiceSectionName", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByInvoiceSectionNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByInvoiceSectionName", resp, "Failure sending request")
		return
	}

	result, err = client.ListByInvoiceSectionNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ListByInvoiceSectionName", resp, "Failure responding to request")
	}

	return
}

// ListByInvoiceSectionNamePreparer prepares the ListByInvoiceSectionName request.
func (client ProductsClient) ListByInvoiceSectionNamePreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, filter string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}
	if len(filter) > 0 {
		queryParameters["$filter"] = autorest.Encode("query", filter)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/products", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByInvoiceSectionNameSender sends the ListByInvoiceSectionName request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) ListByInvoiceSectionNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ListByInvoiceSectionNameResponder handles the response to the ListByInvoiceSectionName request. The method always
// closes the http.Response Body.
func (client ProductsClient) ListByInvoiceSectionNameResponder(resp *http.Response) (result ProductsListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Transfer the operation to transfer a Product to another invoice section.
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// productName - invoice Id.
// parameters - parameters supplied to the Transfer Product operation.
func (client ProductsClient) Transfer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, parameters TransferProductRequestProperties) (result ProductSummary, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.Transfer")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.TransferPreparer(ctx, billingAccountName, invoiceSectionName, productName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Transfer", nil, "Failure preparing request")
		return
	}

	resp, err := client.TransferSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Transfer", resp, "Failure sending request")
		return
	}

	result, err = client.TransferResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "Transfer", resp, "Failure responding to request")
	}

	return
}

// TransferPreparer prepares the Transfer request.
func (client ProductsClient) TransferPreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, parameters TransferProductRequestProperties) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
		"productName":        autorest.Encode("path", productName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/products/{productName}/transfer", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// TransferSender sends the Transfer request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) TransferSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// TransferResponder handles the response to the Transfer request. The method always
// closes the http.Response Body.
func (client ProductsClient) TransferResponder(resp *http.Response) (result ProductSummary, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// UpdateAutoRenewByBillingAccountName cancel auto renew for product by product id and billing account name
// Parameters:
// billingAccountName - billing Account Id.
// productName - invoice Id.
// body - update auto renew request parameters.
func (client ProductsClient) UpdateAutoRenewByBillingAccountName(ctx context.Context, billingAccountName string, productName string, body UpdateAutoRenewRequest) (result UpdateAutoRenewOperationSummary, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.UpdateAutoRenewByBillingAccountName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.UpdateAutoRenewByBillingAccountNamePreparer(ctx, billingAccountName, productName, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByBillingAccountName", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateAutoRenewByBillingAccountNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByBillingAccountName", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateAutoRenewByBillingAccountNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByBillingAccountName", resp, "Failure responding to request")
	}

	return
}

// UpdateAutoRenewByBillingAccountNamePreparer prepares the UpdateAutoRenewByBillingAccountName request.
func (client ProductsClient) UpdateAutoRenewByBillingAccountNamePreparer(ctx context.Context, billingAccountName string, productName string, body UpdateAutoRenewRequest) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"productName":        autorest.Encode("path", productName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/products/{productName}/updateAutoRenew", pathParameters),
		autorest.WithJSON(body),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateAutoRenewByBillingAccountNameSender sends the UpdateAutoRenewByBillingAccountName request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) UpdateAutoRenewByBillingAccountNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// UpdateAutoRenewByBillingAccountNameResponder handles the response to the UpdateAutoRenewByBillingAccountName request. The method always
// closes the http.Response Body.
func (client ProductsClient) UpdateAutoRenewByBillingAccountNameResponder(resp *http.Response) (result UpdateAutoRenewOperationSummary, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// UpdateAutoRenewByInvoiceSectionName cancel auto renew for product by product id and invoice section name
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// productName - invoice Id.
// body - update auto renew request parameters.
func (client ProductsClient) UpdateAutoRenewByInvoiceSectionName(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, body UpdateAutoRenewRequest) (result UpdateAutoRenewOperationSummary, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.UpdateAutoRenewByInvoiceSectionName")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.UpdateAutoRenewByInvoiceSectionNamePreparer(ctx, billingAccountName, invoiceSectionName, productName, body)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByInvoiceSectionName", nil, "Failure preparing request")
		return
	}

	resp, err := client.UpdateAutoRenewByInvoiceSectionNameSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByInvoiceSectionName", resp, "Failure sending request")
		return
	}

	result, err = client.UpdateAutoRenewByInvoiceSectionNameResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "UpdateAutoRenewByInvoiceSectionName", resp, "Failure responding to request")
	}

	return
}

// UpdateAutoRenewByInvoiceSectionNamePreparer prepares the UpdateAutoRenewByInvoiceSectionName request.
func (client ProductsClient) UpdateAutoRenewByInvoiceSectionNamePreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, body UpdateAutoRenewRequest) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
		"productName":        autorest.Encode("path", productName),
	}

	const APIVersion = "2018-11-01-preview"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/products/{productName}/updateAutoRenew", pathParameters),
		autorest.WithJSON(body),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// UpdateAutoRenewByInvoiceSectionNameSender sends the UpdateAutoRenewByInvoiceSectionName request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) UpdateAutoRenewByInvoiceSectionNameSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// UpdateAutoRenewByInvoiceSectionNameResponder handles the response to the UpdateAutoRenewByInvoiceSectionName request. The method always
// closes the http.Response Body.
func (client ProductsClient) UpdateAutoRenewByInvoiceSectionNameResponder(resp *http.Response) (result UpdateAutoRenewOperationSummary, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ValidateTransfer validates the transfer of products across invoice sections.
// Parameters:
// billingAccountName - billing Account Id.
// invoiceSectionName - invoiceSection Id.
// productName - invoice Id.
// parameters - parameters supplied to the Transfer Products operation.
func (client ProductsClient) ValidateTransfer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, parameters TransferProductRequestProperties) (result ValidateProductTransferEligibilityResult, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ProductsClient.ValidateTransfer")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.ValidateTransferPreparer(ctx, billingAccountName, invoiceSectionName, productName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ValidateTransfer", nil, "Failure preparing request")
		return
	}

	resp, err := client.ValidateTransferSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ValidateTransfer", resp, "Failure sending request")
		return
	}

	result, err = client.ValidateTransferResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "billing.ProductsClient", "ValidateTransfer", resp, "Failure responding to request")
	}

	return
}

// ValidateTransferPreparer prepares the ValidateTransfer request.
func (client ProductsClient) ValidateTransferPreparer(ctx context.Context, billingAccountName string, invoiceSectionName string, productName string, parameters TransferProductRequestProperties) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"billingAccountName": autorest.Encode("path", billingAccountName),
		"invoiceSectionName": autorest.Encode("path", invoiceSectionName),
		"productName":        autorest.Encode("path", productName),
	}

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/invoiceSections/{invoiceSectionName}/products/{productName}/validateTransferEligibility", pathParameters),
		autorest.WithJSON(parameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ValidateTransferSender sends the ValidateTransfer request. The method will close the
// http.Response Body if it receives an error.
func (client ProductsClient) ValidateTransferSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
	return autorest.SendWithSender(client, req, sd...)
}

// ValidateTransferResponder handles the response to the ValidateTransfer request. The method always
// closes the http.Response Body.
func (client ProductsClient) ValidateTransferResponder(resp *http.Response) (result ValidateProductTransferEligibilityResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
'use strict';

angular.module('aphrodite')
.directive('creditcard', function ($window) {
    return {
        restrict   : 'E',
        replace    : true,
        templateUrl: 'directives/CreditCardDirectiveTemplate.html',
        scope      : {
            animated: '=?',
            card    : '=?',
            onRemove: '=?',
        },
        link       : function (scope, element) {
            /**
             * Local values
             */
            scope.animationInClass = 'creditcard-wrapper--animation-in';

            /**
             * Remove element animation
             */
            scope._removeAnimation = function () {
                element.removeClass(scope.animationInClass);
            };

            /**
             * Initialize directive
             */
            scope._init = function () {
                if (!scope.animated) {
                    return;
                }

                if (!$window.requestAnimationFrame) {
                    scope._removeAnimation();
                    return;
                }

                $window.requestAnimationFrame(scope._removeAnimation);
            };

            /**
             * First run
             */
            scope._init();
        },
    };
});

redpajama_set_name: RedPajamaGithub


text:
from os import environ
import re
import subprocess

from ansible.module_utils.basic import *

def _check_output_strip(command):
    return subprocess.check_output(command).decode('utf-8').strip()

def _escape_single_quotes(string):
    return re.sub("'", r"'\''", string)

def _split_key(full_key):
    key_array = full_key.split('.')
    schema = '.'.join(key_array[0:-1])
    single_key = key_array[-1]
    return (schema, single_key)

def _get_gnome_version():
    return tuple(map(int, (_check_output_strip(
        ['gnome-shell', '--version']).split(' ')[2].split('.'))))

def _get_dbus_bus_address(user):
    if user is None:
        if environ.get('DBUS_SESSION_BUS_ADDRESS') is None:
            return None

        return "DBUS_SESSION_BUS_ADDRESS={}".format(environ['DBUS_SESSION_BUS_ADDRESS'])

    pgrep_cmd = ['pgrep', '-u', user, 'gnome-session']
    gnome_ver = _get_gnome_version()
    if (gnome_ver >= (3, 33, 90)):
        # From GNOME 3.33.90 session process has changed
        # https://github.com/GNOME/gnome-session/releases/tag/3.33.90
        pgrep_cmd = ['pgrep', '-u', user, '-f', 'session=gnome']

    try:
        pid = _check_output_strip(pgrep_cmd)
    except subprocess.CalledProcessError:
       return None

    if pid:
        return _check_output_strip(
            ['grep', '-z', '^DBUS_SESSION_BUS_ADDRESS',
             '/proc/{}/environ'.format(pid)]).strip('\0')

def _run_cmd_with_dbus(user, cmd):
    dbus_addr = _get_dbus_bus_address(user)
    if not dbus_addr:
        command = ['export `/usr/bin/dbus-launch`', ';']
    else:
        command = ['export', dbus_addr, ';']
    command.extend(cmd)
    if not dbus_addr:
        command.extend([';',
            'kill $DBUS_SESSION_BUS_PID &> /dev/null'
        ])

    if user is None:
        return _check_output_strip(['/bin/sh', '-c', " ".join(command)])

    return _check_output_strip(['su', '-', user , '-c', " ".join(command)])

def _set_value(schemadir, user, full_key, value):
    schema, single_key = _split_key(full_key)

    command = ['/usr/bin/gsettings']
    if schemadir:
        command.extend(['--schemadir', schemadir])
    command.extend(['set', schema, single_key,
        "'%s'" % _escape_single_quotes(value)])

    return _run_cmd_with_dbus(user, command)

def _get_value(schemadir, user, full_key):
    schema, single_key = _split_key(full_key)

    command = ['/usr/bin/gsettings']
    if schemadir:
        command.extend(['--schemadir', schemadir])
    command.extend(['get', schema, single_key])

    return _run_cmd_with_dbus(user, command)

def main():

    module = AnsibleModule(
        argument_spec = {
            'state': { 'choices': ['present'], 'default': 'present' },
            'user': { 'default': None },
            'schemadir': { 'required': False },
            'key': { 'required': True },
            'value': { 'required': True },
        },
        supports_check_mode = True,
    )

    params = module.params
    state = module.params['state']
    user = module.params['user']
    schemadir = module.params['schemadir']
    key = module.params['key']
    value = module.params['value']

    old_value = _get_value(schemadir, user, key)
    changed = old_value != value

    if changed and not module.check_mode:
        _set_value(schemadir, user, key, value)

    module.exit_json(**{
        'changed': changed,
        'key': key,
        'value': value,
        'old_value': old_value,
    })

main()


text:
#include "RandomHoughFeature.hpp"
#include "Detector.hpp"
#include <memory>
#include <opencv2/opencv.hpp>
#include "Detection.hpp"
#include <boost/math/special_functions/round.hpp>
#include <boost/graph/graph_concepts.hpp>
#include "Skin.hpp"
#include "Orthography.hpp"
#include "Quaternion.hpp"
#include "ScanningWindow.hpp"

namespace deformable_depth
{
  using namespace cv;
  using namespace std;

  using params::RESP_ORTHO_X_RES;
  using params::RESP_ORTHO_Y_RES;
  using params::RESP_ORTHO_Z_RES;
  static Size ortho_res(RESP_ORTHO_X_RES,RESP_ORTHO_Y_RES);

  ///
  /// SECTION StructuredWindow
  ///

  Point2d StructuredWindow::queryToImCoords(const Point2d& query) const
  {
    int x = boost::math::round(query.x * detection->BB.width) + detection->BB.tl().x;
    int y = boost::math::round(query.y * detection->BB.height) + detection->BB.tl().y;
    return Point2d(x,y);
  }

  double StructuredWindow::metric_feature(const Point2d& query) const
  {
    assert(im != nullptr);
    Point2d xy = queryToImCoords(query);
    double ignore, depth = im->Z.at<float>(xy.y,xy.x);

    CustomCamera box_camera = im->camera.crop(detection->BB);
    box_camera.setRes(im->cols(),im->rows());
    double did = HOGComputer_Area::DistInvarDepth(depth,box_camera,ignore);;
    //cout << printfpp("z(%f) => did(%f)",depth,did) << endl;
    return did;
    //return im->distInvarientDepths().at<float>(y,x);
  }

  double StructuredWindow::skin_likelihood(const Point2d& query) const
  {
    // get the query position in our local image
    Point2d xy = queryToImCoords(query);

    // get the color at that position
    assert(im->RGB.type() == DataType<Vec3b>::type);
    Vec3b color = im->RGB.at<Vec3b>(xy.y,xy.x);
    return deformable_depth::skin_likelihood(color);
  }

  Vec2d StructuredWindow::rgChroma(const Point2d& query) const
  {
    Vec3b RGB = im->RGB.at<Vec3b>(query.y,query.x);
    double R = RGB[0];
    double G = RGB[1];
    double B = RGB[2];
    double r = R / (R+G+B);
    double g = G / (R+G+B);
    double b = B / (R+G+B);
    return Vec2d(r,g);
  }

  static Rect queryRect(const Point2d&tl,const Point2d&br)
  {
    Rect q(tl,br);
    q.width = std::max(q.width,1);
    q.height= std::max(q.height,1);
    return q;
  }

  double StructuredWindow::mean_area(const Rect_< double >& query) const
  {
    // get the query position in our local image
    Point2d tl = queryToImCoords(query.tl());
    Point2d br = queryToImCoords(query.br());

    return im->mean_depth(queryRect(tl,br));
  }

  double StructuredWindow::relative_depth(const Rect_< double >& query) const
  {
    Point2d tl = queryToImCoords(query.tl());
    Point2d br = queryToImCoords(query.br());

    return im->mean_depth(queryRect(tl,br)) - detection->getDepth(*im);
  }

  double StructuredWindow::mean_intensity(const Rect_< double >& query) const
  {
    Point2d tl = queryToImCoords(query.tl());
    Point2d br = queryToImCoords(query.br());

    return im->mean_intensity(queryRect(tl,br));
  }

  Point3d StructuredWindow::ortho_detBBCenter() const
  {
    assert(im != nullptr);

    Rect detectBB = detection->BB;
    float det_z = im->Z.at<float>(rectCenter(detectBB));
    assert(goodNumber(det_z));
    Rect_<double> detBB_ortho = map2ortho(im->camera,ortho_res,detectBB,det_z);
    Point2d detBBCenter = rectCenter(detBB_ortho);
    assert(0 <= detBBCenter.x && 0 <= detBBCenter.y &&
	    detBBCenter.x < ortho_res.width && detBBCenter.y < ortho_res.height);
    return Point3d(detBBCenter.x,detBBCenter.y,det_z);
  }

  Rect_< double > StructuredWindow::ortho_detBB() const
  {
    return map2ortho(im->camera,ortho_res,detection->BB, detection->getDepth(*im));
  }

  ///
  /// SECTION StructuredExample
  ///

  Point3d StructuredExample::ortho_handBBCenter() const
  {
    // load im
    const MetaData& c_metadata = *metadata;
    shared_ptr<const ImRGBZ> im = c_metadata.load_im();

    // get the center for the GT
    Rect handBB = metadata->get_positives_c().at("HandBB");
    handBB = clamp(im->Z,handBB);
    float hand_z = im->Z.at<float>(rectCenter(handBB));
    Rect_<double> handBB_ortho = map2ortho(im->camera,ortho_res,handBB, hand_z);
    Point2d handBBCenter = rectCenter(handBB_ortho);
    handBBCenter.x = clamp<int>(0,handBBCenter.x,ortho_res.width-1);
    handBBCenter.y = clamp<int>(0,handBBCenter.y,ortho_res.height-1);
    assert(0 <= handBBCenter.x && 0 <= handBBCenter.y &&
	    handBBCenter.x < ortho_res.width && handBBCenter.y < ortho_res.height);
    return Point3d(handBBCenter.x,handBBCenter.y,hand_z);
  }

  double compCorrectness(const map<string,AnnotationBoundingBox>&selected,const Rect_<double>&bb)
  {
    double correctness = 0;
    for(auto & gt_bb : selected)
      correctness = std::max<double>(correctness,rectIntersect(gt_bb.second,bb));
    return correctness; //;
  }

  double StructuredExample::correctness() const
  {
    auto&selected = metadata->default_training_positives();
    return compCorrectness(selected,detection->BB);
  }

  bool StructuredExample::is_correct() const
  {
    return correctness() > .5;
  }

  bool StructuredExample::is_black() const
  {
    auto selected = metadata->get_positives_c();
    return compCorrectness(selected,detection->BB);
  }

  bool StructuredExample::is_white() const
  {
    return correctness() > .75;
  }

  ///
  /// SECTION RandomFeature
  ///
  RandomFeature::RandomFeature()
  {
  }

  RandomFeature::RandomFeature(const vector<StructuredExample>&examples) :
  uuid(deformable_depth::uuid())
  {
    // randomly select a feature type
    vector<double> feat_type_dist{0,0,.1,.3,.2,.2,.1,.1};
    switch(rnd_multinom(feat_type_dist))
    {
      case 0:
	feature_type = DistanceInvarientDepth;
	break;
      case 1:
	feature_type = SkinLikelihood;
	break;
      case 2:
	feature_type = MeanDepth;
	break;
      case 3:
	feature_type = MeanIntensity;
	break;
      case 4:
	feature_type = R_Chroma;
	break;
      case 5:
	feature_type = G_Chroma;
	break;
      case 6:
	feature_type = Resolution;
	break;
      case 7:
	feature_type = RelativeDepth;
	break;
      default:
	assert(false);
    }

    p.x = sample_in_range(0,1);
    p.y = sample_in_range(0,1);
    roi1 = Rect_<double>(Point2d(sample_in_range(0,1),sample_in_range(0,1)),
			 Point2d(sample_in_range(0,1),sample_in_range(0,1)));
    roi2 = Rect_<double>(Point2d(sample_in_range(0,1),sample_in_range(0,1)),
			 Point2d(sample_in_range(0,1),sample_in_range(0,1)));
    const StructuredExample&random_example = examples[rand()%examples.size()];
    this->threshold = feature(random_example);

    log_file << printfpp("RandomFeature::RandomFeature %f %f %f %d",
			 (double)p.x,(double)p.y,
			 (double)this->threshold,(int)feature_type) << endl;
  }

  double RandomFeature::feature(const StructuredWindow& ex) const
  {
    switch(feature_type)
    {
      case DistanceInvarientDepth: // size
	return ex.metric_feature(p);
      case SkinLikelihood: // color
	return ex.skin_likelihood(p);
      case MeanDepth: // shape
	return ex.mean_area(roi2) - ex.mean_area(roi1);
      case MeanIntensity:
	return ex.mean_intensity(roi2) - ex.mean_intensity(roi1);
      case R_Chroma:
	return ex.rgChroma(p)[0];
      case G_Chroma:
	return ex.rgChroma(p)[1];
      case Resolution:
	return ex.detection->BB.area();
      case RelativeDepth:
	return ex.relative_depth(roi1);
      default:
	throw std::logic_error("Bad Feature_type");
    }
  }

  bool RandomFeature::predict(const StructuredWindow& ex) const
  {
    return feature(ex) < this->threshold;
  }

  double RandomFeature::structural_gain
  (
    double correct_true_ratio, double correct_false_ratio,
    vector<StructuredExample>&correct_exs_true, vector<StructuredExample>&correct_exs_false,
    const PCAPose&pcaPose, ostringstream&oss,
    Mat&pose_mu_true, Mat&pose_cov_true,
    Mat&pose_mu_false, Mat&pose_cov_false
  )
  {
    double latent_structural_gain =
	- correct_true_ratio * entropy_gaussian(
	      [&](int i)
	      {
		Mat pcFeat = pcaPose.project_q(correct_exs_true[i].metadata);
		oss << "p" << pcFeat;
		return pcFeat;
	      },
	      correct_exs_true.size(),pose_mu_true,pose_cov_true)
	- correct_false_ratio * entropy_gaussian(
	      [&](int i)
	      {
		Mat pcFeat = pcaPose.project_q(correct_exs_false[i].metadata);
		oss << "f" << pcFeat;
		return pcFeat;
	      },
	      correct_exs_false.size(),pose_mu_false,pose_cov_false);

    return latent_structural_gain;
  }

  void write(cv::FileStorage&fs, std::string&, const deformable_depth::RandomFeature&rf)
  {
    fs << "{";
    fs << "feature_type" << rf.feature_type;
    fs << "p" << rf.p;
    fs << "roi1" << rf.roi1;
    fs << "roi2" << rf.roi2;
    fs << "threshold" << rf.threshold;
    fs << "uuid" << rf.uuid;
    fs << "}";
  }

  ///
  /// SECTION: RandomHoughFeature
  ///
  RandomHoughFeature::RandomHoughFeature(vector<StructuredExample>&examples) :
    RandomFeature(examples)
  {
    times_voted_true = 0;
    times_voted_false = 0;
  }

  string RandomHoughFeature::get_uuid() const
  {
    return uuid;
  }

  double RandomHoughFeature::get_N_false_neg() const
  {
    return (1-correct_false)*get_N_false();
  }

  double RandomHoughFeature::get_N_false_pos() const
  {
    return correct_false*get_N_false();
  }

  double RandomHoughFeature::get_N_true_neg() const
  {
    return (1-correct_true)*get_N_true();
  }

  double RandomHoughFeature::get_N_true_pos() const
  {
    return correct_true*get_N_true();
  }

  int RandomHoughFeature::get_N_false() const
  {
    return N_false;
  }

  int RandomHoughFeature::get_N_true() const
  {
    return N_true;
  }

  void RandomHoughFeature::print_voting_history() const
  {
    log_file << printfpp("RandomFeature: votes %d (true) %d (false)",
			 (int)times_voted_true,(int)times_voted_false) << endl;
  }

  VoteResult RandomHoughFeature::vote(
    HoughOutputSpace& output,
    const StructuredWindow&swin,
    const PCAPose&pose) const
  {
    Point3d center = swin.ortho_detBBCenter();
    Point3d kernel_center = center;

    double correct_ratio;
    Mat voting_kernel;
    bool prediction = predict(swin);
    if(prediction)
    {
      // vote for true
      times_voted_true++;
      correct_ratio = correct_true;
      voting_kernel = vote_location.voting_kernel_true;
    }
    else
    {
      // vote for false
      times_voted_false++;
      correct_ratio = correct_false;
      voting_kernel = vote_location.voting_kernel_false;
    }
    kernel_center.x += vote_location.mu(prediction).at<double>(0);
    kernel_center.y += vote_location.mu(prediction).at<double>(1);

    // Call Spaces's vote function
    double conf = output.vote(prediction,correct_ratio,
		       kernel_center,center,voting_kernel,pose,vote_pose);

    VoteResult result;
    result.leaf = this;
    result.conf = conf;
    return result;
  }

  Mat offset_from_example(const vector<StructuredExample>&exs,int iter)
  {
    // grab current example
    const StructuredExample & ex = exs[iter];

    // get the offsets
    Point3d handBBCenter = ex.ortho_handBBCenter();
    Point3d detBBCenter = ex.ortho_detBBCenter();
    int off_x = handBBCenter.x - detBBCenter.x;
    int off_y = handBBCenter.y - detBBCenter.y;
    //int off_z = (handBBCenter.z - detBBCenter.z)/10;

    // write the factored parameters
    Mat sample(1,2,DataType<double>::type,Scalar::all(0));
    sample.at<double>(0,0) = off_x;
    sample.at<double>(0,1) = off_y;
    require_equal<int>(sample.rows,1);
    require_equal<int>(sample.cols,2);
    return sample;
  }

  void RandomFeature::split_props(
    const vector< StructuredExample >& examples,
    double&true_pos, double&false_pos, double&true_neg, double&false_neg)
  {
    vector<StructuredExample> exs_true,exs_false,correct_exs_true,correct_exs_false;
    split_examples(examples, exs_true, exs_false,
		   true_pos, false_pos, true_neg, false_neg,
		   correct_exs_true, correct_exs_false);
  }

  void RandomFeature::split_examples(
    const vector< StructuredExample >& examples,
    vector<StructuredExample> &exs_true,
    vector<StructuredExample> &exs_false,
    double&true_pos,
    double&false_pos,
    double&true_neg,
    double&false_neg,
    vector<StructuredExample> &correct_exs_true,
    vector<StructuredExample> &correct_exs_false
  )
  {
    // clear
    exs_true.clear();
    exs_false.clear();
    correct_exs_true.clear();
    correct_exs_false.clear();

    // compute
    atomic<long> count(0);
    for(const StructuredExample&ex : examples)
    {
      if(predict(ex))
      {
	exs_true.push_back(ex);
	if(ex.is_white() > .75)
	{
	  correct_exs_true.push_back(ex);
	  true_pos++;
	}
	else if(ex.is_black() <= 0)
	  true_neg++;
      }
      else
      {
	exs_false.push_back(ex);
	if(ex.is_white() > .75)
	{
	  correct_exs_false.push_back(ex);
	  false_pos++;
	}
	else if(ex.is_black() <= 0)
	  false_neg++;
      }

      long cur_count = count++;
      int stride = (examples.size()/10);
      if(stride > 0 && cur_count % stride == 0)
	log_file << printfpp("info_gain partition %d of %d",
			      (int)cur_count,(int)examples.size()) << endl;
    }
  }

  InformationGain RandomHoughFeature::info_gain(
    vector< StructuredExample >& examples,
    vector<StructuredExample> &exs_true,
    vector<StructuredExample> &exs_false,
    const PCAPose&pcaPose)
  {
    h0 = qnan; // not needed in practice entropy_gaussian(examples,totalMu,totalSigma,p_correct);

    double true_pos = 0, false_pos = 0, true_neg = 0, false_neg = 0;
    vector<StructuredExample> correct_exs_true;
    vector<StructuredExample> correct_exs_false;
    split_examples(examples,
		   exs_true, exs_false,
		   true_pos, false_pos,
		   true_neg, false_neg,
		   correct_exs_true,correct_exs_false);
    log_file << printfpp("Split %d/%d",(int)exs_true.size(),(int)exs_false.size()) << endl;
    if(exs_true.size() == 0 || exs_false.size() == 0)
    {
      InfoGain.shannon_info_gain = -inf;
      InfoGain.differential_info_gain = -inf;
      InfoGain.latent_structural_gain = -inf;
      return InfoGain;
    }

    // compute the branch probabilities
    double true_ratio = exs_true.size() / (double)examples.size();
    double false_ratio = exs_false.size() / (double)examples.size();
    double n_correct = correct_exs_true.size() + correct_exs_false.size();
    double correct_true_ratio = correct_exs_true.size() / n_correct;
    double correct_false_ratio = correct_exs_false.size() / n_correct;
    N_true = exs_true.size();
    N_false = exs_false.size();
    correct_true = true_pos/N_true;
    correct_false = false_pos/N_false;
    // compute the location differential_info_gain
    InfoGain.differential_info_gain =
	- true_ratio * entropy_gaussian(
	      [&](int i){
		return offset_from_example(exs_true,i);},
	      exs_true.size(),vote_location.mu_true,vote_location.cov_true)
	- false_ratio* entropy_gaussian([&](int i){
		return offset_from_example(exs_false,i);},
	      exs_false.size(),vote_location.mu_false,vote_location.cov_false);
    // compute the shannon_info_gain
    InfoGain.shannon_info_gain =
	- true_ratio * shannon_entropy({true_pos/exs_true.size(),true_neg/exs_true.size()})
	- false_ratio* shannon_entropy({false_pos/exs_false.size(),false_neg/exs_false.size()});
    // compute the info_gain in our latent space
    ostringstream oss;
    InfoGain.latent_structural_gain = structural_gain(
      correct_true_ratio, correct_false_ratio,
      correct_exs_true, correct_exs_false,pcaPose, oss,
      vote_pose.mu_true,vote_pose.cov_true,
      vote_pose.mu_false,vote_pose.cov_false);

    // compute the voting kernels
    vote_location.update_votes(2.5);
    vote_pose.update_votes(5);
    vote_pose.message = oss.str();

    log_file << *this << endl;

    return InfoGain;
  }

  void RandomHoughFeature::log_kernels() const
  {
    //log_im("voting_kernel_true",imageeq("",voting_kernel_true,false,false));
    //log_im("voting_kernel_false",imageeq("",voting_kernel_false,false,false));

    // generate the test text
    Mat test_text = image_text(
      printfpp("feat = %d thresh = %f",(int)feature_type,(double)this->threshold));

    // generate # the text
    Mat text_true = image_text(
      printfpp("%f %f",(double)correct_true,(double)N_true));
    Mat text_false = image_text(
      printfpp("%f %f",(double)correct_false,(double)N_false));
    Mat text = vertCat(text_true,text_false);

    Mat vis_sidebyside = vertCat(vote_location.log_kernels(),text);
    Mat vis_pose = vote_pose.log_kernels();
    vis_pose = rotate_colors(vis_pose,Quaternion(1,0,1,1).rotation_matrix());

    log_im("voting_kernels",vertCat(test_text,horizCat(vis_sidebyside,vis_pose)));
  }

  ostream& operator<< (ostream& os, const HoughVote&vote)
  {
    os << "mu_true: " << vote.mu_true << endl;
    os << "mu_false: " << vote.mu_false << endl;
    os << "cov_true: " << vote.cov_true << endl;
    os << "cov_false: " << vote.cov_false << endl;
    return os;
  }

  ostream& operator << (ostream& os, const RandomHoughFeature&rf)
  {
    static mutex m; lock_guard<mutex> l(m);
    os << printfpp("RandomFeature::info_gain H(examples) = %f",rf.h0) << endl;
    os << printfpp("RandomFeature::info_gain (%f,%f)",
		   rf.InfoGain.shannon_info_gain,
		   rf.InfoGain.differential_info_gain) << endl;
    os << "n_true: " << rf.N_true << endl;
    os << "n_false: " << rf.N_false << endl;
    os << "c0: " << rf.p_correct << endl;
    os << "correct_true: " << rf.correct_true << endl;
    os << "correct_false: " << rf.correct_false << endl;
    os << "vote_location: " << rf.vote_location << endl;
    os << "test pt: " << printfpp("(%f, %f)",(double)rf.p.x,(double)rf.p.y) << endl;
    os << "roi1: " << rf.roi1 << endl;
    os << "roi2: " << rf.roi2 << endl;
    os << "threshold: " << rf.threshold << endl;
    os << "feature_type: " << rf.feature_type << endl;

    return os;
  }

  RandomHoughFeature::RandomHoughFeature()
  {
  }

  InformationGain::InformationGain() :
    differential_info_gain(qnan),
    shannon_info_gain(qnan),
    latent_structural_gain(qnan)
  {
  }

  void write(FileStorage& fs, string& , const InformationGain& ig)
  {
    fs << "{";
    fs << "differential_info_gain" << ig.differential_info_gain;
    fs << "shannon_info_gain" << ig.shannon_info_gain;
    fs << "latent_structural_gain" << ig.latent_structural_gain;
    fs << "}";
  }

  void read(const FileNode& fn, InformationGain& ig, InformationGain )
  {
    fn["differential_info_gain"] >> ig.differential_info_gain;
    fn["shannon_info_gain"] >> ig.shannon_info_gain;
    fn["latent_structural_gain"] >> ig.latent_structural_gain;
  }

  void write(cv::FileStorage&fs, std::string&, const deformable_depth::HoughVote&vote)
  {
    fs << "{";
    fs << "mu_true" << vote.mu_true;
    fs << "mu_false" << vote.mu_false;
    fs << "cov_true" << vote.cov_true;
    fs << "cov_false" << vote.cov_false;
    fs << "sigmaInv_false" << vote.sigmaInv_false;
    fs << "sigmaInv_true" << vote.sigmaInv_true;
    fs << "voting_kernel_true" << vote.voting_kernel_true;
    fs << "voting_kernel_false" << vote.voting_kernel_false;
    fs << "}";
  }

  void write(FileStorage& fs, string& , const unique_ptr< RandomHoughFeature >& rf)
  {
    fs << "{";
    fs << "feature_type" << rf->feature_type;
    fs << "p" << rf->p;
    fs << "roi1" << rf->roi1;
    fs << "roi2" << rf->roi2;
    fs << "threshold" << rf->threshold;
    fs << "h0" << rf->h0;
    fs << "InfoGain" << rf->InfoGain;
    fs << "p_correct" << rf->p_correct;
    fs << "correct_true" << rf->correct_true;
    fs << "correct_false" << rf->correct_false;
    fs << "N_true" << rf->N_true;
    fs << "N_false" << rf->N_false;
    fs << "vote_location" << rf->vote_location;
    fs << "vote_pose" << rf->vote_pose;
    fs << "uuid" << rf->uuid;
    fs << "}";
  }

  void read(const cv::FileNode&fn, deformable_depth::HoughVote&vote, deformable_depth::HoughVote)
  {
    fn["mu_true"] >> vote.mu_true;
    fn["mu_false"] >> vote.mu_false;
    fn["cov_true"] >> vote.cov_true;
    fn["cov_false"] >> vote.cov_false;
    fn["sigmaInv_false"] >> vote.sigmaInv_false;
    fn["sigmaInv_true"] >> vote.sigmaInv_true;
    fn["voting_kernel_true"] >> vote.voting_kernel_true;
    fn["voting_kernel_false"] >> vote.voting_kernel_false;
  }

  void read(const FileNode& fn, unique_ptr< RandomHoughFeature >& rf, unique_ptr< RandomHoughFeature > )
  {
    rf.reset(new RandomHoughFeature());
    int ft; fn["feature_type"] >> ft; rf->feature_type = RandomHoughFeature::FeatureTypes(ft);
    read(fn["p"],rf->p,Point2d());
    deformable_depth::read<double>(fn["roi1"],rf->roi1,Rect_<double>());
    deformable_depth::read<double>(fn["roi2"],rf->roi2,Rect_<double>());
    fn["threshold"] >> rf->threshold;
    fn["h0"] >> rf->h0;
    fn["InfoGain"] >> rf->InfoGain;
    fn["p_correct"] >> rf->p_correct;
    fn["correct_true"] >> rf->correct_true;
    fn["correct_false"] >> rf->correct_false;
    fn["N_true"] >> rf->N_true;
    fn["N_false"] >> rf->N_false;
    fn["vote_location"] >> rf->vote_location;
    fn["vote_pose"] >> rf->vote_pose;
    if(!fn["uuid"].empty())
      fn["uuid"] >> rf->uuid;
    else
      rf->uuid = deformable_depth::uuid();
  }

  Mat RandomHoughFeature::get_cov_false() const
  {
    return vote_location.cov_false;
  }

  Mat RandomHoughFeature::get_cov_true() const
  {
    return vote_location.cov_true;
  }

  Mat RandomHoughFeature::get_mu_false() const
  {
    return vote_location.mu_false;
  }

  Mat RandomHoughFeature::get_mu_true() const
  {
    return vote_location.mu_true;
  }

  ///
  /// SECTION: Standalone functions
  ///
  vector<StructuredExample> extract_features(FeatureExtractionModel&feature_extractor,
					     vector< shared_ptr< MetaData > >& training_set)
  {
    return extract_features(training_set);
  }

  vector<StructuredExample>
    extract_features(
      vector< shared_ptr< MetaData > >& training_set)
  {
    log_file << "++extract_features" << endl;
    vector<StructuredExample> all_feats;
    TaskBlock extract_features("SRF_Model::Train extract_features");
    progressBars->set_progress("srf_extract_features",0,training_set.size());
    for(int iter = 0; iter < training_set.size(); ++iter)
    {
      extract_features.add_callee([&,iter]()
      {
	auto && ex = training_set.at(iter);
	progressBars->set_progress("srf_extract_features",iter,training_set.size());
	shared_ptr<const ImRGBZ> im = ex->load_im();
	DetectionFilter filt(-inf);
	filt.supress_feature = true;
	//filt.feat_pyr = shared_ptr<IFeatPyr>(new FauxFeatPyr(*im));
	//DetectionSet feats = feature_extractor.detect(*im,filt);
	filt.manifoldFn = manifoldFn_apxMin;
	DetectionSet feats = enumerate_windows(*im,filt);
	feats = removeTruncations(*im,feats);
	log_file << printfpp("SRFModel::train extracted %d examples from %s",
	  (int)feats.size(),ex->get_filename().c_str()) << endl;

	// append
	auto selected_gt = params::defaultSelectFn()(ex->get_positives());
	vector<StructuredExample> here_feats;
	for(auto && feat : feats)
	{
	  // allocated a structured example for each feature
	  StructuredExample s_ex;
	  s_ex.metadata = ex;
	  s_ex.detection = feat;
	  const MetaData&c_metadata = *ex;
	  s_ex.im = c_metadata.load_im();
	  {
	    here_feats.push_back(s_ex);
	  }
	}

	// make sure we get all positives through the filter
	logMissingPositives(*ex,feats);

	// accumulate the windows...
	{
	  static mutex m; unique_lock<mutex> l(m);
	  all_feats.insert(all_feats.end(),here_feats.begin(),here_feats.end());
	}
	// track memory consumption
	if(iter % 25 == 0)
	  dump_heap_profile();
      });
    }
    extract_features.execute();
    log_file << "--extract_features" << endl;
    progressBars->set_progress("srf_extract_features",0,0);
    return all_feats;
  }

  vector<StructuredExample> extract_gt_features(
    FeatureExtractionModel&feature_extractor,vector<StructuredExample>&all_feats)
  {
    map<MetaData*,StructuredExample> closest_matches;

    cout << "SRFModel::extract_gt_features begin" << endl;
    for(auto && feat : all_feats)
    {
      Rect_<double> bb_gt   = feat.metadata->get_positives().at("HandBB");
      Rect_<double> bb_cur;
      if(closest_matches[&*feat.metadata].detection != nullptr)
	bb_cur = closest_matches[&*feat.metadata].detection->BB;
      Rect_<double> bb_cand = feat.detection->BB;
      double old_ol = rectIntersect(bb_cur,bb_gt);
      double new_ol = rectIntersect(bb_cand,bb_gt);
      if(new_ol >= old_ol)
      {
	cout << printfpp("ol: %f => %f",old_ol,new_ol) << endl;
	closest_matches[&*feat.metadata] = feat;
      }
    }
    cout << "SRFModel::extract_gt_features selection complete, converting" << endl;

    // vectorize
    vector<StructuredExample> gt_feats;
    for(auto & pair : closest_matches)
    {
      Rect_<double>&bb = pair.second.detection->BB;
      Rect_<double> bb_gt   = pair.second.metadata->get_positives().at("HandBB");
      if(rectIntersect(bb,bb_gt) < .5)
	continue;
      bb = rectFromCenter(rectCenter(bb_gt),bb.size());

      //Mat im = pair.second.im->RGB.clone();
      //rectangle(im,bb.tl(),bb.br(),Scalar(255,0,0));
      //log_im("gt_bb",im);
      gt_feats.push_back(pair.second);
    }
    double accept_ratio = gt_feats.size()/static_cast<double>(closest_matches.size());
    log_file << printfpp("extract_gt_features, accepted %f percent",accept_ratio) << endl;
    return gt_feats;
  }

  vector< StructuredWindow > extract_windows(FeatureExtractionModel& feature_extractor,
					      shared_ptr< ImRGBZ >& sample_im)
  {
    // what were extracting from this frame
    vector<StructuredWindow> frame_wins;
    DetectionFilter filt(-inf);
    filt.supress_feature = true;
    DetectionSet windows = feature_extractor.detect(*sample_im,filt);
    for(auto && win : windows)
    {
      StructuredWindow swin;
      swin.detection = win;
      swin.im = sample_im;
    }

    return frame_wins;
  }
}


text:
import {Component} from 'angular2/core';
import {SignUpFormComponent} from './signup-form.component'

@Component({
    selector: 'my-app',
    template: `
		<signup-form></signup-form>
    `,
    directives :[SignUpFormComponent]
})
export class AppComponent {
}


text:
if (typeof define !== 'function') { var define = (require('../amdefine/node_modules/amdefine/amdefine'))(module); }

define({
    name: 'd'
})


text:
// flow-typed signature: 322663b29fff985a1988d5995a1c4f69
// flow-typed version: <<STUB>>/react-native-search-bar_v3.4.0/flow_v0.65.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'react-native-search-bar'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'react-native-search-bar' {
  declare module.exports: any;
}


text:
'use strict';

const request = require('supertest');
const express = require('express');
const path = require('path');
const MongoClient = require('mongodb').MongoClient;
const castToObjectId = require('mongodb').ObjectId;
const sinon = require('sinon');
const assert = require('assert');
const nock = require('nock');
const initObjectIdStub = require('objectid-stub');
const passport = require('passport');

const initRoutes = require('../../app/routes');

describe('OAuth XEE endpoints', () => {
  let context;
  const fakeState = new Buffer(JSON.stringify({
    contents: { fake: 'token' },
  })).toString('base64');

  before(done => {
    context = {
      env: { NODE_ENV: 'development' },
    };
    context.env.SESSION_SECRET = 'none';
    context.env.STATIC_PATH = path.join(__dirname, '..', '..', '..', 'mobile', 'www');
    context.env.XEE_ID = '123-456-789';
    context.env.XEE_SECRET = 'shhh-its-a-secret';
    context.tokens = {
      createToken: sinon.stub().returns({
        contents: { fake: 'token' },
      }),
      checkToken: sinon.stub().returns(true),
    };
    context.time = sinon.stub().returns(1664);
    context.passport = passport;
    context.logger = {
      error: sinon.spy(),
      debug: sinon.spy(),
      info: sinon.spy(),
    };
    context.createObjectId = initObjectIdStub({
      ctor: castToObjectId,
    });
    context.base = 'http://tripstory.insertafter.com';
    MongoClient.connect('mongodb://localhost:27017/tripstory_test')
      .then(db => {
        context.db = db;
        done();
      });
  });

  before(done => {
    context.app = express();
    initRoutes(context);
    done();
  });

  beforeEach(done => {
    context.bus = {
      trigger: sinon.spy(),
    };
    done();
  });

  afterEach(done => {
    context.db.collection('users').deleteMany({}, done);
  });

  describe('entry point', () => {

    it('should redirect to the OAuth page', done => {
      request(context.app).get('/auth/xee')
        .expect(302)
        .end((err, res) => {
          if(err) {
            return done(err);
          }
          assert(context.tokens.createToken.callCount, 1);
          assert.equal(
            res.headers.location,
            `https://cloud.xee.com/v1/auth/auth?response_type=code&redirect_uri=${encodeURIComponent(
  `${context.base}/auth/xee/callback`
)}&scope=user_get%20email_get%20car_get%20data_get%20location_get%20address_all%20accelerometer_get&state=${encodeURIComponent(fakeState)}&client_id=${context.env.XEE_ID}`
          );
          done();
        });
    });

  });

  describe('callback endpoint', () => {
    let accessTokenCall;
    let profileCall;

    beforeEach(() => {
      accessTokenCall = nock('https://cloud.xee.com:443', {
        encodedQueryParams: true,
      })
      .post(
        '/v1/auth/access_token.json',
        `grant_type=authorization_code&redirect_uri=${encodeURIComponent(
  `${context.base}/auth/xee/callback`
)}&client_id=${context.env.XEE_ID}&client_secret=${context.env.XEE_SECRET}&code=THISISIT`
      )
      .basicAuth({
        user: context.env.XEE_ID,
        pass: context.env.XEE_SECRET,
      })
      .reply(
        200, {
          access_token: 'COMMON_BOY',
          token_type: 'bearer',
          expires_in: '13060800',
          expires_at: 1467821352,
          refresh_token: 'COME_AGAIN_MAN',
        }, {
          'content-type': 'text/plain; charset=UTF-8',
        });

      profileCall = nock('https://cloud.xee.com:443', {
        encodedQueryParams: true,
      })
      .get('/v1/user/me.json')
      .query({
        access_token: 'COMMON_BOY',
      })
      .reply(200, {
        id: 1664,
        name: 'Froidure',
        firstName: 'Nicolas',
        gender: 1,
        nickName: '',
        role: 'dev',
        birthDate: '2015-11-22',
        licenseDeliveryDate: null,
      }, {
        'content-type': 'text/javascript; charset=UTF-8',
      });
    });

    describe('when user is not known', () => {

      it('should work', done => {
        const newUserId = context.createObjectId.next();

        request(context.app).get(
          `/auth/xee/callback?state=${encodeURIComponent(fakeState)}&client_id=${context.env.XEE_ID}&client_secret=${context.env.XEE_SECRET}&code=THISISIT` // eslint-disable-line
        )
          .expect(301)
          .end((err, res) => {
            if(err) {
              return done(err);
            }
            accessTokenCall.done();
            profileCall.done();
            context.db.collection('users').findOne({
              'contents.name': 'Nicolas Froidure',
            }).then(user => {
              assert(user, 'User was created!');
              assert.deepEqual(user, {
                _id: newUserId,
                contents: {
                  name: 'Nicolas Froidure',
                },
                friends_ids: [],
                cars: [],
                auth: {
                  xee: {
                    id: '1664',
                    accessToken: 'COMMON_BOY',
                    refreshToken: 'COME_AGAIN_MAN',
                  },
                },
                rights: [{
                  methods: 127,
                  path: '/api/v0/users/:_id/?.*',
                }, {
                  methods: 7,
                  path: '/api/v0/profile',
                }, {
                  methods: 8,
                  path: '/api/v0/logout',
                }],
              });
              assert.deepEqual(context.bus.trigger.args, [[{
                exchange: 'A_XEE_SIGNUP',
                contents: {
                  ip: '::ffff:127.0.0.1',
                  user_id: newUserId,
                },
              }]]);
              done();
            }).catch(done);
          });
      });

    });

    describe('when user is known', () => {

      beforeEach(done => {
        context.db.collection('users').insertOne({
          _id: castToObjectId('abbacacaabbacacaabbacaca'),
          contents: {
            name: 'Popol',
            email: 'popol@moon.u',
          },
          emailKeys: ['popol@moon.u'],
          passwordHash: '$2a$10$s4FQh8WjiYQfx6gdO4AXAePe7tj4HXoo8fIcTsjD6YGkZ/B2oDDpW',
          auth: {
            xee: {
              id: 1664,
              accessToken: 'COMMON_BOY',
              refreshToken: 'COME_AGAIN_MAN',
            },
          },
        }, done);
      });

      it('should work', done => {
        request(context.app).get(
          `/auth/xee/callback?state=${encodeURIComponent(fakeState)}&client_id=${context.env.XEE_ID}&client_secret=${context.env.XEE_SECRET}&code=THISISIT`
        )
          .expect(301)
          .end(err => {
            if(err) {
              return done(err);
            }
            accessTokenCall.done();
            profileCall.done();
            context.db.collection('users').findOne({
              _id: castToObjectId('abbacacaabbacacaabbacaca'),
            }).then(user => {
              assert(user, 'User was created!');
              assert.deepEqual(user, {
                _id: castToObjectId('abbacacaabbacacaabbacaca'),
                contents: {
                  name: 'Nicolas Froidure',
                  email: 'popol@moon.u',
                },
                auth: {
                  xee: {
                    id: 1664,
                    accessToken: 'COMMON_BOY',
                    refreshToken: 'COME_AGAIN_MAN',
                  },
                },
                emailKeys: ['popol@moon.u'],
                passwordHash: '$2a$10$s4FQh8WjiYQfx6gdO4AXAePe7tj4HXoo8fIcTsjD6YGkZ/B2oDDpW',
              });
              assert.deepEqual(context.bus.trigger.args, [[{
                exchange: 'A_XEE_LOGIN',
                contents: {
                  ip: '::ffff:127.0.0.1',
                  user_id: castToObjectId('abbacacaabbacacaabbacaca'),
                },
              }]]);
              done();
            }).catch(done);
          });
      });

    });

  });

});


text:
package org.xtreemfs.test.osd;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.xtreemfs.common.xloc.StripingPolicyImpl;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.checksums.ChecksumFactory;
import org.xtreemfs.foundation.checksums.provider.JavaChecksumProvider;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.util.FSUtils;
import org.xtreemfs.osd.OSDConfig;
import org.xtreemfs.osd.replication.ObjectSet;
import org.xtreemfs.osd.storage.FileMetadata;
import org.xtreemfs.osd.storage.HashStorageLayout;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.osd.storage.ObjectInformation;
import org.xtreemfs.osd.storage.SingleFileStorageLayout;
import org.xtreemfs.osd.storage.StorageLayout;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica;
import org.xtreemfs.test.SetupUtils;
import org.xtreemfs.test.TestHelper;

/**
 *
 * @author bjko
 */
public class StorageLayoutTest {
    @Rule
    public final TestRule testLog = TestHelper.testLog;

    static OSDConfig      config;

    @BeforeClass
    public static void initializeTest() throws Exception {
        Logging.start(SetupUtils.DEBUG_LEVEL);
        config = SetupUtils.createOSD1Config();
    }

    @Before
    public void setUp() throws Exception {
        FSUtils.delTree(new File(config.getObjDir()));
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testHashStorageLayoutBasics() throws Exception {

        HashStorageLayout layout = new HashStorageLayout(config, new MetadataCache());
        basicTests(layout);
    }

    @Test
    public void testHashStorageLayoutWithChecksumsBasics() throws Exception {

        JavaChecksumProvider j = new JavaChecksumProvider();
        ChecksumFactory.getInstance().addProvider(j);
        SetupUtils.CHECKSUMS_ON = true;
        OSDConfig configCSUM = SetupUtils.createOSD1Config();
        SetupUtils.CHECKSUMS_ON = false;
        HashStorageLayout layout = new HashStorageLayout(configCSUM, new MetadataCache());
        basicTests(layout);
    }

    @Test
    public void testSingleFileLayout() throws Exception {
        SingleFileStorageLayout layout = new SingleFileStorageLayout(config, new MetadataCache());
        basicTests(layout);
    }

    @Test
    public void testSingleFileStorageLayoutWithChecksumsBasics() throws Exception {

        JavaChecksumProvider j = new JavaChecksumProvider();
        ChecksumFactory.getInstance().addProvider(j);
        SetupUtils.CHECKSUMS_ON = true;
        OSDConfig configCSUM = SetupUtils.createOSD1Config();
        SetupUtils.CHECKSUMS_ON = false;
        SingleFileStorageLayout layout = new SingleFileStorageLayout(configCSUM, new MetadataCache());
        basicTests(layout);
    }

    @Test
    public void testHashStorageLayoutGetObjectList() throws Exception {

        HashStorageLayout layout = new HashStorageLayout(config, new MetadataCache());
        getObjectListTest(layout);
    }

    @Test
    public void testSingleFileStorageLayoutGetObjectList() throws Exception {

        SingleFileStorageLayout layout = new SingleFileStorageLayout(config, new MetadataCache());
        getObjectListTest(layout);
    }

    @Test
    public void testHashStorageLayoutGetFileIDList() throws Exception {

        HashStorageLayout layout = new HashStorageLayout(config, new MetadataCache());
        getFileIDListTest(layout);
    }

    @Test
    public void testSingleFileStorageLayoutGetFileIDList() throws Exception {

        SingleFileStorageLayout layout = new SingleFileStorageLayout(config, new MetadataCache());
        getFileIDListTest(layout);
    }

    /**
     * @param layout
     * @throws IOException
     */
    private void basicTests(StorageLayout layout) throws IOException {
        final String fileId = "ABCDEFG:0001";

        Replica r = Replica.newBuilder().setStripingPolicy(SetupUtils.getStripingPolicy(1, 64)).setReplicationFlags(0)
                .build();
        StripingPolicyImpl sp = StripingPolicyImpl.getPolicy(r, 0);// new RAID0(64, 1);

        /*
         * FileMetadata md = new FileMetadata(sp); md.initLatestObjectVersions(new HashMap<Long, Long>());
         * md.initLargestObjectVersions(new HashMap<Long, Long>()); md.initObjectChecksums(new HashMap<String, Long>());
         */

        FileMetadata md = layout.getFileMetadata(sp, fileId);
        assertNotNull(md);

        assertFalse(layout.fileExists(fileId));

        ReusableBuffer data = BufferPool.allocate(64);
        for (int i = 0; i < 64; i++) {
            data.put((byte) (48 + i));
        }
        data.flip();
        // write 64 bytes
        layout.writeObject(fileId, md, data, 0l, 0, 1l, false, false);

        // read full object
        ObjectInformation oinfo = layout.readObject(fileId, md, 0l, 0, StorageLayout.FULL_OBJECT_LENGTH, 1l);
        assertEquals(64, oinfo.getData().capacity());
        for (int i = 0; i < 64; i++) {
            assertEquals((byte) (48 + i), oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        // read object 1 (does not exist)
        oinfo = layout.readObject(fileId, md, 1l, 0, StorageLayout.FULL_OBJECT_LENGTH, 1l);
        assertEquals(ObjectInformation.ObjectStatus.DOES_NOT_EXIST, oinfo.getStatus());

        // range test
        oinfo = layout.readObject(fileId, md, 0l, 32, 32, 1l);
        assertEquals(32, oinfo.getData().capacity());
        for (int i = 32; i < 64; i++) {
            assertEquals((byte) (48 + i), oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        // range test
        oinfo = layout.readObject(fileId, md, 0l, 32, 1, 1l);
        assertEquals(1, oinfo.getData().capacity());
        for (int i = 32; i < 33; i++) {
            assertEquals((byte) (48 + i), oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        oinfo = layout.readObject(fileId, md, 0l, 32, 64, 1l);
        assertEquals(32, oinfo.getData().capacity());
        for (int i = 32; i < 64; i++) {
            assertEquals((byte) (48 + i), oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        // truncate to 32 byte
        layout.truncateObject(fileId, md, 0l, 32, 1, false);
        oinfo = layout.readObject(fileId, md, 0l, 32, 64, 1l);
        assertTrue(((oinfo.getData() == null) || (oinfo.getData().capacity() == 0)));
        BufferPool.free(oinfo.getData());

        // read (non-existent) data from offset 32
        oinfo = layout.readObject(fileId, md, 0l, 0, 32, 1l);
        assertEquals(32, oinfo.getData().capacity());
        for (int i = 0; i < 32; i++) {
            assertEquals((byte) (48 + i), oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        // truncate extend to 64 bytes
        layout.truncateObject(fileId, md, 0l, 64, 2, false);
        oinfo = layout.readObject(fileId, md, 0l, 32, 64, 2l);
        assertEquals(32, oinfo.getData().capacity());
        for (int i = 0; i < 32; i++) {
            assertEquals((byte) 0, oinfo.getData().get());
        }
        BufferPool.free(oinfo.getData());

        // write more objects...
        // obj 1 = hole
        // obj 2 = second half
        // obj 3 = full

        data = BufferPool.allocate(32);
        for (int i = 0; i < 32; i++) {
            data.put((byte) (48 + i));
        }
        data.flip();
        // write 64 bytes
        layout.writeObject(fileId, md, data, 2l, 0, 1l, false, false);

        data = BufferPool.allocate(64);
        for (int i = 0; i < 64; i++) {
            data.put((byte) (48 + i));
        }
        data.flip();
        // write 64 bytes
        layout.writeObject(fileId, md, data, 3l, 0, 1l, false, false);

        // read object 1... should be all zeros or zero padding
        oinfo = layout.readObject(fileId, md, 1l, 0, sp.getStripeSizeForObject(1), 1l);
        if (oinfo.getStatus() == ObjectInformation.ObjectStatus.PADDING_OBJECT) {
            // fine
        } else if (oinfo.getStatus() == ObjectInformation.ObjectStatus.DOES_NOT_EXIST) {
            // also fine
        } else {
            // we expect full stripe size of zeros
            assertEquals(sp.getStripeSizeForObject(1), oinfo.getData().capacity());
            for (int i = 0; i < sp.getStripeSizeForObject(1); i++) {
                assertEquals((byte) 0, oinfo.getData().get());
            }
            BufferPool.free(oinfo.getData());
        }

    }

    private void getObjectListTest(StorageLayout layout) throws IOException {
        final String fileId = "ABCDEFG:0001";

        Replica r = Replica.newBuilder().setStripingPolicy(SetupUtils.getStripingPolicy(1, 64)).setReplicationFlags(0)
                .build();
        StripingPolicyImpl sp = StripingPolicyImpl.getPolicy(r, 0);// new RAID0(64, 1);

        FileMetadata md = layout.getFileMetadata(sp, fileId);
        assertNotNull(md);

        assertFalse(layout.fileExists(fileId));
        assertEquals(0, layout.getObjectSet(fileId, md).size());

        ReusableBuffer data = BufferPool.allocate(64);
        for (int i = 0; i < 64; i++) {
            data.put((byte) (48 + i));
        }

        // objects to write
        long objectNos[] = { 0, 2, 4, 8, 10, 12, 20, 24, 32, 44, 46, 48, 50 };

        // write objects
        for (long objNo : objectNos) {
            layout.writeObject(fileId, md, data.createViewBuffer(), objNo, 0, 1, false, false);
        }
        BufferPool.free(data);

        ObjectSet objectList = layout.getObjectSet(fileId, md);
        // check
        ObjectSet objectNosList = new ObjectSet(1, 0, objectNos.length);
        for (long object : objectNos)
            objectNosList.add(object);
        assertTrue(objectList.equals(objectNosList));
    }

    private void getFileIDListTest(StorageLayout layout) throws IOException {
        final ArrayList<String> fileIDs = new ArrayList<String>();
        fileIDs.add("0002:ABCDEF");
        fileIDs.add("0012:GHIJKL");
        fileIDs.add("0123:MNOPQR");
        fileIDs.add("1234:STUVWX");

        Replica r = Replica.newBuilder().setStripingPolicy(SetupUtils.getStripingPolicy(1, 64)).setReplicationFlags(0)
                .build();
        StripingPolicyImpl sp = StripingPolicyImpl.getPolicy(r, 0);// new RAID0(64, 1);

        // create some data
        ReusableBuffer data = BufferPool.allocate(64);
        for (int i = 0; i < 64; i++) {
            data.put((byte) (48 + i));
        }
        data.flip();

        // create some files
        for (String f : fileIDs) {
            String fileId = f;
            FileMetadata md = layout.getFileMetadata(sp, fileId);

            assertNotNull(md);

            assertFalse(layout.fileExists(fileId));

            // write 64 bytes
            layout.writeObject(fileId, md, data.createViewBuffer(), 0l, 0, 1l, false, false);
        }

        ArrayList<String> newFileIDs = layout.getFileIDList();
        // compare fileIDs with newFileIDs
        assertTrue(newFileIDs.containsAll(fileIDs));
        assertTrue(fileIDs.containsAll(newFileIDs));
    }

}


text:
namespace OmniAPI.Services.Messaging {
    public class MessagePage {
        /// <summary>
        /// ID for the "source". Used to show source graphics, if set.
        /// </summary>
        public readonly string SourceId;

        /// <summary>
        /// The message body.
        /// </summary>
        public readonly string Body;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:OmniAPI.Services.Messaging.MessagePage"/> class.
        /// </summary>
        /// <param name="body">Body.</param>
        public MessagePage(string body) : this(null, body) {}

        /// <summary>
        /// Initializes a new instance of the <see cref="T:OmniAPI.Services.Messaging.MessagePage"/> class.
        /// </summary>
        /// <param name="sourceId">Source identifier.</param>
        /// <param name="body">Body.</param>
        public MessagePage(string sourceId, string body) {
            this.SourceId = sourceId;
            this.Body = body;
        }
    }
}


text:
package org.apache.hadoop.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Util class to stores ips/hosts/subnets.
 */
public class CombinedIPList implements IPList {

  public static final Logger LOG =
      LoggerFactory.getLogger(CombinedIPList.class);

  private final IPList[] networkLists;

  public CombinedIPList(String fixedBlackListFile,
      String variableBlackListFile, long cacheExpiryInSeconds) {

    IPList fixedNetworkList = new FileBasedIPList(fixedBlackListFile);
    if (variableBlackListFile != null) {
      IPList variableNetworkList = new CacheableIPList(
          new FileBasedIPList(variableBlackListFile), cacheExpiryInSeconds);
      networkLists = new IPList[]{fixedNetworkList, variableNetworkList};
    } else {
      networkLists = new IPList[]{fixedNetworkList};
    }
  }

  @Override
  public boolean isIn(String ipAddress) {
    if (ipAddress == null) {
      throw new IllegalArgumentException("ipAddress is null");
    }

    for (IPList networkList : networkLists) {
      if (networkList.isIn(ipAddress)) {
        return true;
      }
    }
    return false;
  }
}