text:
package containerservice

// 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/autorest/validation"
	"net/http"
)

// Client is the compute Client
type Client struct {
	BaseClient
}

// NewClient creates an instance of the Client client.
func NewClient(subscriptionID string) Client {
	return NewClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

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

// CreateOrUpdate the operation to create or update a container service.
// Parameters:
// resourceGroupName - the name of the resource group.
// containerServiceName - the name of the container service within the given subscription and resource group.
// parameters - parameters supplied to the Create Container Service operation.
func (client Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, containerServiceName string, parameters ContainerService) (result CreateOrUpdateFuture, err error) {
	if err := validation.Validate([]validation.Validation{
		{TargetValue: parameters,
			Constraints: []validation.Constraint{{Target: "parameters.Properties", Name: validation.Null, Rule: false,
				Chain: []validation.Constraint{{Target: "parameters.Properties.MasterProfile", Name: validation.Null, Rule: true,
					Chain: []validation.Constraint{{Target: "parameters.Properties.MasterProfile.DNSPrefix", Name: validation.Null, Rule: true, Chain: nil}}},
					{Target: "parameters.Properties.AgentPoolProfiles", Name: validation.Null, Rule: true, Chain: nil},
					{Target: "parameters.Properties.WindowsProfile", Name: validation.Null, Rule: false,
						Chain: []validation.Constraint{{Target: "parameters.Properties.WindowsProfile.AdminUsername", Name: validation.Null, Rule: true, Chain: nil},
							{Target: "parameters.Properties.WindowsProfile.AdminPassword", Name: validation.Null, Rule: true, Chain: nil},
						}},
					{Target: "parameters.Properties.LinuxProfile", Name: validation.Null, Rule: true,
						Chain: []validation.Constraint{{Target: "parameters.Properties.LinuxProfile.AdminUsername", Name: validation.Null, Rule: true, Chain: nil},
							{Target: "parameters.Properties.LinuxProfile.SSH", Name: validation.Null, Rule: true, Chain: nil},
						}},
				}}}}}); err != nil {
		return result, validation.NewError("containerservice.Client", "CreateOrUpdate", err.Error())
	}

	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, containerServiceName, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	result, err = client.CreateOrUpdateSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "CreateOrUpdate", result.Response(), "Failure sending request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client Client) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, containerServiceName string, parameters ContainerService) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"containerServiceName": autorest.Encode("path", containerServiceName),
		"resourceGroupName":    autorest.Encode("path", resourceGroupName),
		"subscriptionId":       autorest.Encode("path", client.SubscriptionID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client Client) CreateOrUpdateSender(req *http.Request) (future CreateOrUpdateFuture, err error) {
	sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
	future.Future = azure.NewFuture(req)
	future.req = req
	_, err = future.Done(sender)
	if err != nil {
		return
	}
	err = autorest.Respond(future.Response(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted))
	return
}

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

// Delete the operation to delete a container service.
// Parameters:
// resourceGroupName - the name of the resource group.
// containerServiceName - the name of the container service within the given subscription and resource group.
func (client Client) Delete(ctx context.Context, resourceGroupName string, containerServiceName string) (result DeleteFuture, err error) {
	req, err := client.DeletePreparer(ctx, resourceGroupName, containerServiceName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "Delete", nil, "Failure preparing request")
		return
	}

	result, err = client.DeleteSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "Delete", result.Response(), "Failure sending request")
		return
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client Client) DeletePreparer(ctx context.Context, resourceGroupName string, containerServiceName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"containerServiceName": autorest.Encode("path", containerServiceName),
		"resourceGroupName":    autorest.Encode("path", resourceGroupName),
		"subscriptionId":       autorest.Encode("path", client.SubscriptionID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client Client) DeleteSender(req *http.Request) (future DeleteFuture, err error) {
	sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
	future.Future = azure.NewFuture(req)
	future.req = req
	_, err = future.Done(sender)
	if err != nil {
		return
	}
	err = autorest.Respond(future.Response(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
	return
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get the operation to get a container service.
// Parameters:
// resourceGroupName - the name of the resource group.
// containerServiceName - the name of the container service within the given subscription and resource group.
func (client Client) Get(ctx context.Context, resourceGroupName string, containerServiceName string) (result ContainerService, err error) {
	req, err := client.GetPreparer(ctx, resourceGroupName, containerServiceName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "Get", nil, "Failure preparing request")
		return
	}

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

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

	return
}

// GetPreparer prepares the Get request.
func (client Client) GetPreparer(ctx context.Context, resourceGroupName string, containerServiceName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"containerServiceName": autorest.Encode("path", containerServiceName),
		"resourceGroupName":    autorest.Encode("path", resourceGroupName),
		"subscriptionId":       autorest.Encode("path", client.SubscriptionID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices/{containerServiceName}", 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 Client) GetSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

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

// ListByResourceGroup the operation to list container services.
// Parameters:
// resourceGroupName - the name of the resource group.
func (client Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListResult, err error) {
	req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "ListByResourceGroup", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByResourceGroupSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "containerservice.Client", "ListByResourceGroup", resp, "Failure sending request")
		return
	}

	result, err = client.ListByResourceGroupResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "containerservice.Client", "ListByResourceGroup", resp, "Failure responding to request")
	}

	return
}

// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client Client) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

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

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/containerServices", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client Client) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client Client) ListByResourceGroupResponder(resp *http.Response) (result ListResult, 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:
from proteus.default_p import *
from proteus.mprans import RANS2P
from proteus import Context

ct = Context.get()
domain = ct.domain
nd = domain.nd
mesh = domain.MeshOptions
genMesh = mesh.genMesh
movingDomain = ct.movingDomain
T = ct.T

LevelModelType = RANS2P.LevelModel
if ct.useOnlyVF:
    LS_model = None
else:
    LS_model = 2
if ct.useRANS >= 1:
    Closure_0_model = 5
    Closure_1_model = 6
    if ct.useOnlyVF:
        Closure_0_model = 2
        Closure_1_model = 3
else:
    Closure_0_model = None
    Closure_1_model = None

coefficients = RANS2P.Coefficients(epsFact=ct.epsFact_viscosity,
                                   sigma=0.0,
                                   rho_0=ct.rho_0,
                                   nu_0=ct.nu_0,
                                   rho_1=ct.rho_1,
                                   nu_1=ct.nu_1,
                                   g=ct.g,
                                   nd=domain.nd,
                                   ME_model=0,
                                   VF_model=1,
                                   LS_model=LS_model,
                                   Closure_0_model=Closure_0_model,
                                   Closure_1_model=Closure_1_model,
                                   epsFact_density=ct.epsFact_density,
                                   stokes=False,
                                   useVF=ct.useVF,
                                   useRBLES=ct.useRBLES,
                                   useMetrics=ct.useMetrics,
                                   eb_adjoint_sigma=1.0,
                                   eb_penalty_constant=ct.weak_bc_penalty_constant,
                                   forceStrongDirichlet=ct.ns_forceStrongDirichlet,
                                   turbulenceClosureModel=ct.ns_closure,
                                   movingDomain=movingDomain)

dirichletConditions = {
    0: lambda x, flag: domain.bc[flag].p_dirichlet.init_cython(),
    1: lambda x, flag: domain.bc[flag].u_dirichlet.init_cython(),
    2: lambda x, flag: domain.bc[flag].v_dirichlet.init_cython()
}

advectiveFluxBoundaryConditions = {
    0: lambda x, flag: domain.bc[flag].p_advective.init_cython(),
    1: lambda x, flag: domain.bc[flag].u_advective.init_cython(),
    2: lambda x, flag: domain.bc[flag].v_advective.init_cython()
}

diffusiveFluxBoundaryConditions = {
    0: {},
    1: {1: lambda x, flag: domain.bc[flag].u_diffusive.init_cython()},
    2: {2: lambda x, flag: domain.bc[flag].v_diffusive.init_cython()}
}

class PerturbedSurface_p:
    def __init__(self, waterLevel):
        self.waterLevel = waterLevel

    def uOfXT(self, x, t):
        if ct.signedDistance(x) < 0:
            return -(ct.tank_dim[1] - self.waterLevel) * ct.rho_1 * ct.g[1] \
                   - (self.waterLevel -x[1]) * ct.rho_0 * ct.g[1]
        else:
            return -(ct.tank_dim[1] - self.waterLevel) * ct.rho_1 * ct.g[1]

class AtRest:
    def __init__(self):
        pass

    def uOfXT(self, x, t):
        return 0.0

class initialVelocity_u:
    def __init__(self):
        pass

    def uOfXT(self, x, t):
        if x[0] < ct.obstacle_x_start:
            return ct.twpflowVelocity_u(x, 0)
        elif x[0] < ct.tank_dim[0]:  #xSponge_2:
            return ct.twpflowVelocity_u_D(x, 0)
        else:
            return 0.0

initialConditions = {0: PerturbedSurface_p(ct.inflow_level),
                     1: initialVelocity_u(),
                     2: AtRest()}

redpajama_set_name: RedPajamaGithub


text:
@interface UIView (AppViews)

@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat bottomY;
@property (nonatomic, assign) CGFloat endX;
@property (nonatomic, assign) CGPoint origin;
@property (nonatomic, assign) CGSize  size;

@end


text:
package flagutil

import (
	"crypto/rsa"
	"errors"
	"flag"
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go/v4"
	"github.com/sirupsen/logrus"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"

	"k8s.io/test-infra/prow/config/secret"
	"k8s.io/test-infra/prow/git"
	"k8s.io/test-infra/prow/github"
)

// GitHubOptions holds options for interacting with GitHub.
//
// Set AllowAnonymous to be true if you want to allow anonymous github access.
// Set AllowDirectAccess to be true if you want to suppress warnings on direct github access (without ghproxy).
type GitHubOptions struct {
	Host              string
	endpoint          Strings
	graphqlEndpoint   string
	TokenPath         string
	AllowAnonymous    bool
	AllowDirectAccess bool
	AppID             string
	AppPrivateKeyPath string

	ThrottleHourlyTokens int
	ThrottleAllowBurst   int

	OrgThrottlers       Strings
	parsedOrgThrottlers map[string]throttlerSettings

	// These will only be set after a github client was retrieved for the first time
	tokenGenerator github.TokenGenerator
	userGenerator  github.UserGenerator

	// the following options determine how the client behaves around retries
	maxRequestTime time.Duration
	maxRetries     int
	max404Retries  int
	initialDelay   time.Duration
	maxSleepTime   time.Duration
}

type throttlerSettings struct {
	hourlyTokens int
	burst        int
}

// flagParams struct is used indirectly by users of this package to customize
// the common flags behavior, such as providing their own default values
// or suppressing presence of certain flags.
type flagParams struct {
	defaults GitHubOptions

	disableThrottlerOptions bool
}

type FlagParameter func(options *flagParams)

// ThrottlerDefaults allows to customize the default values of flags
// that control the throttler behavior. Setting `hourlyTokens` to zero
// disables throttling by default.
func ThrottlerDefaults(hourlyTokens, allowedBursts int) FlagParameter {
	return func(o *flagParams) {
		o.defaults.ThrottleHourlyTokens = hourlyTokens
		o.defaults.ThrottleAllowBurst = allowedBursts
	}
}

// DisableThrottlerOptions suppresses the presence of throttler-related flags,
// effectively disallowing external users to parametrize default throttling
// behavior. This is useful mostly when a program creates multiple GH clients
// with different behavior.
func DisableThrottlerOptions() FlagParameter {
	return func(o *flagParams) {
		o.disableThrottlerOptions = true
	}
}

// AddCustomizedFlags injects GitHub options into the given FlagSet. Behavior can be customized
// via the functional options.
func (o *GitHubOptions) AddCustomizedFlags(fs *flag.FlagSet, paramFuncs ...FlagParameter) {
	o.addFlags(fs, paramFuncs...)
}

// AddFlags injects GitHub options into the given FlagSet
func (o *GitHubOptions) AddFlags(fs *flag.FlagSet) {
	o.addFlags(fs)
}

func (o *GitHubOptions) addFlags(fs *flag.FlagSet, paramFuncs ...FlagParameter) {
	params := flagParams{
		defaults: GitHubOptions{
			Host:            github.DefaultHost,
			endpoint:        NewStrings(github.DefaultAPIEndpoint),
			graphqlEndpoint: github.DefaultGraphQLEndpoint,
		},
	}

	for _, parametrize := range paramFuncs {
		parametrize(&params)
	}

	defaults := params.defaults
	fs.StringVar(&o.Host, "github-host", defaults.Host, "GitHub's default host (may differ for enterprise)")
	o.endpoint = NewStrings(defaults.endpoint.Strings()...)
	fs.Var(&o.endpoint, "github-endpoint", "GitHub's API endpoint (may differ for enterprise).")
	fs.StringVar(&o.graphqlEndpoint, "github-graphql-endpoint", defaults.graphqlEndpoint, "GitHub GraphQL API endpoint (may differ for enterprise).")
	fs.StringVar(&o.TokenPath, "github-token-path", defaults.TokenPath, "Path to the file containing the GitHub OAuth secret.")
	fs.StringVar(&o.AppID, "github-app-id", defaults.AppID, "ID of the GitHub app. If set, requires --github-app-private-key-path to be set and --github-token-path to be unset.")
	fs.StringVar(&o.AppPrivateKeyPath, "github-app-private-key-path", defaults.AppPrivateKeyPath, "Path to the private key of the github app. If set, requires --github-app-id to bet set and --github-token-path to be unset")

	if !params.disableThrottlerOptions {
		fs.IntVar(&o.ThrottleHourlyTokens, "github-hourly-tokens", defaults.ThrottleHourlyTokens, "If set to a value larger than zero, enable client-side throttling to limit hourly token consumption. If set, --github-allowed-burst must be positive too.")
		fs.IntVar(&o.ThrottleAllowBurst, "github-allowed-burst", defaults.ThrottleAllowBurst, "Size of token consumption bursts. If set, --github-hourly-tokens must be positive too and set to a higher or equal number.")
		fs.Var(&o.OrgThrottlers, "github-throttle-org", "Throttler settings for a specific org in org:hourlyTokens:burst format. Can be passed multiple times. Only valid when using github apps auth.")
	}

	fs.DurationVar(&o.maxRequestTime, "github-client.request-timeout", github.DefaultMaxSleepTime, "Timeout for any single request to the GitHub API.")
	fs.IntVar(&o.maxRetries, "github-client.max-retries", github.DefaultMaxRetries, "Maximum number of retries that will be used for a failing request to the GitHub API.")
	fs.IntVar(&o.max404Retries, "github-client.max-404-retries", github.DefaultMax404Retries, "Maximum number of retries that will be used for a 404-ing request to the GitHub API.")
	fs.DurationVar(&o.maxSleepTime, "github-client.backoff-timeout", github.DefaultMaxSleepTime, "Largest allowable Retry-After time for requests to the GitHub API.")
	fs.DurationVar(&o.initialDelay, "github-client.initial-delay", github.DefaultInitialDelay, "Initial delay before retries begin for requests to the GitHub API.")
}

func (o *GitHubOptions) parseOrgThrottlers() error {
	if len(o.OrgThrottlers.vals) == 0 {
		return nil
	}

	if o.AppID == "" {
		return errors.New("--github-throttle-org was passed, but client doesn't use apps auth")
	}

	o.parsedOrgThrottlers = make(map[string]throttlerSettings, len(o.OrgThrottlers.vals))
	var errs []error
	for _, orgThrottler := range o.OrgThrottlers.vals {
		colonSplit := strings.Split(orgThrottler, ":")
		if len(colonSplit) != 3 {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s is not in org:hourlyTokens:burst format", orgThrottler))
			continue
		}
		org, hourlyTokensString, burstString := colonSplit[0], colonSplit[1], colonSplit[2]
		hourlyTokens, err := strconv.ParseInt(hourlyTokensString, 10, 32)
		if err != nil {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s is not in org:hourlyTokens:burst format: hourlyTokens is not an int", orgThrottler))
			continue
		}
		burst, err := strconv.ParseInt(burstString, 10, 32)
		if err != nil {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s is not in org:hourlyTokens:burst format: burst is not an int", orgThrottler))
			continue
		}
		if hourlyTokens < 1 {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s: hourlyTokens must be > 0", orgThrottler))
			continue
		}
		if burst < 1 {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s: burst must be > 0", orgThrottler))
			continue
		}
		if burst > hourlyTokens {
			errs = append(errs, fmt.Errorf("-github-throttle-org=%s: burst must not be greater than hourlyTokens", orgThrottler))
			continue
		}
		if _, alreadyExists := o.parsedOrgThrottlers[org]; alreadyExists {
			errs = append(errs, fmt.Errorf("got multiple -github-throttle-org for the %s org", org))
			continue
		}
		o.parsedOrgThrottlers[org] = throttlerSettings{hourlyTokens: int(hourlyTokens), burst: int(burst)}
	}

	return utilerrors.NewAggregate(errs)
}

// Validate validates GitHub options. Note that validate updates the GitHubOptions
// to add default values for TokenPath and graphqlEndpoint.
func (o *GitHubOptions) Validate(bool) error {
	endpoints := o.endpoint.Strings()
	for i, uri := range endpoints {
		if uri == "" {
			endpoints[i] = github.DefaultAPIEndpoint
		} else if _, err := url.ParseRequestURI(uri); err != nil {
			return fmt.Errorf("invalid -github-endpoint URI: %q", uri)
		}
	}

	if o.TokenPath != "" && (o.AppID != "" || o.AppPrivateKeyPath != "") {
		return fmt.Errorf("--token-path is mutually exclusive with --app-id and --app-private-key-path")
	}
	if o.AppID == "" != (o.AppPrivateKeyPath == "") {
		return errors.New("--app-id and --app-private-key-path must be set together")
	}

	if o.TokenPath != "" && len(endpoints) == 1 && endpoints[0] == github.DefaultAPIEndpoint && !o.AllowDirectAccess {
		logrus.Warn("It doesn't look like you are using ghproxy to cache API calls to GitHub! This has become a required component of Prow and other components will soon be allowed to add features that may rapidly consume API ratelimit without caching. Starting May 1, 2020 use Prow components without ghproxy at your own risk! https://github.com/kubernetes/test-infra/tree/master/ghproxy#ghproxy")
	}

	if o.graphqlEndpoint == "" {
		o.graphqlEndpoint = github.DefaultGraphQLEndpoint
	} else if _, err := url.Parse(o.graphqlEndpoint); err != nil {
		return fmt.Errorf("invalid -github-graphql-endpoint URI: %q", o.graphqlEndpoint)
	}

	if (o.ThrottleHourlyTokens > 0) != (o.ThrottleAllowBurst > 0) {
		if o.ThrottleHourlyTokens == 0 {
			// Tolerate `--github-hourly-tokens=0` alone to disable throttling
			o.ThrottleAllowBurst = 0
		} else {
			return errors.New("--github-hourly-tokens and --github-allowed-burst must be either both higher than zero or both equal to zero")
		}
	}
	if o.ThrottleAllowBurst > o.ThrottleHourlyTokens {
		return errors.New("--github-allowed-burst must not be larger than --github-hourly-tokens")
	}

	return o.parseOrgThrottlers()
}

// GitHubClientWithLogFields returns a GitHub client with extra logging fields
func (o *GitHubOptions) GitHubClientWithLogFields(dryRun bool, fields logrus.Fields) (github.Client, error) {
	client, err := o.githubClient(dryRun)
	if err != nil {
		return nil, err
	}
	return client.WithFields(fields), nil
}

func (o *GitHubOptions) githubClient(dryRun bool) (github.Client, error) {
	fields := logrus.Fields{}
	options := o.baseClientOptions()
	options.DryRun = dryRun
	if o.TokenPath == "" {
		logrus.Warn("empty -github-token-path, will use anonymous github client")
		options.GetToken = func() []byte {
			return []byte{}
		}
	} else {
		if err := secret.Add(o.TokenPath); err != nil {
			return nil, fmt.Errorf("failed to add GitHub token to secret agent: %w", err)
		}
		options.GetToken = secret.GetTokenGenerator(o.TokenPath)
	}

	if o.AppPrivateKeyPath != "" {
		if err := secret.Add(o.AppPrivateKeyPath); err != nil {
			return nil, fmt.Errorf("failed to add the the key from --app-private-key-path to secret agent: %w", err)
		}
		options.AppPrivateKey = func() *rsa.PrivateKey {
			raw := secret.GetTokenGenerator(o.AppPrivateKeyPath)()
			privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(raw)
			// TODO alvaroaleman: Add hooks to the SecretAgent
			if err != nil {
				panic(fmt.Sprintf("failed to parse private key: %v", err))
			}
			return privateKey
		}

	}

	optionallyThrottled := func(c github.Client) (github.Client, error) {
		// Throttle handles zeros as "disable throttling" so we do not need to call it conditionally
		if err := c.Throttle(o.ThrottleHourlyTokens, o.ThrottleAllowBurst); err != nil {
			return nil, fmt.Errorf("failed to throttle: %w", err)
		}
		for org, settings := range o.parsedOrgThrottlers {
			if err := c.Throttle(settings.hourlyTokens, settings.burst, org); err != nil {
				return nil, fmt.Errorf("failed to set up throttling for org %s: %w", org, err)
			}
		}
		return c, nil
	}

	tokenGenerator, userGenerator, client := github.NewClientFromOptions(fields, options)
	o.tokenGenerator = tokenGenerator
	o.userGenerator = userGenerator
	return optionallyThrottled(client)
}

// baseClientOptions populates client options that are derived from flags without processing
func (o *GitHubOptions) baseClientOptions() github.ClientOptions {
	return github.ClientOptions{
		Censor:          secret.Censor,
		AppID:           o.AppID,
		GraphqlEndpoint: o.graphqlEndpoint,
		Bases:           o.endpoint.Strings(),
		MaxRequestTime:  o.maxRequestTime,
		InitialDelay:    o.initialDelay,
		MaxSleepTime:    o.maxSleepTime,
		MaxRetries:      o.maxRetries,
		Max404Retries:   o.max404Retries,
	}
}

// GitHubClient returns a GitHub client.
func (o *GitHubOptions) GitHubClient(dryRun bool) (github.Client, error) {
	return o.GitHubClientWithLogFields(dryRun, logrus.Fields{})
}

// GitHubClientWithAccessToken creates a GitHub client from an access token.
func (o *GitHubOptions) GitHubClientWithAccessToken(token string) github.Client {
	options := o.baseClientOptions()
	options.GetToken = func() []byte { return []byte(token) }
	_, _, client := github.NewClientFromOptions(logrus.Fields{}, options)
	return client
}

// GitClient returns a Git client.
func (o *GitHubOptions) GitClient(dryRun bool) (client *git.Client, err error) {
	client, err = git.NewClientWithHost(o.Host)
	if err != nil {
		return nil, err
	}

	// We must capture the value of client here to prevent issues related
	// to the use of named return values when an error is encountered.
	// Without this, we risk a nil pointer dereference.
	defer func(client *git.Client) {
		if err != nil {
			client.Clean()
		}
	}(client)

	user, generator, err := o.getGitAuthentication(dryRun)
	if err != nil {
		return nil, fmt.Errorf("failed to get git authentication: %w", err)
	}
	client.SetCredentials(user, generator)

	return client, nil
}

func (o *GitHubOptions) getGitAuthentication(dryRun bool) (string, git.GitTokenGenerator, error) {
	// the client must have been created at least once for us to have generators
	if o.userGenerator == nil {
		if _, err := o.GitHubClient(dryRun); err != nil {
			return "", nil, fmt.Errorf("error getting GitHub client: %w", err)
		}
	}

	login, err := o.userGenerator()
	if err != nil {
		return "", nil, fmt.Errorf("error getting bot name: %w", err)
	}
	return login, git.GitTokenGenerator(o.tokenGenerator), nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarCommander.Types
{
    public enum ShipConfigurationType
    {
        Heavy,
        Light,
        Balanced
    }
}


text:
require 'test_helper'

class VirtualizableTest < ActiveSupport::TestCase
  def test_act_as_virtualizable
    assert_respond_to ActiveRecord::Base, :acts_as_virtualizable
    assert_respond_to Car, :federate
  end

  def test_simple_mapping
    assert Car.data_mapping.key? :color
    assert_equal [:manufacturer], Car.data_mapping[:color]
  end

  def test_aggregated_mapping
    assert Car::Audi.data_mapping.key? :price
    assert_equal [:manufacturer, :dealership].sort, Car::Audi.data_mapping[:price].sort
  end

  def test_attributes
    assert_respond_to Car.new, :color
    assert_respond_to Car.new, :price
  end

  def test_has_many_data_sources
    assert_respond_to Car.new, :data_sources
    assert_equal 0, Car.new.data_sources.count
  end
end


text:
namespace Sequencing.WeatherApp.Models
{
    using System;
    using System.Collections.Generic;

    public partial class SendForecast
    {
        public long UserId { get; set; }
        public long SendForecastID { get; set; }
        public long WeatherCond { get; set; }
        public long VitaminD { get; set; }
        public long MelanomaRisk { get; set; }
        public System.DateTime ForecastDate { get; set; }
        public int AppTypeId { get; set; }

        public virtual Condition Condition { get; set; }
        public virtual MelanomaRisk MelanomaRisk1 { get; set; }
        public virtual SendInfo SendInfo { get; set; }
        public virtual VitaminD VitaminD1 { get; set; }
        public virtual ApplicationName ApplicationName { get; set; }
    }
}


text:
title: настройка nginx basic HTTP Authentication
tags:
  - nginx
  - security
categories:
  - IT
  - sysadm
date: 2014-08-28 17:27:31
---
Добавляем базовую аутентификацию в nginx
<!-- more -->
В конфиг nginx для нужного сайта добавляем строки:
> auth_basic "Unauthorized";
> auth_basic_user_file /var/www/gra_htpasswd;

создаем файл для аутентификации:
    # sudo nano /var/www/gra_htpasswd
> grafa:saEZ6MlWYV9nQ #пользователь:сольпароль

Создать хеш для файла можно такой командой:
    # python -c 'import crypt; print crypt.crypt("123", "sal")'

Меняем владельца файла на пользователя от которого запущен nginx:
    # sudo chown www-data /var/www/gra_htpasswd
И права:
    # sudo chmod 600 /var/www/gra_htpasswd
Проверяем конфигурацию:
    # sudo service nginx configtest
Перезапускаем nginx:
    # sudo service nginx reload


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Null Value Handling</title>

  <link rel="stylesheet" type="text/css" href="../jquery.jqplot.css" />
  <link rel="stylesheet" type="text/css" href="examples.css" />

<?php include "nav.inc"; ?>


text:
namespace v8 {
namespace internal {
namespace wasm {

// Support for serializing WebAssembly {NativeModule} objects. This class takes
// a snapshot of the module state at instantiation, and other code that modifies
// the module after that won't affect the serialized result.
class WasmSerializer {
 public:
  WasmSerializer(Isolate* isolate, NativeModule* native_module);

  // Measure the required buffer size needed for serialization.
  size_t GetSerializedNativeModuleSize() const;

  // Serialize the {NativeModule} into the provided {buffer}. Returns true on
  // success and false if the given buffer it too small for serialization.
  bool SerializeNativeModule(Vector<byte> buffer) const;

 private:
  Isolate* isolate_;
  NativeModule* native_module_;
  std::vector<WasmCode*> code_table_;
};

// Support for deserializing WebAssembly {NativeModule} objects.
// Checks the version header of the data against the current version.
bool IsSupportedVersion(Isolate* isolate, Vector<const byte> data);

// Deserializes the given data to create a compiled Wasm module.
MaybeHandle<WasmModuleObject> DeserializeNativeModule(
    Isolate* isolate, Vector<const byte> data, Vector<const byte> wire_bytes);

}  // namespace wasm
}  // namespace internal
}  // namespace v8

#endif  // V8_WASM_WASM_SERIALIZATION_H_


text:
import {
  Cartesian3,
  ImplicitSubtree,
  ImplicitTileCoordinates,
  ImplicitTileset,
  ImplicitMetadataView,
  MetadataClass,
  MetadataSchema,
  Resource,
} from "../../index.js";
import ImplicitTilingTester from "../../../../Specs/ImplicitTilingTester.js";

describe("Scene/ImplicitMetadataView", function () {
  const highlightColors = [
    [255, 0, 0],
    [255, 255, 0],
    [255, 0, 255],
    [255, 255, 255],
  ];

  const buildingCounts = [100, 350, 200, 500];

  const tileTableDescription = {
    name: "Tiles",
    class: "tile",
    properties: {
      highlightColor: highlightColors,
      buildingCount: buildingCounts,
    },
  };

  const buildingHeights = [20, 30, 10];
  const buildingTypes = ["Residential", "Commercial", "Other"];

  const buildingTableDescription = {
    name: "Buildings",
    class: "building",
    properties: {
      height: buildingHeights,
      buildingType: buildingTypes,
    },
  };

  const treeHeights = [3, 2, 4];
  const treeSpecies = ["Oak", "Pine", "Maple"];

  const treeTableDescription = {
    name: "Trees",
    class: "tree",
    properties: {
      height: treeHeights,
      species: treeSpecies,
    },
  };

  const schema = {
    classes: {
      tile: {
        properties: {
          highlightColor: {
            type: "VEC3",
            componentType: "UINT8",
            semantic: "_HIGHLIGHT_COLOR",
          },
          buildingCount: {
            type: "SCALAR",
            componentType: "UINT16",
          },
        },
      },
      building: {
        properties: {
          height: {
            type: "SCALAR",
            componentType: "UINT16",
            semantic: "_HEIGHT",
          },
          buildingType: {
            type: "STRING",
            semantic: "_BUILDING_TYPE",
          },
        },
      },
      tree: {
        properties: {
          height: {
            type: "SCALAR",
            componentType: "UINT16",
            semantic: "_HEIGHT",
          },
          species: {
            type: "STRING",
            semantic: "_TREE_SPECIES",
          },
        },
      },
    },
  };

  let tileClass;
  let buildingClass;
  let treeClass;

  const propertyTablesDescription = {
    schema: schema,
    propertyTables: [
      tileTableDescription,
      buildingTableDescription,
      treeTableDescription,
    ],
  };

  const subtreeDescription = {
    tileAvailability: {
      descriptor: "11011",
      lengthBits: 5,
      isInternal: true,
      includeAvailableCount: true,
    },
    contentAvailability: [
      {
        descriptor: "01011",
        lengthBits: 5,
        isInternal: true,
        includeAvailableCount: true,
      },
      {
        descriptor: "11001",
        lengthBits: 5,
        isInternal: true,
        includeAvailableCount: true,
      },
    ],
    childSubtreeAvailability: {
      descriptor: 0,
      lengthBits: 16,
      isInternal: true,
    },
    metadata: {
      isInternal: true,
      propertyTables: propertyTablesDescription,
    },
  };

  let tilesetResource;
  let subtreeResource;

  let mockTilesetWithMetadata;
  let metadataSchema;

  const implicitQuadtreeJson = {
    geometricError: 500,
    refine: "ADD",
    boundingVolume: {
      region: [0, 0, Math.PI / 24, Math.PI / 24, 0, 1000.0],
    },
    content: {
      uri: "https://example.com/{level}/{x}/{y}.b3dm",
    },
    implicitTiling: {
      subdivisionScheme: "QUADTREE",
      subtreeLevels: 2,
      availableLevels: 2,
      subtrees: {
        uri: "https://example.com/{level}/{x}/{y}.subtree",
      },
    },
  };

  let metadataQuadtree;
  let rootCoordinates;

  beforeAll(function () {
    tilesetResource = new Resource({
      url: "https://example.com/tileset.json",
    });

    subtreeResource = new Resource({
      url: "https://example.com/test.subtree",
    });

    tileClass = new MetadataClass({
      id: "tile",
      class: schema.classes.tile,
    });

    buildingClass = new MetadataClass({
      id: "building",
      class: schema.classes.building,
    });

    treeClass = new MetadataClass({
      id: "tree",
      class: schema.classes.tree,
    });

    mockTilesetWithMetadata = {
      metadata: {
        schema: new MetadataSchema(schema),
      },
    };

    metadataSchema = mockTilesetWithMetadata.metadata.schema;

    metadataQuadtree = new ImplicitTileset(
      tilesetResource,
      implicitQuadtreeJson,
      metadataSchema
    );

    rootCoordinates = new ImplicitTileCoordinates({
      subdivisionScheme: metadataQuadtree.subdivisionScheme,
      subtreeLevels: metadataQuadtree.subtreeLevels,
      x: 0,
      y: 0,
      level: 0,
    });
  });

  const emptyJson = {};

  let subtree;

  let tileView;
  let secondTileView;

  let buildingView;
  let secondBuildingView;

  let treeView;
  let secondTreeView;

  beforeEach(function () {
    const results = ImplicitTilingTester.generateSubtreeBuffers(
      subtreeDescription
    );

    subtree = new ImplicitSubtree(
      subtreeResource,
      undefined,
      results.subtreeBuffer,
      metadataQuadtree,
      rootCoordinates
    );

    return subtree.readyPromise.then(function () {
      tileView = new ImplicitMetadataView({
        metadataTable: subtree.tileMetadataTable,
        class: tileClass,
        entityId: 0,
        propertyTableJson: emptyJson,
      });

      secondTileView = new ImplicitMetadataView({
        metadataTable: subtree.tileMetadataTable,
        class: tileClass,
        entityId: 1,
        propertyTableJson: emptyJson,
      });

      buildingView = new ImplicitMetadataView({
        metadataTable: subtree.contentMetadataTables[0],
        class: buildingClass,
        entityId: 0,
        contentIndex: 0,
        propertyTableJson: emptyJson,
      });

      secondBuildingView = new ImplicitMetadataView({
        metadataTable: subtree.contentMetadataTables[0],
        class: buildingClass,
        entityId: 1,
        contentIndex: 0,
        propertyTableJson: emptyJson,
      });

      treeView = new ImplicitMetadataView({
        metadataTable: subtree.contentMetadataTables[1],
        class: treeClass,
        entityId: 0,
        contentIndex: 1,
        propertyTableJson: emptyJson,
      });

      secondTreeView = new ImplicitMetadataView({
        metadataTable: subtree.contentMetadataTables[1],
        class: treeClass,
        entityId: 1,
        contentIndex: 1,
        propertyTableJson: emptyJson,
      });
    });
  });

  it("throws without metadataTable", function () {
    expect(function () {
      tileView = new ImplicitMetadataView({
        metadataTable: undefined,
        class: tileClass,
        entityId: 0,
        propertyTableJson: emptyJson,
      });
    }).toThrowDeveloperError();
  });

  it("throws without class", function () {
    expect(function () {
      tileView = new ImplicitMetadataView({
        metadataTable: subtree.tileMetadataTable,
        class: undefined,
        entityId: 0,
        propertyTableJson: emptyJson,
      });
    }).toThrowDeveloperError();
  });

  it("throws without entityId", function () {
    expect(function () {
      tileView = new ImplicitMetadataView({
        metadataTable: subtree.tileMetadataTable,
        class: tileClass,
        entityId: undefined,
        propertyTableJson: emptyJson,
      });
    }).toThrowDeveloperError();
  });

  it("throws without propertyTableJson", function () {
    expect(function () {
      tileView = new ImplicitMetadataView({
        metadataTable: subtree.tileMetadataTable,
        class: tileClass,
        entityId: 0,
        propertyTableJson: undefined,
      });
    }).toThrowDeveloperError();
  });

  it("creates tile metadata table view", function () {
    tileView = new ImplicitMetadataView({
      metadataTable: subtree.tileMetadataTable,
      class: tileClass,
      entityId: 0,
      propertyTableJson: emptyJson,
    });

    expect(tileView.class).toBe(tileClass);
    expect(tileView.extras).toBe(undefined);
    expect(tileView.extensions).toBe(undefined);
  });

  it("creates content metadata table views", function () {
    buildingView = new ImplicitMetadataView({
      metadataTable: subtree.contentMetadataTables[0],
      class: buildingClass,
      entityId: 0,
      propertyTableJson: emptyJson,
    });

    expect(buildingView.class).toBe(buildingClass);
    expect(buildingView.extras).toBe(undefined);
    expect(buildingView.extensions).toBe(undefined);

    treeView = new ImplicitMetadataView({
      metadataTable: subtree.contentMetadataTables[1],
      class: treeClass,
      entityId: 0,
      propertyTableJson: emptyJson,
    });

    expect(treeView.class).toBe(treeClass);
    expect(treeView.extras).toBe(undefined);
    expect(treeView.extensions).toBe(undefined);
  });

  it("hasProperty returns true if the metadata table has this property", function () {
    expect(tileView.hasProperty("highlightColor")).toBe(true);
    expect(buildingView.hasProperty("height")).toBe(true);
    expect(treeView.hasProperty("species")).toBe(true);
  });

  it("hasProperty returns false if the metadata table does not have this property", function () {
    expect(tileView.hasProperty("height")).toBe(false);
    expect(buildingView.hasProperty("buildingCount")).toBe(false);
    expect(treeView.hasProperty("buildingType")).toBe(false);
  });

  it("hasPropertyBySemantic returns true if the metadata table has a property with the given semantic", function () {
    expect(tileView.hasPropertyBySemantic("_HIGHLIGHT_COLOR")).toBe(true);
    expect(buildingView.hasPropertyBySemantic("_HEIGHT")).toBe(true);
    expect(treeView.hasPropertyBySemantic("_TREE_SPECIES")).toBe(true);
  });

  it("hasPropertyBySemantic returns false if the metadata table does not have a property with the given semantic", function () {
    expect(tileView.hasPropertyBySemantic("_AREA")).toBe(false);
    expect(buildingView.hasPropertyBySemantic("_HIGHLIGHT_COLOR")).toBe(false);
    expect(treeView.hasPropertyBySemantic("_BUILDING_TYPE")).toBe(false);
  });

  it("getPropertyIds returns array of property IDs for the tile metadata table", function () {
    const tilePropertyIds = tileView.getPropertyIds([]);
    tilePropertyIds.sort();
    expect(tilePropertyIds).toEqual(["buildingCount", "highlightColor"]);
  });

  it("getPropertyIds returns different property IDs for different content metadata tables", function () {
    const buildingPropertyIds = buildingView.getPropertyIds([]);
    buildingPropertyIds.sort();
    expect(buildingPropertyIds).toEqual(["buildingType", "height"]);

    const treePropertyIds = treeView.getPropertyIds([]);
    treePropertyIds.sort();
    expect(treePropertyIds).toEqual(["height", "species"]);
  });

  it("getProperty returns undefined if a property does not exist for the metadata table", function () {
    expect(tileView.getProperty("height")).not.toBeDefined();
    expect(buildingView.getProperty("species")).not.toBeDefined();
    expect(treeView.getProperty("buildingType")).not.toBeDefined();
  });

  it("getProperty returns the property value for the metadata table", function () {
    expect(tileView.getProperty("highlightColor")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(tileView.getProperty("buildingCount")).toBe(100);

    expect(buildingView.getProperty("height")).toEqual(20);
    expect(buildingView.getProperty("buildingType")).toBe("Residential");

    expect(treeView.getProperty("height")).toEqual(3);
    expect(treeView.getProperty("species")).toBe("Oak");
  });

  it("getProperty returns the correct value for metadata table views that point to the same table", function () {
    expect(tileView.getProperty("highlightColor")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(secondTileView.getProperty("highlightColor")).toEqual(
      new Cartesian3(255, 255, 0)
    );

    expect(buildingView.getProperty("buildingType")).toEqual("Residential");
    expect(secondBuildingView.getProperty("buildingType")).toBe("Commercial");

    expect(treeView.getProperty("species")).toEqual("Oak");
    expect(secondTreeView.getProperty("species")).toBe("Pine");
  });

  it("getProperty returns the correct value for different metadata table views with same property", function () {
    expect(buildingView.getProperty("height")).toEqual(20);
    expect(treeView.getProperty("height")).toEqual(3);
  });

  it("setProperty does not create property if it doesn't exist", function () {
    expect(tileView.setProperty("height", 10)).toBe(false);
    expect(buildingView.setProperty("buildingCount", 10)).toBe(false);
    expect(treeView.setProperty("buildingType", "Other")).toBe(false);
  });

  it("setProperty sets property value", function () {
    expect(tileView.getProperty("buildingCount")).toBe(100);
    expect(tileView.setProperty("buildingCount", 400)).toBe(true);
    expect(tileView.getProperty("buildingCount")).toBe(400);

    expect(buildingView.getProperty("buildingType")).toBe("Residential");
    expect(buildingView.setProperty("buildingType", "Commercial")).toBe(true);
    expect(buildingView.getProperty("buildingType")).toBe("Commercial");

    expect(treeView.getProperty("species")).toBe("Oak");
    expect(treeView.setProperty("species", "Chestnut")).toBe(true);
    expect(treeView.getProperty("species")).toBe("Chestnut");
  });

  it("setProperty sets property value for different metadata table views with same property", function () {
    expect(buildingView.setProperty("height", 100)).toBe(true);
    expect(buildingView.getProperty("height")).toBe(100);
    expect(treeView.getProperty("height")).toBe(3);

    expect(treeView.setProperty("height", 25)).toBe(true);
    expect(treeView.getProperty("height")).toBe(25);
    expect(buildingView.getProperty("height")).toBe(100);
  });

  it("setProperty sets the correct values for metadata table views that point to the same table", function () {
    expect(tileView.getProperty("buildingCount")).toBe(100);
    expect(tileView.setProperty("buildingCount", 400)).toBe(true);
    expect(tileView.getProperty("buildingCount")).toBe(400);
    expect(secondTileView.getProperty("buildingCount")).toBe(350);

    expect(buildingView.getProperty("buildingType")).toBe("Residential");
    expect(buildingView.setProperty("buildingType", "Other")).toBe(true);
    expect(buildingView.getProperty("buildingType")).toBe("Other");
    expect(secondBuildingView.getProperty("buildingType")).toBe("Commercial");

    expect(treeView.getProperty("species")).toBe("Oak");
    expect(treeView.setProperty("species", "Chestnut")).toBe(true);
    expect(treeView.getProperty("species")).toBe("Chestnut");
    expect(secondTreeView.getProperty("species")).toBe("Pine");
  });

  it("getPropertyBySemantic returns undefined when there's no property with the given semantic", function () {
    expect(tileView.getPropertyBySemantic("_AREA")).not.toBeDefined();
    expect(
      buildingView.getPropertyBySemantic("_HIGHLIGHT_COLOR")
    ).not.toBeDefined();
    expect(treeView.getPropertyBySemantic("_BUILDING_TYPE")).not.toBeDefined();
  });

  it("getPropertyBySemantic returns the property value", function () {
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Residential"
    );
    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak");
  });

  it("getPropertyBySemantic returns correct values for different metadata table views with same semantic", function () {
    expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(20);
    expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(3);
  });

  it("getPropertyBySemantic returns correct values for metadata table views that point to the same table", function () {
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(secondTileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 255, 0)
    );

    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Residential"
    );
    expect(secondBuildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Commercial"
    );

    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak");
    expect(secondTreeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual(
      "Pine"
    );
  });

  it("setPropertyBySemantic sets property value", function () {
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(
      tileView.setPropertyBySemantic(
        "_HIGHLIGHT_COLOR",
        new Cartesian3(0, 0, 0)
      )
    ).toBe(true);
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(0, 0, 0)
    );

    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Residential"
    );
    expect(buildingView.setPropertyBySemantic("_BUILDING_TYPE", "Other")).toBe(
      true
    );
    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Other"
    );

    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak");
    expect(treeView.setPropertyBySemantic("_TREE_SPECIES", "Chestnut")).toBe(
      true
    );
    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Chestnut");
  });

  it("setPropertyBySemantic sets the correct value for different metadata table views with the same semantic", function () {
    expect(buildingView.setPropertyBySemantic("_HEIGHT", 100)).toBe(true);
    expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(100);
    expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(3);

    expect(treeView.setPropertyBySemantic("_HEIGHT", 55)).toBe(true);
    expect(treeView.getPropertyBySemantic("_HEIGHT")).toEqual(55);
    expect(buildingView.getPropertyBySemantic("_HEIGHT")).toEqual(100);
  });

  it("setPropertyBySemantic sets the correct value for metadata table views that point to the same table", function () {
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 0, 0)
    );
    expect(
      tileView.setPropertyBySemantic(
        "_HIGHLIGHT_COLOR",
        new Cartesian3(0, 0, 0)
      )
    ).toBe(true);
    expect(tileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(0, 0, 0)
    );
    expect(secondTileView.getPropertyBySemantic("_HIGHLIGHT_COLOR")).toEqual(
      new Cartesian3(255, 255, 0)
    );

    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Residential"
    );
    expect(buildingView.setPropertyBySemantic("_BUILDING_TYPE", "Other")).toBe(
      true
    );
    expect(buildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Other"
    );
    expect(secondBuildingView.getPropertyBySemantic("_BUILDING_TYPE")).toEqual(
      "Commercial"
    );

    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Oak");
    expect(treeView.setPropertyBySemantic("_TREE_SPECIES", "Chestnut")).toBe(
      true
    );
    expect(treeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual("Chestnut");
    expect(secondTreeView.getPropertyBySemantic("_TREE_SPECIES")).toEqual(
      "Pine"
    );
  });

  it("setPropertyBySemantic returns false if the semantic does not exist", function () {
    expect(tileView.setPropertyBySemantic("_AREA", 100)).toBe(false);
    expect(
      buildingView.setPropertyBySemantic(
        "_HIGHLIGHT_COLOR",
        new Cartesian3(255, 0, 0)
      )
    ).toBe(false);
    expect(
      treeView.setPropertyBySemantic(
        "_HIGHLIGHT_COLOR",
        new Cartesian3(255, 0, 0)
      )
    ).toBe(false);
  });
});


text:
<?php

namespace Seahinet\Admin\ViewModel\Customer\Grid\Attribute;

use Seahinet\Admin\ViewModel\Grid;
use Seahinet\Customer\Model\Customer;
use Seahinet\Lib\Model\Collection\Eav\Attribute\Set as Collection;

class Set extends Grid
{

    protected $action = [
        'getEditAction' => 'Admin\\Customer\\Attribute\\Set::edit',
        'getDeleteAction' => 'Admin\\Customer\\Attribute\\Set::delete'
    ];
    protected $translateDomain = 'eav';

    public function getEditAction($item)
    {
        return 'getAdminUrl(':ADMIN/customer_attribute_set/edit/?id=') . $item['id'] . '" title="' . $this->translate('Edit') .
                '">' .
                $this->translate('Edit') . '';
    }

    public function getDeleteAction($item)
    {
        return 'getAdminUrl(':ADMIN/customer_attribute_set/delete/') . '" data-method="delete" data-params="id=' . $item['id'] .
                '&csrf=' . $this->getCsrfKey() . '" title="' . $this->translate('Delete') .
                '">' .
                $this->translate('Delete') . '';
    }

    protected function prepareColumns()
    {
        return [
            'name' => [
                'label' => 'Name'
            ]
        ];
    }

    protected function prepareCollection($collection = null)
    {
        $collection = new Collection;
        $collection->join('eav_entity_type', 'eav_entity_type.id=eav_attribute_set.type_id', [], 'left')
                ->where(['eav_entity_type.code' => Customer::ENTITY_TYPE]);
        if (!$this->getQuery('desc')) {
            $this->query['desc'] = 'eav_attribute_set.created_at';
        }
        return parent::prepareCollection($collection);
    }

}


text:
package net.sf.mmm.util.metakey.api;

/**
 * This interface is a collection of constants defining keys for metadata-properties of a movie (video content). <br>
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 */
public interface MetakeyMovie extends MetakeyAudioVideo {

  /**
   * The company "responsible for the movie".
   */
  String COMPANY = "company";

  /**
   * The country where the movie was produced.
   */
  String COUNTRY = "country";

  /**
   * The director of the movie.
   */
  String DIRECTOR = "director";

  /**
   * The name of the actors playing the movie.
   */
  String ACTOR = "actor";

}


text:
import urllib.parse

def assert_no_response_errors(response):
    # TODO: improve this assertion
    assert response.response.status_code == 200

def assert_redirect(response, path, query, redirect_status_code=302):
    assert response.response.status_code == redirect_status_code
    parsed_redirect = urllib.parse.urlparse(response.response.location)
    assert parsed_redirect.path == path
    parsed_query_string = urllib.parse.parse_qs(parsed_redirect.query)
    assert parsed_query_string == query


text:
const commands = {
	go(data) {
		if (typeof data.path !== 'string' || data.path.trim().length === 0) {
			return console.error('`path` not defined');
		}
		let params = FlowRouter.current().queryParams;
		if (data.layout) {
			params.layout = data.layout;
		}

		FlowRouter.go(data.path, null, params);
	},

	'set-user-status'(data) {
		AccountBox.setStatus(data.status);
	},

	'call-custom-oauth-login'(data, event) {
		const customOAuthCallback = (response) => {
			event.source.postMessage({
				event: 'custom-oauth-callback',
				response: response
			}, event.origin);
		};

		if (typeof data.service === 'string') {
			const customOauth = ServiceConfiguration.configurations.findOne({service: data.service});

			if (customOauth) {
				const customLoginWith = Meteor['loginWith' + _.capitalize(customOauth.service, true)];
				const customRedirectUri = window.OAuth._redirectUri(customOauth.service, customOauth);
				customLoginWith.call(Meteor, {'redirectUrl': customRedirectUri}, customOAuthCallback);
			}
		}
	},

	'login-with-token'(data) {
		if (typeof data.token === 'string') {
			Meteor.loginWithToken(data.token, function() {
				console.log('Iframe command [login-with-token]: result', arguments);
			});
		}
	},

	'logout'() {
		const user = Meteor.user();
		Meteor.logout(() => {
			RocketChat.callbacks.run('afterLogoutCleanUp', user);
			Meteor.call('logoutCleanUp', user);
			return FlowRouter.go('home');
		});
	}
};

window.addEventListener('message', (e) => {
	if (RocketChat.settings.get('Iframe_Integration_receive_enable') !== true) {
		return;
	}

	if (typeof e.data !== 'object' || typeof e.data.externalCommand !== 'string') {
		return;
	}

	let origins = RocketChat.settings.get('Iframe_Integration_receive_origin');

	if (origins !== '*' && origins.split(',').indexOf(e.origin) === -1) {
		return console.error('Origin not allowed', e.origin);
	}

	const command = commands[e.data.externalCommand];
	if (command) {
		command(e.data, e);
	}
});


text:
package com.ctrip.framework.apollo.portal.component;

import com.google.common.collect.Lists;

import com.ctrip.framework.apollo.core.MetaDomainConsts;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

@Component
public class AdminServiceAddressLocator {

  private static final int DEFAULT_TIMEOUT_MS = 1000;
  private static final long NORMAL_REFRESH_INTERVAL = 5 * 60 * 1000;
  private static final long OFFLINE_REFRESH_INTERVAL = 10 * 1000;
  private static final int RETRY_TIMES = 3;
  private static final String ADMIN_SERVICE_URL_PATH = "/services/admin";
  private static final Logger logger = LoggerFactory.getLogger(AdminServiceAddressLocator.class);

  private ScheduledExecutorService refreshServiceAddressService;
  private RestTemplate restTemplate;
  private List<Env> allEnvs;
  private Map<Env, List<ServiceDTO>> cache = new ConcurrentHashMap<>();

  @Autowired
  private HttpMessageConverters httpMessageConverters;
  @Autowired
  private PortalSettings portalSettings;

  @PostConstruct
  public void init() {
    allEnvs = portalSettings.getAllEnvs();

    //init restTemplate
    restTemplate = new RestTemplate(httpMessageConverters.getConverters());
    if (restTemplate.getRequestFactory() instanceof SimpleClientHttpRequestFactory) {
      SimpleClientHttpRequestFactory rf =
          (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
      rf.setReadTimeout(DEFAULT_TIMEOUT_MS);
      rf.setConnectTimeout(DEFAULT_TIMEOUT_MS);
    } else if (restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
      HttpComponentsClientHttpRequestFactory rf =
          (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
      rf.setReadTimeout(DEFAULT_TIMEOUT_MS);
      rf.setConnectTimeout(DEFAULT_TIMEOUT_MS);
    }

    refreshServiceAddressService =
        Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("ServiceLocator", false));

    refreshServiceAddressService.schedule(new RefreshAdminServerAddressTask(), 1, TimeUnit.MILLISECONDS);
  }

  public List<ServiceDTO> getServiceList(Env env) {
    List<ServiceDTO> services = cache.get(env);
    if (CollectionUtils.isEmpty(services)) {
      return Collections.emptyList();
    }
    List<ServiceDTO> randomConfigServices = Lists.newArrayList(services);
    Collections.shuffle(randomConfigServices);
    return randomConfigServices;
  }

  //maintain admin server address
  private class RefreshAdminServerAddressTask implements Runnable {

    @Override
    public void run() {
      boolean refreshSuccess = true;
      //refresh fail if get any env address fail
      for (Env env : allEnvs) {
        boolean currentEnvRefreshResult = refreshServerAddressCache(env);
        refreshSuccess = refreshSuccess && currentEnvRefreshResult;
      }

      if (refreshSuccess) {
        refreshServiceAddressService
            .schedule(new RefreshAdminServerAddressTask(), NORMAL_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
      } else {
        refreshServiceAddressService
            .schedule(new RefreshAdminServerAddressTask(), OFFLINE_REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
      }
    }
  }

  private boolean refreshServerAddressCache(Env env) {

    for (int i = 0; i < RETRY_TIMES; i++) {

      try {
        ServiceDTO[] services = getAdminServerAddress(env);
        if (services == null || services.length == 0) {
          continue;
        }
        cache.put(env, Arrays.asList(services));
        return true;
      } catch (Throwable e) {
        logger.error(String.format("Get admin server address from meta server failed. env: %s, meta server address:%s",
                                   env, MetaDomainConsts.getDomain(env)), e);
        Tracer
            .logError(String.format("Get admin server address from meta server failed. env: %s, meta server address:%s",
                                    env, MetaDomainConsts.getDomain(env)), e);
      }
    }
    return false;
  }

  private ServiceDTO[] getAdminServerAddress(Env env) {
    String domainName = MetaDomainConsts.getDomain(env);
    String url = domainName + ADMIN_SERVICE_URL_PATH;
    return restTemplate.getForObject(url, ServiceDTO[].class);
  }

}


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER2(UnaryOp, CPU, "Tan", functor::tan, float, double);

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Tan", functor::tan, float, double);
#endif

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Tan", functor::tan, float, double);
#endif  // TENSORFLOW_USE_SYCL
}  // namespace tensorflow


text:
package client

import (
	"github.com/dpb587/ssoca/client"
	"github.com/dpb587/ssoca/client/service"
	"github.com/dpb587/ssoca/httpclient"
	"github.com/sirupsen/logrus"

	svc "github.com/dpb587/ssoca/service/openvpn"
	svchttpclient "github.com/dpb587/ssoca/service/openvpn/httpclient"

	boshsys "github.com/cloudfoundry/bosh-utils/system"
)

type Service struct {
	svc.ServiceType

	name             string
	runtime          client.Runtime
	logger           logrus.FieldLogger
	fs               boshsys.FileSystem
	cmdRunner        boshsys.CmdRunner
	executableFinder client.ExecutableFinder
}

var _ service.Service = Service{}

func NewService(name string, runtime client.Runtime, logger logrus.FieldLogger, fs boshsys.FileSystem, cmdRunner boshsys.CmdRunner, executableFinder client.ExecutableFinder) *Service {
	return &Service{
		name:             name,
		runtime:          runtime,
		logger:           logger,
		fs:               fs,
		cmdRunner:        cmdRunner,
		executableFinder: executableFinder,
	}
}

func (s Service) Name() string {
	return s.name
}

func (s Service) GetClient(skipAuthRetry bool) (svchttpclient.Client, error) {
	var client httpclient.Client
	var err error

	if skipAuthRetry {
		client, err = s.runtime.GetClient()
	} else {
		client, err = s.runtime.GetAuthInterceptClient()
	}

	if err != nil {
		return nil, err
	}

	return svchttpclient.New(client, s.name)
}


text:
import Todo from '../../services/todos';

export const CREATE_NEW_TODO__REQUEST = 'CREATE_NEW_TODO__REQUEST';
export const CREATE_NEW_TODO__SUCCESS = 'CREATE_NEW_TODO__SUCCESS';
export const CREATE_NEW_TODO__FAILURE = 'CREATE_NEW_TODO__FAILURE';
export const GET_TODOS__REQUEST = 'GET_TODOS__REQUEST';
export const GET_TODOS__SUCCESS = 'GET_TODOS__SUCCESS';
export const GET_TODOS__FAILURE = 'GET_TODOS__FAILURE';
export const UPDATE_TODO__REQUEST = 'UPDATE_TODO__REQUEST';
export const UPDATE_TODO__SUCCESS = 'UPDATE_TODO__SUCCESS';
export const UPDATE_TODO__FAILURE = 'UPDATE_TODO__FAILURE';
export const GET_TODO__REQUEST = 'GET_TODO__REQUEST';
export const GET_TODO__SUCCESS = 'GET_TODO__SUCCESS';
export const GET_TODO__FAILURE = 'GET_TODO__FAILURE';

export function createNewTodo(name) {
  return async dispatch => {
    dispatch(createNewTodoRequest());
    try {
      const response = await Todo.create(name);

      if (response.status === 201) {
        dispatch(createNewTodoSuccess());
        dispatch(getTodos());
      } else {
        dispatch(createNewTodoFailure());
      }
    } catch (err) {
      dispatch(createNewTodoFailure());
    }
  };
}

function createNewTodoRequest() {
  return { type: CREATE_NEW_TODO__REQUEST };
}

function createNewTodoSuccess() {
  return { type: CREATE_NEW_TODO__SUCCESS };
}

function createNewTodoFailure() {
  return { type: CREATE_NEW_TODO__FAILURE };
}

export function getTodos() {
  return async dispatch => {
    dispatch(getTodosRequest());
    try {
      const data = await Todo.getTodos();
      dispatch(getTodosSuccess(data));
    } catch (err) {
      dispatch(getTodosFailure());
    }
  };
}

function getTodosRequest() {
  return { type: GET_TODOS__REQUEST };
}

function getTodosSuccess(todos) {
  return { type: GET_TODOS__SUCCESS, todos };
}

function getTodosFailure() {
  return { type: GET_TODOS__FAILURE };
}

export function updateTodo(id) {
  return async dispatch => {
    dispatch(updateTodoRequest());
    try {
      const response = await Todo.updateTodo(id);

      if (response.status === 200) {
        dispatch(updateTodoSuccess(response));
        dispatch(getTodos());
      } else {
        dispatch(updateTodoFailure());
      }
    } catch (err) {
      dispatch(updateTodoFailure());
    }
  };
}

function updateTodoRequest() {
  return { type: UPDATE_TODO__REQUEST };
}

function updateTodoSuccess(todo) {
  return { type: UPDATE_TODO__SUCCESS, todo };
}

function updateTodoFailure() {
  return { type: UPDATE_TODO__FAILURE };
}

export function getTodo(id) {
  return async dispatch => {
    dispatch(getTodoRequest());
    try {
      const data = await Todo.getTodo(id);
      dispatch(getTodoSuccess(data));
    } catch (err) {
      dispatch(getTodoFailure());
    }
  };
}

function getTodoRequest() {
  return { type: GET_TODO__REQUEST };
}

function getTodoSuccess(todo) {
  return { type: GET_TODO__SUCCESS, todo };
}

function getTodoFailure() {
  return { type: GET_TODO__FAILURE };
}


text:
require 'spec_helper'

describe LambdaMoo::ReturnStatement do
  let(:parser) { LambdaMoo::Parser.new }
  let(:runtime) { LambdaMoo::Runtime.new }

  it "should be case-insensitive" do
    program = parser.parse("RETURN;")
    program.execute(runtime)
  end

  it "should halt execution of the current program" do
    expect(runtime).not_to receive(:call_builtin_function)
    program = parser.parse("return 42; test_builtin();")
    program.execute(runtime)
  end
end


text:
import { PhucVuService } from '../phuc-vu.service';
import { Router } from '@angular/router';
import { Ban } from '../../shared/models/Ban';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Message } from 'primeng/components/common/message';
import { BanService } from 'app/phuc-vu/ban/ban.service';
import { SelectItem } from 'primeng/components/common/selectitem';

@Component({
  selector: 'app-ban',
  templateUrl: './ban.component.html',
  styleUrls: ['./ban.component.scss']
})
export class BanComponent implements OnInit, OnDestroy {
  khuVucs: SelectItem[];
  filteredBans: Array<any> = [];
  bans: Array<any> = [];
  trangThai = null;
  trangThais: SelectItem[] = [{ label: 'Tất cả', value: null }];

  connection;
  banObserver;

  selected;

  mons = [];
  msgs: Message[] = [];
  constructor(private service: BanService, private router: Router, private phucVuService: PhucVuService) {
  }

  ngOnInit() {
    const self = this;
    this.getBan();
    this.getKhuVuc();

    this.banObserver = setInterval(() => {
      self.getBan()
    }, 5000);

    this.trangThais.push({ label: 'trống', value: 'trống' });
    this.trangThais.push({ label: 'có khách', value: 'có khách' });
    this.trangThais.push({ label: 'đã đặt', value: 'đã đặt' });
    this.connection = this.phucVuService.listenToNewDish()
      .subscribe(function (message: string) {
        self.msgs = [];
        self.msgs.push({ severity: 'success', summary: 'Có món mới xong!', detail: message });
      })
  }

  getImage(trangThai) {
    switch (trangThai) {
      case 'có khách':
        return 'assets/images/taken.png';
      case 'đã đặt':
        return 'assets/images/booked.png';
      default:
        return 'assets/images/empty.png';
    }
  }

  getKhuVuc() {
    this.service.getKhuVuc().subscribe(
      response => {
        const results = response.json();
        this.khuVucs = [];
        this.khuVucs.push({ label: 'Tất cả', value: null });
        results.forEach(element => {
          this.khuVucs.push({ label: element.ten, value: element._id });
        });
      },
      error => {
        console.log(error);
      });
  }

  getBan() {
    this.service.getBan().subscribe(
      response => {
        // tslint:disable-next-line:prefer-const
        this.bans = response.json();
        this.filter();
        console.log(this.bans);
      },
      error => {
        console.log(error);
      }
    );
  }

  filterTrangThai(e) {
    this.trangThai = e.value;
    this.filter();
  }

  filter() {
    if (this.selected == null) {
      if (this.trangThai !== null) {
        this.filteredBans = this.bans.filter(item => {
          return item.trangThai === this.trangThai;
        });
      } else {
        this.filteredBans = this.bans.slice();
      }
    } else {
      this.filteredBans = this.bans.filter(item => {
        if (this.trangThai !== null) {
          return item.khuVucId._id === this.selected && item.trangThai === this.trangThai;
        }
        return item.khuVucId._id === this.selected;
      });
    }
    this.filteredBans.sort((a, b) => a.ten.localeCompare(b.ten));
  }

  navigate(id) {
    const ban = this.bans.find(item => {
      return item._id === id;
    })
    if (ban.trangThai !== 'đã đặt') {
      this.router.navigate(['/phuc-vu', 'menu', id]);
    } else {
      this.msgs = [];
      this.msgs.push({
        severity: 'error',
        summary: '',
        detail: 'Bàn này đã được đặt trước. Vui lòng check in ở quầy lễ tân để sử dụng!'
      });
    }
  }

  ngOnDestroy() {
    if (this.banObserver) {
      clearInterval(this.banObserver);
    }
  }
}


text:
package org.sablecc.sablecc.grammar.transformation;

import java.util.*;

import org.sablecc.exception.*;
import org.sablecc.sablecc.core.interfaces.*;
import org.sablecc.sablecc.grammar.*;
import org.sablecc.sablecc.grammar.interfaces.*;

public abstract class SAlternativeTransformationListElement {

    public abstract List<SAlternativeTransformationListElement> inline(
            Alternative inlinedAlternative,
            Map<Element, Element> oldToNewElement);

    @Override
    public abstract SAlternativeTransformationListElement clone();

    public static class ReferenceElement
            extends SAlternativeTransformationListElement {

        private IElement reference;

        public ReferenceElement(
                IElement reference) {

            if (reference == null) {
                throw new InternalException("reference shouldn't be null");
            }

            this.reference = reference;
        }

        @Override
        public List<SAlternativeTransformationListElement> inline(
                Alternative inlinedAlternative,
                Map<Element, Element> oldToNewElement) {

            LinkedList<SAlternativeTransformationListElement> inlineResult = new LinkedList<SAlternativeTransformationListElement>();

            if (this.reference instanceof Element.ProductionElement) {
                Element.ProductionElement productionElement = (Element.ProductionElement) this.reference;

                if (productionElement.getReference().equals(
                        inlinedAlternative.getProduction())) {

                    for (SAlternativeTransformationElement element : inlinedAlternative
                            .getTransformation().getElements()) {

                        for (SAlternativeTransformationElement newElement : element
                                .inline(inlinedAlternative, oldToNewElement)) {

                            if (newElement instanceof SAlternativeTransformationElement.ReferenceElement) {
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.ReferenceElement(
                                                ((SAlternativeTransformationElement.ReferenceElement) newElement)
                                                        .getReference()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.NewElement) {
                                SAlternativeTransformationElement.NewElement newNewElemnt = (SAlternativeTransformationElement.NewElement) newElement;
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.NewElement(
                                                newNewElemnt.getAlternative(),
                                                newNewElemnt.getElements()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.ListElement) {
                                inlineResult
                                        .addAll(((SAlternativeTransformationElement.ListElement) newElement)
                                                .getElements());
                            }
                        }

                    }

                }
                else {
                    inlineResult
                            .add(new SAlternativeTransformationListElement.ReferenceElement(
                                    oldToNewElement.get(this.reference)));
                }
            }
            else {
                inlineResult
                        .add(new SAlternativeTransformationListElement.ReferenceElement(
                                oldToNewElement.get(this.reference)));
            }

            return inlineResult;
        }

        @Override
        public SAlternativeTransformationListElement clone() {

            return new ReferenceElement(this.reference);
        }

    }

    public static class NewElement
            extends SAlternativeTransformationListElement {

        private IReferencable alternative;

        private List<SAlternativeTransformationElement> elements = new LinkedList<SAlternativeTransformationElement>();

        public NewElement(
                IReferencable alternative,
                List<SAlternativeTransformationElement> elements) {

            if (alternative == null) {
                throw new InternalException("reference shouldn't be null");
            }

            if (elements == null) {
                throw new InternalException("reference shouldn't be null");
            }

            this.alternative = alternative;
            this.elements = elements;
        }

        @Override
        public List<SAlternativeTransformationListElement> inline(
                Alternative inlinedAlternative,
                Map<Element, Element> oldToNewElement) {

            List<SAlternativeTransformationElement> newElements = new LinkedList<SAlternativeTransformationElement>();

            for (SAlternativeTransformationElement element : this.elements) {
                newElements.addAll(element.inline(inlinedAlternative,
                        oldToNewElement));
            }

            List<SAlternativeTransformationListElement> inlineResult = new LinkedList<SAlternativeTransformationListElement>();

            inlineResult
                    .add(new SAlternativeTransformationListElement.NewElement(
                            this.alternative, newElements));

            return inlineResult;
        }

        public IReferencable getAlternative() {

            return this.alternative;
        }

        @Override
        public SAlternativeTransformationListElement clone() {

            LinkedList<SAlternativeTransformationElement> newElements = new LinkedList<SAlternativeTransformationElement>();

            for (SAlternativeTransformationElement element : this.elements) {
                newElements.add(element.clone());
            }

            return new NewElement(this.alternative, newElements);
        }

    }

    public static class NormalListElement
            extends SAlternativeTransformationListElement {

        private IElement reference;

        public NormalListElement(
                IElement reference) {

            if (reference == null) {
                throw new InternalException("reference shouldn't be null");
            }

            this.reference = reference;
        }

        @Override
        public List<SAlternativeTransformationListElement> inline(
                Alternative inlinedAlternative,
                Map<Element, Element> oldToNewElement) {

            LinkedList<SAlternativeTransformationListElement> inlineResult = new LinkedList<SAlternativeTransformationListElement>();

            if (this.reference instanceof Element.ProductionElement) {
                Element.ProductionElement productionElement = (Element.ProductionElement) this.reference;

                if (productionElement.getReference().equals(
                        inlinedAlternative.getProduction())) {

                    for (SAlternativeTransformationElement element : inlinedAlternative
                            .getTransformation().getElements()) {
                        for (SAlternativeTransformationElement newElement : element
                                .inline(inlinedAlternative, oldToNewElement)) {

                            if (newElement instanceof SAlternativeTransformationElement.ReferenceElement) {
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.ReferenceElement(
                                                ((SAlternativeTransformationElement.ReferenceElement) newElement)
                                                        .getReference()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.NewElement) {
                                SAlternativeTransformationElement.NewElement newNewElemnt = (SAlternativeTransformationElement.NewElement) newElement;
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.NewElement(
                                                newNewElemnt.getAlternative(),
                                                newNewElemnt.getElements()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.ListElement) {
                                inlineResult
                                        .addAll(((SAlternativeTransformationElement.ListElement) newElement)
                                                .getElements());
                            }
                        }
                    }

                }
                else {
                    inlineResult
                            .add(new SAlternativeTransformationListElement.NormalListElement(
                                    oldToNewElement.get(this.reference)));
                }
            }
            else {
                inlineResult
                        .add(new SAlternativeTransformationListElement.NormalListElement(
                                oldToNewElement.get(this.reference)));
            }

            return inlineResult;
        }

        @Override
        public SAlternativeTransformationListElement clone() {

            // TODO Auto-generated method stub
            return null;
        }

    }

    public static class LeftListElement
            extends SAlternativeTransformationListElement {

        private IElement reference;

        public LeftListElement(
                IElement reference) {

            if (reference == null) {
                throw new InternalException("reference shouldn't be null");
            }

            this.reference = reference;
        }

        @Override
        public SAlternativeTransformationListElement clone() {

            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public List<SAlternativeTransformationListElement> inline(
                Alternative inlinedAlternative,
                Map<Element, Element> oldToNewElement) {

            LinkedList<SAlternativeTransformationListElement> inlineResult = new LinkedList<SAlternativeTransformationListElement>();

            if (this.reference instanceof Element.ProductionElement) {
                Element.ProductionElement productionElement = (Element.ProductionElement) this.reference;

                if (productionElement.getReference().equals(
                        inlinedAlternative.getProduction())) {

                    for (SAlternativeTransformationElement element : inlinedAlternative
                            .getTransformation().getElements()) {
                        for (SAlternativeTransformationElement newElement : element
                                .inline(inlinedAlternative, oldToNewElement)) {

                            if (newElement instanceof SAlternativeTransformationElement.ReferenceElement) {
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.ReferenceElement(
                                                ((SAlternativeTransformationElement.ReferenceElement) newElement)
                                                        .getReference()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.NewElement) {
                                SAlternativeTransformationElement.NewElement newNewElemnt = (SAlternativeTransformationElement.NewElement) newElement;
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.NewElement(
                                                newNewElemnt.getAlternative(),
                                                newNewElemnt.getElements()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.ListElement) {
                                inlineResult
                                        .addAll(((SAlternativeTransformationElement.ListElement) newElement)
                                                .getElements());
                            }
                        }
                    }

                }
                else {
                    inlineResult
                            .add(new SAlternativeTransformationListElement.LeftListElement(
                                    oldToNewElement.get(this.reference)));
                }
            }
            else {
                inlineResult
                        .add(new SAlternativeTransformationListElement.LeftListElement(
                                oldToNewElement.get(this.reference)));
            }

            return inlineResult;
        }

    }

    public static class RightListElement
            extends SAlternativeTransformationListElement {

        private IElement reference;

        public RightListElement(
                IElement reference) {

            if (reference == null) {
                throw new InternalException("reference shouldn't be null");
            }

            this.reference = reference;
        }

        @Override
        public SAlternativeTransformationListElement clone() {

            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public List<SAlternativeTransformationListElement> inline(
                Alternative inlinedAlternative,
                Map<Element, Element> oldToNewElement) {

            LinkedList<SAlternativeTransformationListElement> inlineResult = new LinkedList<SAlternativeTransformationListElement>();

            if (this.reference instanceof Element.ProductionElement) {
                Element.ProductionElement productionElement = (Element.ProductionElement) this.reference;

                if (productionElement.getReference().equals(
                        inlinedAlternative.getProduction())) {

                    for (SAlternativeTransformationElement element : inlinedAlternative
                            .getTransformation().getElements()) {
                        for (SAlternativeTransformationElement newElement : element
                                .inline(inlinedAlternative, oldToNewElement)) {

                            if (newElement instanceof SAlternativeTransformationElement.ReferenceElement) {
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.ReferenceElement(
                                                ((SAlternativeTransformationElement.ReferenceElement) newElement)
                                                        .getReference()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.NewElement) {
                                SAlternativeTransformationElement.NewElement newNewElemnt = (SAlternativeTransformationElement.NewElement) newElement;
                                inlineResult
                                        .add(new SAlternativeTransformationListElement.NewElement(
                                                newNewElemnt.getAlternative(),
                                                newNewElemnt.getElements()));
                            }
                            else if (newElement instanceof SAlternativeTransformationElement.ListElement) {
                                inlineResult
                                        .addAll(((SAlternativeTransformationElement.ListElement) newElement)
                                                .getElements());
                            }
                        }
                    }

                }
                else {
                    inlineResult
                            .add(new SAlternativeTransformationListElement.RightListElement(
                                    oldToNewElement.get(this.reference)));
                }
            }
            else {
                inlineResult
                        .add(new SAlternativeTransformationListElement.RightListElement(
                                oldToNewElement.get(this.reference)));
            }

            return inlineResult;
        }

    }

}


text:
Daisy is a solution for running multi-step workflows on GCE.

[![GoDoc](https://godoc.org/github.com/GoogleCloudPlatform/compute-daisy?status.svg)](https://godoc.org/github.com/GoogleCloudPlatform/compute-daisy)

The current Daisy stepset includes support for creating/deleting GCE resources,
waiting for signals from GCE VMs, streaming GCE VM logs, uploading local files
to GCE and GCE VMs, and more.

For example, Daisy is used to create Google Official Guest OS images. The
workflow:
1. Creates a Debian 8 disk and another empty disk.
2. Creates and boots a VM with the two disks.
3. Runs and waits for a script on the VM.
4. Creates an image from the previously empty disk.
5. Automatically cleans up the VM and disks.

Other use-case examples:
* Workflows for importing external physical or virtual disks to GCE.
* GCE environment deployment.
* Ad hoc GCE testing environment deployment and test running.


text:
var sinon = require('sinon');
var should = require('should');
require('./should-sinon');

it('should test if given object is sinon stub', function() {
  var callback = sinon.spy();

  should(null).be.not.a.sinonStub();
  should(void 0).be.not.a.sinonStub();

  callback.should.be.a.sinonStub();
});

it('should get number of calls', function() {
  var callback = sinon.spy();

  callback.should.have.callCount(0);
  callback.should.not.be.called();
  callback.should.not.be.calledOnce();
  callback.should.not.be.calledTwice();
  callback.should.not.be.calledThrice();

  callback();

  callback.should.have.callCount(1);
  callback.should.be.called();
  callback.should.be.calledOnce();
  callback.should.not.be.calledTwice();
  callback.should.not.be.calledThrice();

  callback();

  callback.should.have.callCount(2);
  callback.should.be.called();
  callback.should.not.be.calledOnce();
  callback.should.be.calledTwice();
  callback.should.not.be.calledThrice();

  callback();

  callback.should.have.callCount(3);
  callback.should.be.called();
  callback.should.not.be.calledOnce();
  callback.should.not.be.calledTwice();
  callback.should.be.calledThrice();

  callback();

  callback.should.have.callCount(4);
  callback.should.be.called();
  callback.should.not.be.calledOnce();
  callback.should.not.be.calledTwice();
  callback.should.not.be.calledThrice();
});

it('should check if stub was called with specific this', function () {
  var callback = sinon.spy();

  var obj = {};

  callback.call(obj);

  callback.should.be.calledOn(obj);

  var obj2 = {};

  callback.call(obj);

  callback.should.be.alwaysCalledOn(obj);

  callback.call(obj2);

  callback.should.not.be.alwaysCalledOn(obj);
  callback.should.not.be.alwaysCalledOn(obj2);

  callback.should.be.calledOn(obj2);
});


text:
package fr.inra.maiage.bibliome.util.bionlpst;

public enum Visibility {
	A1(".a1"),
	A2(".a2"),
	PREDICTION(".a2");

	public final String fileSuffix;

	private Visibility(String fileSuffix) {
		this.fileSuffix = fileSuffix;
	}
}


text:
namespace dclass   // open namespace dclass
{

// Forward declarations
class DistributedType;

// format_value steps through packed data and unpacks it as a .dc file parameter value.
//     An DistributedType represents any type with defined structure (Class, Field, method, etc...)
std::string format_value(const DistributedType*, const std::vector<uint8_t> &packed);
std::string format_value(const DistributedType*, const std::string &packed);
void format_value(const DistributedType*, const std::vector<uint8_t> &packed, std::ostream &out);
void format_value(const DistributedType*, const std::string &packed, std::ostream &out);

// format_hex outputs <str> as a hexidecimal constant enclosed in angle-brackets (<>)
std::string format_hex(const std::string &str);
void format_hex(const std::string &str, std::ostream &out);

// format_quoted outputs <str> enclosed in quotes after escaping the string.
//     Any instances of backslash (\) or the quoute character in the string are escaped.
//     Non-printable characters are replaced with an escaped hexidecimal constant.std::string format_quoted(const std::string &str);
std::string format_quoted(char quote_mark, const std::string &str);
void format_quoted(char quote_mark, const std::string &str, std::ostream &out);

} // close namespace dclass


text:
Article 1277
----
La simple indication faite, par le débiteur, d'une personne qui doit payer à sa
place, n'opère point novation.

Il en est de même de la simple indication faite, par le créancier, d'une
personne qui doit recevoir pour lui.


text:
package io.druid.segment.data;

import com.google.common.primitives.Ints;
import io.druid.collections.ResourceHolder;
import io.druid.collections.StupidResourceHolder;
import io.druid.java.util.common.io.smoosh.FileSmoosher;
import io.druid.segment.IndexIO;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.channels.WritableByteChannel;

/**
 * Streams array of integers out in the binary format described by CompressedIntsIndexedSupplier
 */
public class CompressedIntsIndexedWriter extends SingleValueIndexedIntsWriter
{
  private static final byte VERSION = CompressedIntsIndexedSupplier.VERSION;

  public static CompressedIntsIndexedWriter create(
      final IOPeon ioPeon,
      final String filenameBase,
      final CompressedObjectStrategy.CompressionStrategy compression
  )
  {
    return new CompressedIntsIndexedWriter(
        ioPeon,
        filenameBase,
        CompressedIntsIndexedSupplier.MAX_INTS_IN_BUFFER,
        IndexIO.BYTE_ORDER,
        compression
    );
  }

  private final int chunkFactor;
  private final CompressedObjectStrategy.CompressionStrategy compression;
  private final GenericIndexedWriter<ResourceHolder<IntBuffer>> flattener;
  private IntBuffer endBuffer;
  private int numInserted;

  public CompressedIntsIndexedWriter(
      final IOPeon ioPeon,
      final String filenameBase,
      final int chunkFactor,
      final ByteOrder byteOrder,
      final CompressedObjectStrategy.CompressionStrategy compression
  )
  {
    this(chunkFactor, compression, new GenericIndexedWriter<>(
        ioPeon, filenameBase, CompressedIntBufferObjectStrategy.getBufferForOrder(byteOrder, compression, chunkFactor)
    ));
  }

  public CompressedIntsIndexedWriter(
      final int chunkFactor,
      final CompressedObjectStrategy.CompressionStrategy compression,
      GenericIndexedWriter<ResourceHolder<IntBuffer>> flattner
  )
  {
    this.chunkFactor = chunkFactor;
    this.compression = compression;
    this.endBuffer = IntBuffer.allocate(chunkFactor);
    this.numInserted = 0;
    this.flattener = flattner;
  }

  @Override
  public void open() throws IOException
  {
    flattener.open();
  }

  @Override
  protected void addValue(int val) throws IOException
  {
    if (!endBuffer.hasRemaining()) {
      endBuffer.rewind();
      flattener.write(StupidResourceHolder.create(endBuffer));
      endBuffer = IntBuffer.allocate(chunkFactor);
    }
    endBuffer.put(val);
    numInserted++;
  }

  @Override
  public void close() throws IOException
  {
    try {
      if (numInserted > 0) {
        endBuffer.limit(endBuffer.position());
        endBuffer.rewind();
        flattener.write(StupidResourceHolder.create(endBuffer));
      }
      endBuffer = null;
    }
    finally {
      flattener.close();
    }
  }

  @Override
  public long getSerializedSize()
  {
    return 1 +             // version
           Ints.BYTES +    // numInserted
           Ints.BYTES +    // chunkFactor
           1 +             // compression id
           flattener.getSerializedSize();
  }

  @Override
  public void writeToChannel(WritableByteChannel channel, FileSmoosher smoosher) throws IOException
  {
    channel.write(ByteBuffer.wrap(new byte[]{VERSION}));
    channel.write(ByteBuffer.wrap(Ints.toByteArray(numInserted)));
    channel.write(ByteBuffer.wrap(Ints.toByteArray(chunkFactor)));
    channel.write(ByteBuffer.wrap(new byte[]{compression.getId()}));
    flattener.writeToChannel(channel, smoosher);
  }
}