text:
package tests

import (
	"bytes"
	"context"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/influxdata/flux/csv"
	"github.com/influxdata/influxdb/v2"
	"github.com/influxdata/influxdb/v2/authorization"
	influxhttp "github.com/influxdata/influxdb/v2/http"
	"github.com/influxdata/influxdb/v2/kit/platform"
	"github.com/influxdata/influxdb/v2/pkg/httpc"
	"github.com/influxdata/influxdb/v2/tenant"
)

type ClientConfig struct {
	UserID             platform.ID
	OrgID              platform.ID
	BucketID           platform.ID
	DocumentsNamespace string

	// If Session is provided, Token is ignored.
	Token   string
	Session *influxdb.Session
}

// Client provides an API for writing, querying, and interacting with
// resources like authorizations, buckets, and organizations.
type Client struct {
	Client *httpc.Client
	*influxhttp.Service

	*authorization.AuthorizationClientService
	*tenant.BucketClientService
	*tenant.OrgClientService
	*tenant.UserClientService

	ClientConfig
}

// NewClient initialises a new Client which is ready to write points to the HTTP write endpoint.
func NewClient(endpoint string, config ClientConfig) (*Client, error) {
	opts := make([]httpc.ClientOptFn, 0)
	if config.Session != nil {
		config.Token = ""
		opts = append(opts, httpc.WithSessionCookie(config.Session.Key))
	}
	hc, err := influxhttp.NewHTTPClient(endpoint, config.Token, false, opts...)
	if err != nil {
		return nil, err
	}

	svc, err := influxhttp.NewService(hc, endpoint, config.Token)
	if err != nil {
		return nil, err
	}
	return &Client{
		Client:                     hc,
		Service:                    svc,
		AuthorizationClientService: &authorization.AuthorizationClientService{Client: hc},
		BucketClientService:        &tenant.BucketClientService{Client: hc},
		OrgClientService:           &tenant.OrgClientService{Client: hc},
		UserClientService:          &tenant.UserClientService{Client: hc},
		ClientConfig:               config,
	}, nil
}

// Open opens the client
func (c *Client) Open() error { return nil }

// Close closes the client
func (c *Client) Close() error { return nil }

// MustWriteBatch calls WriteBatch, panicking if an error is encountered.
func (c *Client) MustWriteBatch(points string) {
	if err := c.WriteBatch(points); err != nil {
		panic(err)
	}
}

// WriteBatch writes the current batch of points to the HTTP endpoint.
func (c *Client) WriteBatch(points string) error {
	return c.WriteService.WriteTo(
		context.Background(),
		influxdb.BucketFilter{
			ID:             &c.BucketID,
			OrganizationID: &c.OrgID,
		},
		strings.NewReader(points),
	)
}

// Query returns the CSV response from a flux query to the HTTP API.
//
// This also remove all the \r to make it easier to write tests.
func (c *Client) QueryFlux(org, query string) (string, error) {
	var csv string
	csvResp := func(resp *http.Response) error {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		// remove the \r to simplify testing against a body of CSV.
		body = bytes.ReplaceAll(body, []byte("\r"), nil)
		csv = string(body)
		return nil
	}

	qr := QueryRequestBody(query)
	err := c.Client.PostJSON(qr, fluxPath).
		QueryParams([2]string{"org", org}).
		Accept("text/csv").
		RespFn(csvResp).
		StatusFn(httpc.StatusIn(http.StatusOK)).
		Do(context.Background())

	return csv, err
}

const (
	fluxPath = "/api/v2/query"
	// This is the only namespace for documents present after init.
	DefaultDocumentsNamespace = "templates"
)

// QueryRequestBody creates a body for a flux query using common CSV output params.
// Headers are included, but, annotations are not.
func QueryRequestBody(flux string) *influxhttp.QueryRequest {
	header := true
	return &influxhttp.QueryRequest{
		Type:  "flux",
		Query: flux,
		Dialect: influxhttp.QueryDialect{
			Header:         &header,
			Delimiter:      ",",
			CommentPrefix:  "#",
			DateTimeFormat: "RFC3339",
			Annotations:    csv.DefaultEncoderConfig().Annotations,
		},
	}
}

// MustCreateAuth creates an auth  or is a fatal error.
// Used in tests where the content of the bucket does not matter.
//
// This authorization token is an operator token for the default
// organization for the default user.
func (c *Client) MustCreateAuth(t *testing.T) platform.ID {
	t.Helper()

	perms := influxdb.OperPermissions()
	auth := &influxdb.Authorization{
		OrgID:       c.OrgID,
		UserID:      c.UserID,
		Permissions: perms,
	}
	err := c.CreateAuthorization(context.Background(), auth)
	if err != nil {
		t.Fatalf("unable to create auth: %v", err)
	}
	return auth.ID
}

// MustCreateBucket creates a bucket or is a fatal error.
// Used in tests where the content of the bucket does not matter.
func (c *Client) MustCreateBucket(t *testing.T) platform.ID {
	t.Helper()

	bucket := &influxdb.Bucket{OrgID: c.OrgID, Name: "n1"}
	err := c.CreateBucket(context.Background(), bucket)
	if err != nil {
		t.Fatalf("unable to create bucket: %v", err)
	}
	return bucket.ID
}

// MustCreateOrg creates an org or is a fatal error.
// Used in tests where the content of the org does not matter.
func (c *Client) MustCreateOrg(t *testing.T) platform.ID {
	t.Helper()

	org := &influxdb.Organization{Name: "n1"}
	err := c.CreateOrganization(context.Background(), org)
	if err != nil {
		t.Fatalf("unable to create org: %v", err)
	}
	return org.ID
}

// MustCreateLabel creates a label or is a fatal error.
// Used in tests where the content of the label does not matter.
func (c *Client) MustCreateLabel(t *testing.T) platform.ID {
	t.Helper()

	l := &influxdb.Label{OrgID: c.OrgID, Name: "n1"}
	err := c.CreateLabel(context.Background(), l)
	if err != nil {
		t.Fatalf("unable to create label: %v", err)
	}
	return l.ID
}

// MustCreateCheck creates a check or is a fatal error.
// Used in tests where the content of the check does not matter.
func (c *Client) MustCreateCheck(t *testing.T) platform.ID {
	t.Helper()

	chk, err := c.CreateCheck(context.Background(), MockCheck("c", c.OrgID, c.UserID))
	if err != nil {
		t.Fatalf("unable to create check: %v", err)
	}
	return chk.ID
}

// MustCreateTelegraf creates a telegraf config or is a fatal error.
// Used in tests where the content of the telegraf config does not matter.
func (c *Client) MustCreateTelegraf(t *testing.T) platform.ID {
	t.Helper()

	tc := &influxdb.TelegrafConfig{
		OrgID:       c.OrgID,
		Name:        "n1",
		Description: "d1",
		Config:      "[[howdy]]",
	}
	unused := platform.ID(1) /* this id is not used in the API */
	err := c.CreateTelegrafConfig(context.Background(), tc, unused)
	if err != nil {
		t.Fatalf("unable to create telegraf config: %v", err)
	}
	return tc.ID
}

// MustCreateUser creates a user or is a fatal error.
// Used in tests where the content of the user does not matter.
func (c *Client) MustCreateUser(t *testing.T) platform.ID {
	t.Helper()

	u := &influxdb.User{Name: "n1"}
	err := c.CreateUser(context.Background(), u)
	if err != nil {
		t.Fatalf("unable to create user: %v", err)
	}
	return u.ID
}

// MustCreateVariable creates a variable or is a fatal error.
// Used in tests where the content of the variable does not matter.
func (c *Client) MustCreateVariable(t *testing.T) platform.ID {
	t.Helper()

	v := &influxdb.Variable{
		OrganizationID: c.OrgID,
		Name:           "n1",
		Arguments: &influxdb.VariableArguments{
			Type:   "constant",
			Values: influxdb.VariableConstantValues{"v1", "v2"},
		},
	}
	err := c.CreateVariable(context.Background(), v)
	if err != nil {
		t.Fatalf("unable to create variable: %v", err)
	}
	return v.ID
}

// MustCreateNotificationEndpoint creates a notification endpoint or is a fatal error.
// Used in tests where the content of the notification endpoint does not matter.
func (c *Client) MustCreateNotificationEndpoint(t *testing.T) platform.ID {
	t.Helper()

	ne := ValidNotificationEndpoint(c.OrgID)
	err := c.CreateNotificationEndpoint(context.Background(), ne, c.UserID)
	if err != nil {
		t.Fatalf("unable to create notification endpoint: %v", err)
	}
	return ne.GetID()
}

// MustCreateNotificationRule creates a Notification Rule or is a fatal error
// Used in tests where the content of the notification rule does not matter
func (c *Client) MustCreateNotificationRule(t *testing.T) platform.ID {
	t.Helper()
	ctx := context.Background()

	ne := ValidCustomNotificationEndpoint(c.OrgID, time.Now().String())
	err := c.CreateNotificationEndpoint(ctx, ne, c.UserID)
	if err != nil {
		t.Fatalf("unable to create notification endpoint: %v", err)
	}
	endpointID := ne.GetID()
	r := ValidNotificationRule(c.OrgID, endpointID)
	rc := influxdb.NotificationRuleCreate{NotificationRule: r, Status: influxdb.Active}

	err = c.CreateNotificationRule(ctx, rc, c.UserID)
	if err != nil {
		t.Fatalf("unable to create notification rule: %v", err)
	}

	// we don't need this endpoint, so delete it to be compatible with other tests
	_, _, err = c.DeleteNotificationEndpoint(ctx, endpointID)
	if err != nil {
		t.Fatalf("unable to delete notification endpoint: %v", err)
	}

	return r.GetID()
}

// MustCreateDBRPMapping creates a DBRP Mapping or is a fatal error.
// Used in tests where the content of the mapping does not matter.
// The created mapping points to the user's default bucket.
func (c *Client) MustCreateDBRPMapping(t *testing.T) platform.ID {
	t.Helper()
	ctx := context.Background()

	m := &influxdb.DBRPMapping{
		Database:        "db",
		RetentionPolicy: "rp",
		OrganizationID:  c.OrgID,
		BucketID:        c.BucketID,
	}
	if err := c.DBRPMappingService.Create(ctx, m); err != nil {
		t.Fatalf("unable to create DBRP mapping: %v", err)
	}
	return m.ID
}

// MustCreateResource will create a generic resource via the API.
// Used in tests where the content of the resource does not matter.
//
//  // Create one of each org resource
//  for _, r := range influxdb.OrgResourceTypes {
//      client.MustCreateResource(t, r)
//  }
//
//
//  // Create a variable:
//  id := client.MustCreateResource(t, influxdb.VariablesResourceType)
//  defer client.MustDeleteResource(t, influxdb.VariablesResourceType, id)
func (c *Client) MustCreateResource(t *testing.T, r influxdb.ResourceType) platform.ID {
	t.Helper()

	switch r {
	case influxdb.AuthorizationsResourceType: // 0
		return c.MustCreateAuth(t)
	case influxdb.BucketsResourceType: // 1
		return c.MustCreateBucket(t)
	case influxdb.OrgsResourceType: // 3
		return c.MustCreateOrg(t)
	case influxdb.SourcesResourceType: // 4
		t.Skip("I think sources are going to be removed right?")
	case influxdb.TasksResourceType: // 5
		t.Skip("Task go client is not yet created")
	case influxdb.TelegrafsResourceType: // 6
		return c.MustCreateTelegraf(t)
	case influxdb.UsersResourceType: // 7
		return c.MustCreateUser(t)
	case influxdb.VariablesResourceType: // 8
		return c.MustCreateVariable(t)
	case influxdb.ScraperResourceType: // 9
		t.Skip("Scraper go client is not yet created")
	case influxdb.SecretsResourceType: // 10
		t.Skip("Secrets go client is not yet created")
	case influxdb.LabelsResourceType: // 11
		return c.MustCreateLabel(t)
	case influxdb.ViewsResourceType: // 12
		t.Skip("Are views still a thing?")
	case influxdb.NotificationRuleResourceType: // 14
		return c.MustCreateNotificationRule(t)
	case influxdb.NotificationEndpointResourceType: // 15
		return c.MustCreateNotificationEndpoint(t)
	case influxdb.ChecksResourceType: // 16
		return c.MustCreateCheck(t)
	case influxdb.DBRPResourceType: // 17
		return c.MustCreateDBRPMapping(t)
	}
	return 0
}

// DeleteResource will remove a resource using the API.
func (c *Client) DeleteResource(t *testing.T, r influxdb.ResourceType, id platform.ID) error {
	t.Helper()

	ctx := context.Background()
	switch r {
	case influxdb.AuthorizationsResourceType: // 0
		return c.DeleteAuthorization(ctx, id)
	case influxdb.BucketsResourceType: // 1
		return c.DeleteBucket(context.Background(), id)
	case influxdb.OrgsResourceType: // 3
		return c.DeleteOrganization(ctx, id)
	case influxdb.SourcesResourceType: // 4
		t.Skip("I think sources are going to be removed right?")
	case influxdb.TasksResourceType: // 5
		t.Skip("Task go client is not yet created")
	case influxdb.TelegrafsResourceType: // 6
		return c.DeleteTelegrafConfig(ctx, id)
	case influxdb.UsersResourceType: // 7
		return c.DeleteUser(ctx, id)
	case influxdb.VariablesResourceType: // 8
		return c.DeleteVariable(ctx, id)
	case influxdb.ScraperResourceType: // 9
		t.Skip("Scraper go client is not yet created")
	case influxdb.SecretsResourceType: // 10
		t.Skip("Secrets go client is not yet created")
	case influxdb.LabelsResourceType: // 11
		return c.DeleteLabel(ctx, id)
	case influxdb.ViewsResourceType: // 12
		t.Skip("Are views still a thing?")
	case influxdb.NotificationRuleResourceType: // 14
		return c.DeleteNotificationRule(ctx, id)
	case influxdb.NotificationEndpointResourceType: // 15
		// Ignore the other results as suggested by goDoc.
		_, _, err := c.DeleteNotificationEndpoint(ctx, id)
		return err
	case influxdb.ChecksResourceType: // 16
		return c.DeleteCheck(ctx, id)
	case influxdb.DBRPResourceType: // 17
		return c.DBRPMappingService.Delete(ctx, c.OrgID, id)
	}
	return nil
}

// MustDeleteResource requires no error when deleting a resource.
func (c *Client) MustDeleteResource(t *testing.T, r influxdb.ResourceType, id platform.ID) {
	t.Helper()

	if err := c.DeleteResource(t, r, id); err != nil {
		t.Fatalf("unable to delete resource %v %v: %v", r, id, err)
	}
}

// FindAll returns all the IDs of a specific resource type.
func (c *Client) FindAll(t *testing.T, r influxdb.ResourceType) ([]platform.ID, error) {
	t.Helper()

	var ids []platform.ID
	ctx := context.Background()
	switch r {
	case influxdb.AuthorizationsResourceType: // 0
		rs, _, err := c.FindAuthorizations(ctx, influxdb.AuthorizationFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.BucketsResourceType: // 1
		rs, _, err := c.FindBuckets(ctx, influxdb.BucketFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.OrgsResourceType: // 3
		rs, _, err := c.FindOrganizations(ctx, influxdb.OrganizationFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.SourcesResourceType: // 4
		t.Skip("I think sources are going to be removed right?")
	case influxdb.TasksResourceType: // 5
		t.Skip("Task go client is not yet created")
	case influxdb.TelegrafsResourceType: // 6
		rs, _, err := c.FindTelegrafConfigs(ctx, influxdb.TelegrafConfigFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.UsersResourceType: // 7
		rs, _, err := c.FindUsers(ctx, influxdb.UserFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.VariablesResourceType: // 8
		rs, err := c.FindVariables(ctx, influxdb.VariableFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.ScraperResourceType: // 9
		t.Skip("Scraper go client is not yet created")
	case influxdb.SecretsResourceType: // 10
		t.Skip("Secrets go client is not yet created")
	case influxdb.LabelsResourceType: // 11
		rs, err := c.FindLabels(ctx, influxdb.LabelFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.ViewsResourceType: // 12
		t.Skip("Are views still a thing?")
	case influxdb.NotificationRuleResourceType: // 14
		rs, _, err := c.FindNotificationRules(ctx, influxdb.NotificationRuleFilter{OrgID: &c.OrgID})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.GetID())
		}
		return ids, nil
	case influxdb.NotificationEndpointResourceType: // 15
		rs, _, err := c.FindNotificationEndpoints(ctx, influxdb.NotificationEndpointFilter{OrgID: &c.OrgID})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.GetID())
		}
	case influxdb.ChecksResourceType: // 16
		rs, _, err := c.FindChecks(ctx, influxdb.CheckFilter{})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	case influxdb.DBRPResourceType: // 17
		rs, _, err := c.DBRPMappingService.FindMany(ctx, influxdb.DBRPMappingFilter{OrgID: &c.OrgID})
		if err != nil {
			return nil, err
		}
		for _, r := range rs {
			ids = append(ids, r.ID)
		}
	}
	return ids, nil
}

// MustFindAll returns all the IDs of a specific resource type; any error
// is fatal.
func (c *Client) MustFindAll(t *testing.T, r influxdb.ResourceType) []platform.ID {
	t.Helper()

	ids, err := c.FindAll(t, r)
	if err != nil {
		t.Fatalf("unexpected error finding resources %v: %v", r, err)
	}
	return ids
}

func (c *Client) AddURM(u platform.ID, typ influxdb.UserType, r influxdb.ResourceType, id platform.ID) error {
	access := &influxdb.UserResourceMapping{
		UserID:       u,
		UserType:     typ,
		MappingType:  influxdb.UserMappingType,
		ResourceType: r,
		ResourceID:   id,
	}

	return c.CreateUserResourceMapping(
		context.Background(),
		access,
	)
}

// AddOwner associates the user as owner of the resource.
func (c *Client) AddOwner(user platform.ID, r influxdb.ResourceType, id platform.ID) error {
	return c.AddURM(user, influxdb.Owner, r, id)
}

// MustAddOwner requires that the user is associated with the resource
// or the test will be stopped fatally.
func (c *Client) MustAddOwner(t *testing.T, user platform.ID, r influxdb.ResourceType, id platform.ID) {
	t.Helper()

	if err := c.AddOwner(user, r, id); err != nil {
		t.Fatalf("unexpected error adding owner %v to %v: %v", user, id, err)
	}
}

// AddMember associates the user as member of the resource.
func (c *Client) AddMember(user platform.ID, r influxdb.ResourceType, id platform.ID) error {
	return c.AddURM(user, influxdb.Member, r, id)
}

// MustAddMember requires that the user is associated with the resource
// or the test will be stopped fatally.
func (c *Client) MustAddMember(t *testing.T, user platform.ID, r influxdb.ResourceType, id platform.ID) {
	t.Helper()

	if err := c.AddMember(user, r, id); err != nil {
		t.Fatalf("unexpected error adding member %v to %v", user, id)
	}
}

// RemoveURM removes association of the user to the resource.
// Interestingly the URM service does not make difference on the user type.
// I.e. removing an URM from a user to a resource, will delete every URM of every type
// from that user to that resource.
// Or, put in another way, there can only be one resource mapping from a user to a
// resource at a time: either you are a member, or an owner (in that case you are a member too).
func (c *Client) RemoveURM(user, id platform.ID) error {
	return c.DeleteUserResourceMapping(context.Background(), id, user)
}

// RemoveSpecificURM gets around a client issue where deletes doesn't have enough context to remove a urm from
// a specific resource type
func (c *Client) RemoveSpecificURM(rt influxdb.ResourceType, ut influxdb.UserType, user, id platform.ID) error {
	return c.SpecificURMSvc(rt, ut).DeleteUserResourceMapping(context.Background(), id, user)
}

// MustRemoveURM requires that the user is removed as owner/member from the resource.
func (c *Client) MustRemoveURM(t *testing.T, user, id platform.ID) {
	t.Helper()

	if err := c.RemoveURM(user, id); err != nil {
		t.Fatalf("unexpected error removing org/resource mapping: %v", err)
	}
}

// CreateLabelMapping creates a label mapping for label `l` to the resource with `id`.
func (c *Client) CreateLabelMapping(l platform.ID, r influxdb.ResourceType, id platform.ID) error {
	mapping := &influxdb.LabelMapping{
		LabelID:      l,
		ResourceType: r,
		ResourceID:   id,
	}
	return c.LabelService.CreateLabelMapping(
		context.Background(),
		mapping,
	)
}

// MustCreateLabelMapping requires that the label is associated with the resource
// or the test will be stopped fatally.
func (c *Client) MustCreateLabelMapping(t *testing.T, l platform.ID, r influxdb.ResourceType, id platform.ID) {
	t.Helper()

	if err := c.CreateLabelMapping(l, r, id); err != nil {
		t.Fatalf("unexpected error attaching label %v to %v: %v", l, id, err)
	}
}

// FindLabelMappings finds the labels for the specified resource.
func (c *Client) FindLabelMappings(r influxdb.ResourceType, id platform.ID) ([]platform.ID, error) {
	filter := influxdb.LabelMappingFilter{
		ResourceType: r,
		ResourceID:   id,
	}
	ls, err := c.LabelService.FindResourceLabels(
		context.Background(),
		filter,
	)
	if err != nil {
		return nil, err
	}
	var ids []platform.ID
	for _, r := range ls {
		ids = append(ids, r.ID)
	}
	return ids, nil
}

// MustFindLabelMappings makes the test fail if an error is found.
func (c *Client) MustFindLabelMappings(t *testing.T, r influxdb.ResourceType, id platform.ID) []platform.ID {
	t.Helper()

	ls, err := c.FindLabelMappings(r, id)
	if err != nil {
		t.Fatalf("unexpected error finding label mappings: %v", err)
	}
	return ls
}

// DeleteLabelMapping deletes the label for the specified resource.
func (c *Client) DeleteLabelMapping(l platform.ID, r influxdb.ResourceType, id platform.ID) error {
	m := &influxdb.LabelMapping{
		ResourceType: r,
		ResourceID:   id,
		LabelID:      l,
	}
	return c.LabelService.DeleteLabelMapping(
		context.Background(),
		m,
	)
}

// MustDeleteLabelMapping makes the test fail if an error is found.
func (c *Client) MustDeleteLabelMapping(t *testing.T, l platform.ID, r influxdb.ResourceType, id platform.ID) {
	t.Helper()

	if err := c.DeleteLabelMapping(l, r, id); err != nil {
		t.Fatalf("unexpected error deleting label %v from %v", l, id)
	}
}


text:
<?php

namespace AppBundle\Library\Serializer\AngularSchemaFormSerializer\FieldSerializer;

use Symfony\Component\Form\FormInterface;

/**
 *
 * @author Saman Shafigh <samanshafigh@gmail.com>
 */
class CheckboxFieldSerializer extends FieldSerializer
{
    /**
     * Get field data
     *
     * @param FormInterface $form
     * @return array
     */
    public function getFieldStructure(FormInterface $form)
    {
        $label = $this->getFormLabel($form);
        $name = $form->getName();

        return array(
            'name' => $name,
            'schema' => array(
                'type' => 'boolean',
                'title' => $label,
            ),
            'form' => array(
                'key' => $name,
                'type' => 'checkbox',
                'title' => $label,
            ),
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
csharp-bertpc-server
====================

C#(CSharp) BERT RPC server


text:
package com.amazonaws.services.apigateway.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Represents a usage plan than can specify who can assess associated API stages with specified request limits and
 * quotas.
 *

 *

 *

 * In a usage plan, you associate an API by specifying the API's Id and a stage name of the specified API. You add plan
 * customers by adding API keys to the plan.
 *

 *

 Create and Use
 * Usage Plans

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateUsagePlanResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The identifier of a UsagePlan resource.
     *

     */
    private String id;
    /**
     *

     * The name of a usage plan.
     *

     */
    private String name;
    /**
     *

     * The description of a usage plan.
     *

     */
    private String description;
    /**
     *

     * The associated API stages of a usage plan.
     *

     */
    private java.util.List<ApiStage> apiStages;
    /**
     *

     * The request throttle limits of a usage plan.
     *

     */
    private ThrottleSettings throttle;
    /**
     *

     * The maximum number of permitted requests per a given unit time interval.
     *

     */
    private QuotaSettings quota;
    /**
     *

     * The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS Marketplace.
     *

     */
    private String productCode;
    /**
     *

     * The collection of tags. Each tag element is associated with a given resource.
     *

     */
    private java.util.Map<String, String> tags;

    /**
     *

     * The identifier of a UsagePlan resource.
     *

     *
     * @param id
     *        The identifier of a UsagePlan resource.
     */

    public void setId(String id) {
        this.id = id;
    }

    /**
     *

     * The identifier of a UsagePlan resource.
     *

     *
     * @return The identifier of a UsagePlan resource.
     */

    public String getId() {
        return this.id;
    }

    /**
     *

     * The identifier of a UsagePlan resource.
     *

     *
     * @param id
     *        The identifier of a UsagePlan resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withId(String id) {
        setId(id);
        return this;
    }

    /**
     *

     * The name of a usage plan.
     *

     *
     * @param name
     *        The name of a usage plan.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The name of a usage plan.
     *

     *
     * @return The name of a usage plan.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The name of a usage plan.
     *

     *
     * @param name
     *        The name of a usage plan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The description of a usage plan.
     *

     *
     * @param description
     *        The description of a usage plan.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * The description of a usage plan.
     *

     *
     * @return The description of a usage plan.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * The description of a usage plan.
     *

     *
     * @param description
     *        The description of a usage plan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     *

     * The associated API stages of a usage plan.
     *

     *
     * @return The associated API stages of a usage plan.
     */

    public java.util.List<ApiStage> getApiStages() {
        return apiStages;
    }

    /**
     *

     * The associated API stages of a usage plan.
     *

     *
     * @param apiStages
     *        The associated API stages of a usage plan.
     */

    public void setApiStages(java.util.Collection<ApiStage> apiStages) {
        if (apiStages == null) {
            this.apiStages = null;
            return;
        }

        this.apiStages = new java.util.ArrayList<ApiStage>(apiStages);
    }

    /**
     *

     * The associated API stages of a usage plan.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setApiStages(java.util.Collection)} or {@link #withApiStages(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param apiStages
     *        The associated API stages of a usage plan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withApiStages(ApiStage... apiStages) {
        if (this.apiStages == null) {
            setApiStages(new java.util.ArrayList<ApiStage>(apiStages.length));
        }
        for (ApiStage ele : apiStages) {
            this.apiStages.add(ele);
        }
        return this;
    }

    /**
     *

     * The associated API stages of a usage plan.
     *

     *
     * @param apiStages
     *        The associated API stages of a usage plan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withApiStages(java.util.Collection<ApiStage> apiStages) {
        setApiStages(apiStages);
        return this;
    }

    /**
     *

     * The request throttle limits of a usage plan.
     *

     *
     * @param throttle
     *        The request throttle limits of a usage plan.
     */

    public void setThrottle(ThrottleSettings throttle) {
        this.throttle = throttle;
    }

    /**
     *

     * The request throttle limits of a usage plan.
     *

     *
     * @return The request throttle limits of a usage plan.
     */

    public ThrottleSettings getThrottle() {
        return this.throttle;
    }

    /**
     *

     * The request throttle limits of a usage plan.
     *

     *
     * @param throttle
     *        The request throttle limits of a usage plan.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withThrottle(ThrottleSettings throttle) {
        setThrottle(throttle);
        return this;
    }

    /**
     *

     * The maximum number of permitted requests per a given unit time interval.
     *

     *
     * @param quota
     *        The maximum number of permitted requests per a given unit time interval.
     */

    public void setQuota(QuotaSettings quota) {
        this.quota = quota;
    }

    /**
     *

     * The maximum number of permitted requests per a given unit time interval.
     *

     *
     * @return The maximum number of permitted requests per a given unit time interval.
     */

    public QuotaSettings getQuota() {
        return this.quota;
    }

    /**
     *

     * The maximum number of permitted requests per a given unit time interval.
     *

     *
     * @param quota
     *        The maximum number of permitted requests per a given unit time interval.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withQuota(QuotaSettings quota) {
        setQuota(quota);
        return this;
    }

    /**
     *

     * The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS Marketplace.
     *

     *
     * @param productCode
     *        The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS
     *        Marketplace.
     */

    public void setProductCode(String productCode) {
        this.productCode = productCode;
    }

    /**
     *

     * The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS Marketplace.
     *

     *
     * @return The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS
     *         Marketplace.
     */

    public String getProductCode() {
        return this.productCode;
    }

    /**
     *

     * The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS Marketplace.
     *

     *
     * @param productCode
     *        The AWS Markeplace product identifier to associate with the usage plan as a SaaS product on AWS
     *        Marketplace.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withProductCode(String productCode) {
        setProductCode(productCode);
        return this;
    }

    /**
     *

     * The collection of tags. Each tag element is associated with a given resource.
     *

     *
     * @return The collection of tags. Each tag element is associated with a given resource.
     */

    public java.util.Map<String, String> getTags() {
        return tags;
    }

    /**
     *

     * The collection of tags. Each tag element is associated with a given resource.
     *

     *
     * @param tags
     *        The collection of tags. Each tag element is associated with a given resource.
     */

    public void setTags(java.util.Map<String, String> tags) {
        this.tags = tags;
    }

    /**
     *

     * The collection of tags. Each tag element is associated with a given resource.
     *

     *
     * @param tags
     *        The collection of tags. Each tag element is associated with a given resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

    public CreateUsagePlanResult addTagsEntry(String key, String value) {
        if (null == this.tags) {
            this.tags = new java.util.HashMap<String, String>();
        }
        if (this.tags.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.tags.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into Tags.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateUsagePlanResult clearTagsEntries() {
        this.tags = null;
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: ").append(getId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription()).append(",");
        if (getApiStages() != null)
            sb.append("ApiStages: ").append(getApiStages()).append(",");
        if (getThrottle() != null)
            sb.append("Throttle: ").append(getThrottle()).append(",");
        if (getQuota() != null)
            sb.append("Quota: ").append(getQuota()).append(",");
        if (getProductCode() != null)
            sb.append("ProductCode: ").append(getProductCode()).append(",");
        if (getTags() != null)
            sb.append("Tags: ").append(getTags());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateUsagePlanResult == false)
            return false;
        CreateUsagePlanResult other = (CreateUsagePlanResult) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null && other.getId().equals(this.getId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        if (other.getApiStages() == null ^ this.getApiStages() == null)
            return false;
        if (other.getApiStages() != null && other.getApiStages().equals(this.getApiStages()) == false)
            return false;
        if (other.getThrottle() == null ^ this.getThrottle() == null)
            return false;
        if (other.getThrottle() != null && other.getThrottle().equals(this.getThrottle()) == false)
            return false;
        if (other.getQuota() == null ^ this.getQuota() == null)
            return false;
        if (other.getQuota() != null && other.getQuota().equals(this.getQuota()) == false)
            return false;
        if (other.getProductCode() == null ^ this.getProductCode() == null)
            return false;
        if (other.getProductCode() != null && other.getProductCode().equals(this.getProductCode()) == false)
            return false;
        if (other.getTags() == null ^ this.getTags() == null)
            return false;
        if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getApiStages() == null) ? 0 : getApiStages().hashCode());
        hashCode = prime * hashCode + ((getThrottle() == null) ? 0 : getThrottle().hashCode());
        hashCode = prime * hashCode + ((getQuota() == null) ? 0 : getQuota().hashCode());
        hashCode = prime * hashCode + ((getProductCode() == null) ? 0 : getProductCode().hashCode());
        hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
        return hashCode;
    }

    @Override
    public CreateUsagePlanResult clone() {
        try {
            return (CreateUsagePlanResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
#ifndef _EXPR_REPLACER_H_
#define _EXPR_REPLACER_H_

#include"ast.h"
#include"expr_substitution.h"
#include"params.h"

/**
   \brief Abstract interface for functors that replace constants with expressions.
*/
class expr_replacer {
    struct scoped_set_subst;
public:
    virtual ~expr_replacer() {}

    virtual ast_manager & m() const = 0;
    virtual void set_substitution(expr_substitution * s) = 0;

    virtual void operator()(expr * t, expr_ref & result, proof_ref & result_pr, expr_dependency_ref & deps) = 0;
    virtual void operator()(expr * t, expr_ref & result, proof_ref & result_pr);
    virtual void operator()(expr * t, expr_ref & result);
    virtual void operator()(expr_ref & t) { expr_ref s(t, m()); (*this)(s, t); }

    void cancel() { set_cancel(true); }
    void reset_cancel() { set_cancel(false); }
    virtual void set_cancel(bool f) = 0;
    virtual unsigned get_num_steps() const { return 0; }
    virtual void reset() = 0;

    void apply_substitution(expr * s, expr * def, proof * def_pr, expr_ref & t);
    void apply_substitution(expr * s, expr * def, expr_ref & t);
};

/**
   \brief Create a vanilla replacer. It just applies the substitution.
*/
expr_replacer * mk_default_expr_replacer(ast_manager & m);

/**
   \brief Apply substitution and simplify.
*/
expr_replacer * mk_expr_simp_replacer(ast_manager & m, params_ref const & p = params_ref());

#endif


text:
"""
Rain simulation

Simulates rain drops on a surface by animating the scale and opacity
of 50 scatter points.

Author: Nicolas P. Rougier
"""
import numpy as np
import matplotlib.pyplot as plt
from  matplotlib.animation import FuncAnimation

# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7,7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])

# Create rain data
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
                                      ('size',     float, 1),
                                      ('growth',   float, 1),
                                      ('color',    float, 4)])

# Initialize the raindrops in random positions and with
# random growth rates.
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)

# Construct the scatter which we will update during animation
# as the raindrops develop.
scat = ax.scatter(rain_drops['position'][:,0], rain_drops['position'][:,1],
                  s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
                  facecolors='none')

def update(frame_number):
    # Get an index which we can use to re-spawn the oldest raindrop.
    current_index = frame_number % n_drops

    # Make all colors more transparent as time progresses.
    rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
    rain_drops['color'][:,3] = np.clip(rain_drops['color'][:,3], 0, 1)

    # Make all circles bigger.
    rain_drops['size'] += rain_drops['growth']

    # Pick a new position for oldest rain drop, resetting its size,
    # color and growth factor.
    rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
    rain_drops['size'][current_index] = 5
    rain_drops['color'][current_index] = (0, 0, 0, 1)
    rain_drops['growth'][current_index] = np.random.uniform(50, 200)

    # Update the scatter collection, with the new colors, sizes and positions.
    scat.set_edgecolors(rain_drops['color'])
    scat.set_sizes(rain_drops['size'])
    scat.set_offsets(rain_drops['position'])

# Construct the animation, using the update function as the animation
# director.
animation = FuncAnimation(fig, update, interval=10)
plt.show()


text:
package com.tom.api.tileentity;

import com.tom.storage.handler.StorageData;

public class WirelessConnection {
	private StorageData data;
	private ProtectionType protectionType;
	private boolean protectedNetwork;
	private IProtection protection;
	private String name;

	public enum ProtectionType {
		NO_PROTECTION, PASSWORD, ITEM, LOGIN
		;
	}

	public static interface IProtection {

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<document>

Drilbo (Drilbo Represents an Imaging Libary not only for Blorb Objects) is the imaging support library for the fizmo interpreter. It supports the following file input formats:

JPEG

PNG

Z-Machine V6 graphics, MG1 format

Not supported:

Z-Machine V6 graphics, Amiga and Macintosh format

The following file output formats are supported:

JPEG in RGB, Grayscale and JCS_YCbCr.

PPM, P6 variant (usually for testing purposes, P3 variant available, but outcommented in the code).

The following screen output methods are supported:

X11 display though XLib, Truecolor only.

These imaging operations are implemented:

Bilinear scaling

All operations use a "z_image" type which holds all the data and metadata for images. A z_image may contain either an RGB or a grayscale file with a depth of 8 bit per pixel.

See "drilbo.h" for more information on the specific functions.

From The Z-Machine-Specification, section 8 (just for reference):

Some details of the known IBM graphics files are given in Paul David Doherty's "Infocom Fact Sheet". See also Mark Howell's program "pix2gif", which extracts pictures to GIF files. (This is one of his "Ztools" programs.)

Although Version 6 graphics files are not specified here, and were released in several different formats by Infocom for different computers, a consensus seems to have emerged that the MCGA pictures are the ones to adopt (files with filenames *.MG1). These are visually identical to Amiga pictures (whose format has been deciphered by Mark Knibbs). However, some Version 6 story files were tailored to the interpreters they would run on, and use the pictures differently according to what they expect the pictures to be. (For instance, an Amiga-intended story file will use one big Amiga-format picture where an MSDOS-intended story file will use several smaller MCGA ones.)

The easiest option is to interpret only DOS-intended Version 6 story files and only MCGA pictures. But it may be helpful to examine the Frotz source code, as Frotz implements draw_picture and picture_data so that Amiga and Macintosh forms of Version 6 story files can also be used.

It is generally felt that newly-written graphical games should not imitate the old Infocom graphics formats, which are very awkward to construct and have been overtaken by technology. Instead, the draft Blorb proposal for packaging up resources with Z-machine games calls for PNG format graphics glued together in a fairly simple way. An ideal Version 6 interpreter ought to understand both the four Infocom picture-sets and any Blorb set, thus catering for old and new games alike.

</document>


text:
package org.zstack.appliancevm;

import org.zstack.header.message.APIReply;
import org.zstack.header.query.APIQueryReply;

import java.util.List;

/**
 */
public class APIQueryApplianceVmReply extends APIQueryReply {
    private List<ApplianceVmInventory> inventories;

    public List<ApplianceVmInventory> getInventories() {
        return inventories;
    }

    public void setInventories(List<ApplianceVmInventory> inventories) {
        this.inventories = inventories;
    }
}


text:
package com.h6ah4i.android.widget.advrecyclerview.utils;

import android.view.View;

import com.h6ah4i.android.widget.advrecyclerview.expandable.ExpandableItemState;
import com.h6ah4i.android.widget.advrecyclerview.expandable.ExpandableItemViewHolder;
import com.h6ah4i.android.widget.advrecyclerview.expandable.annotation.ExpandableItemStateFlags;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public abstract class AbstractExpandableItemViewHolder extends RecyclerView.ViewHolder implements ExpandableItemViewHolder {
    private final ExpandableItemState mExpandState = new ExpandableItemState();

    public AbstractExpandableItemViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setExpandStateFlags(@ExpandableItemStateFlags int flags) {
        mExpandState.setFlags(flags);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @ExpandableItemStateFlags
    public int getExpandStateFlags() {
        return mExpandState.getFlags();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @NonNull
    public ExpandableItemState getExpandState() {
        return mExpandState;
    }
}


text:
package com.siberiadante.utilsample.http;

import android.annotation.SuppressLint;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public abstract class BaseObserver<T> implements Observer<T> {

    @SuppressLint("CheckResult")
    @Override
    public void onError(@NonNull Throwable e) {
        Observable.just(e)
                .subscribeOn(Schedulers.newThread())

                .map(new Function<Throwable, NetException.ResponseThrowable>() {
                    @Override
                    public NetException.ResponseThrowable apply(Throwable throwable) throws Exception {
                        return NetException.throwable(throwable);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<NetException.ResponseThrowable>() {
                    @Override
                    public void accept(NetException.ResponseThrowable responseThrowable) throws Exception {
                        onError(responseThrowable);
                    }
                });
//                .map(NetException::throwable)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(this::onError);
    }

    @Override
    public void onComplete() {

    }

    public abstract void onError(NetException.ResponseThrowable e);
}


text:
declare namespace java {
  namespace awt {
    namespace image {
      namespace renderable {

        class RenderableImageProducer implements java.awt.image.ImageProducer, java.lang.Runnable {
          rdblImage: java.awt.image.renderable.RenderableImage
          rc: java.awt.image.renderable.RenderContext
          ics: java.util.Vector<java.awt.image.ImageConsumer>
          public constructor(arg0: java.awt.image.renderable.RenderableImage, arg1: java.awt.image.renderable.RenderContext)
          public setRenderContext(arg0: java.awt.image.renderable.RenderContext): void
          public addConsumer(arg0: java.awt.image.ImageConsumer): void
          public isConsumer(arg0: java.awt.image.ImageConsumer): boolean
          public removeConsumer(arg0: java.awt.image.ImageConsumer): void
          public startProduction(arg0: java.awt.image.ImageConsumer): void
          public requestTopDownLeftRightResend(arg0: java.awt.image.ImageConsumer): void
          public run(): void
        }

      }
    }
  }
}


text:
package headfirst.facade.hometheater;

public class TheaterLights {
	String description;

	public TheaterLights(String description) {
		this.description = description;
	}

	public void on() {
		System.out.println(description + " on");
	}

	public void off() {
		System.out.println(description + " off");
	}

	public void dim(int level) {
		System.out.println(description + " dimming to " + level  + "%");
	}

	public String toString() {
		return description;
	}
}


text:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Elders.Cronus
{
    public abstract class CronusOptionsProviderBase<TOptions> :
        IConfigureOptions<TOptions>,
        IOptionsChangeTokenSource<TOptions>,
        IOptionsFactory<TOptions>,
        IPostConfigureOptions<TOptions>
        where TOptions : class, new()
    {
        protected IConfiguration configuration;

        public CronusOptionsProviderBase(IConfiguration configuration, string name)
        {
            this.configuration = configuration;
            this.Name = name;
        }

        public CronusOptionsProviderBase(IConfiguration configuration)
            : this(configuration, Options.DefaultName)
        { }

        public string Name { get; private set; }

        public abstract void Configure(TOptions options);

        public TOptions Create(string name)
        {
            var newOptions = new TOptions();
            Configure(newOptions);
            ValidateByDataAnnotation(newOptions);
            return newOptions;
        }

        public IChangeToken GetChangeToken() => configuration.GetReloadToken();

        public virtual void PostConfigure(string name, TOptions options) { }

        private void ValidateByDataAnnotation(object instance)
        {
            var validationResults = new List<ValidationResult>();
            var context = new ValidationContext(instance);
            var valid = Validator.TryValidateObject(instance, context, validationResults, true);
            if (valid) return;

            var msg = string.Join("\n", validationResults.Select(r => r.ErrorMessage));
            throw new Exception($"Invalid configuration!':\n{msg}");
        }
    }
}


text:
package v1alpha1

// This file contains a collection of methods that can be used from go-restful to
// generate Swagger API documentation for its models. Please read this PR for more
// information on the implementation: https://github.com/emicklei/go-restful/pull/215
//
// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
// they are on one line! For multiple line or blocks that you want to ignore use ---.
// Any context after a --- is ignored.
//
// Those methods can be generated by using hack/update-generated-swagger-docs.sh

// AUTO-GENERATED FUNCTIONS START HERE
var map_PetSet = map[string]string{
	"":       "PetSet represents a set of pods with consistent identities. Identities are defined as:\n - Network: A single stable DNS and hostname.\n - Storage: As many VolumeClaims as requested.\nThe PetSet guarantees that a given network identity will always map to the same storage identity. PetSet is currently in alpha and subject to change without notice.",
	"spec":   "Spec defines the desired identities of pets in this set.",
	"status": "Status is the current status of Pets in this PetSet. This data may be out of date by some window of time.",
}

func (PetSet) SwaggerDoc() map[string]string {
	return map_PetSet
}

var map_PetSetList = map[string]string{
	"": "PetSetList is a collection of PetSets.",
}

func (PetSetList) SwaggerDoc() map[string]string {
	return map_PetSetList
}

var map_PetSetSpec = map[string]string{
	"":                     "A PetSetSpec is the specification of a PetSet.",
	"replicas":             "Replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1.",
	"selector":             "Selector is a label query over pods that should match the replica count. If empty, defaulted to labels on the pod template. More info: http://releases.k8s.io/release-1.3/docs/user-guide/labels.md#label-selectors",
	"template":             "Template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the PetSet will fulfill this Template, but have a unique identity from the rest of the PetSet.",
	"volumeClaimTemplates": "VolumeClaimTemplates is a list of claims that pets are allowed to reference. The PetSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pet. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name.",
	"serviceName":          "ServiceName is the name of the service that governs this PetSet. This service must exist before the PetSet, and is responsible for the network identity of the set. Pets get DNS/hostnames that follow the pattern: pet-specific-string.serviceName.default.svc.cluster.local where \"pet-specific-string\" is managed by the PetSet controller.",
}

func (PetSetSpec) SwaggerDoc() map[string]string {
	return map_PetSetSpec
}

var map_PetSetStatus = map[string]string{
	"":                   "PetSetStatus represents the current state of a PetSet.",
	"observedGeneration": "most recent generation observed by this autoscaler.",
	"replicas":           "Replicas is the number of actual replicas.",
}

func (PetSetStatus) SwaggerDoc() map[string]string {
	return map_PetSetStatus
}

// AUTO-GENERATED FUNCTIONS END HERE


text:
// Copyright 2015 Google Inc. 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.
package com.google.devtools.build.lib.bazel.rules.android;

import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.bazel.repository.RepositoryFunction;
import com.google.devtools.build.lib.packages.PackageIdentifier.RepositoryName;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.skyframe.FileValue;
import com.google.devtools.build.lib.skyframe.RepositoryValue;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

/**
 * Implementation of the {@code android_local_tools_repository} rule.
 */
public class AndroidLocalToolsRepositoryFunction extends RepositoryFunction {
  @Override
  public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException {
    RepositoryName repositoryName = (RepositoryName) skyKey.argument();
    Rule rule = getRule(
        repositoryName, AndroidRepositoryRules.AndroidLocalRepositoryRule.NAME, env);
    if (rule == null) {
      return null;
    }

    FileValue directoryValue = prepareLocalRepositorySymlinkTree(rule, env);
    if (directoryValue == null) {
      return null;
    }

    PathFragment pathFragment = getTargetPath(rule);

    if (!symlinkLocalRepositoryContents(
        directoryValue.realRootedPath().asPath(),
        getOutputBase().getFileSystem().getPath(pathFragment),
        env)) {
      return null;
    }

    return RepositoryValue.create(directoryValue);
  }

  @Override
  public SkyFunctionName getSkyFunctionName() {
    return SkyFunctionName.create(
        AndroidRepositoryRules.AndroidLocalRepositoryRule.NAME.toUpperCase());
  }

  @Override
  public Class<? extends RuleDefinition> getRuleDefinition() {
    return AndroidRepositoryRules.AndroidLocalRepositoryRule.class;
  }
}


text:
@implementation PlanningPokerServer

ServerState serverState;

- (id)init {
    self = [super init];

    if (!self) {
        return nil;
    }

    serverState = ServerStateIdle;

    return self;
}

- (void)startBroadcastingForSessionId:(NSString *)sessionId {

    NSAssert(serverState == ServerStateIdle, @"Wrong state!!");

    serverState = ServerStateAcceptingConnections;

    self.connectedClients = [NSMutableArray arrayWithCapacity:self.maxClients];

    self.session = [[GKSession alloc] initWithSessionID:sessionId displayName:nil sessionMode:GKSessionModeServer];
    self.session.delegate = self;
    self.session.available = YES;
}

- (void)endBroadcasting {

    NSAssert(serverState != ServerStateIdle, @"Wrong state!!");

    serverState = ServerStateIdle;

    [self.session disconnectFromAllPeers];
    self.session.available = FALSE;
    self.session.delegate = nil;

    self.session = nil;

    self.connectedClients = nil;

    [self.delegate planningPokerServerEndedBroadcasting:self];
}

- (void)stopAcceptingNewConnections {
    NSAssert(serverState == ServerStateAcceptingConnections, @"Wrong state!!");

    serverState = ServerStateStopAcceptingNewConnections;
    self.session.available = FALSE;
}

#pragma mark - GKSessionDelegate
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
    NSLog(@"PlanningPokerServer: peer %@ changed state %d", peerID, state);

    //check the state
    switch(state) {
        case GKPeerStateAvailable:
            NSLog(@"GKPeerStateAvailable");
            break;
        case GKPeerStateUnavailable:
            NSLog(@"GKPeerStateUnavailable");
            break;
        case GKPeerStateConnected:
            //Client has connected to server
            NSLog(@"GKPeerStateConnected");

            NSAssert(serverState == ServerStateAcceptingConnections, @"Wrong state!!");

            if(![self.connectedClients containsObject:peerID]) {

                [self.connectedClients addObject:peerID];
                [self.delegate planningPokerServer:self connectedToClient:peerID];
            }

            break;
        case GKPeerStateDisconnected:
            //Client has disconnected from server
            NSLog(@"GKPeerStateDisconnected");

            NSAssert(serverState != ServerStateIdle, @"Wrong state!!");

            if([self.connectedClients containsObject:peerID]) {

                [self.connectedClients removeObject:peerID];
                [self.delegate planningPokerServer:self disconnetedFromClient:peerID];
            }

            break;
        case GKPeerStateConnecting:
            NSLog(@"GKPeerStateConnecting");
            break;
    }
}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {
	NSLog(@"PlanningPokerServer: received connection request from peer %@", peerID);

    NSAssert(serverState == ServerStateAcceptingConnections, @"Wrong state!!");

    if([self.connectedClients count] < self.maxClients) {
        NSError *error;

        if([session acceptConnectionFromPeer:peerID error:&error]) {
            NSLog(@"Connection accepted from %@", peerID);
        } else {
            NSLog(@"Connection error from peer: %@ with error: %@", peerID, error);
        }
    } else {
        NSLog(@"Denied connection...too many devices");
    }
}

- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
    NSLog(@"PlanningPokerServer: connection with peer %@ failed %@", peerID, error);
}

- (void)session:(GKSession *)session didFailWithError:(NSError *)error {
	NSLog(@"PlanningPokerServer: session failed %@", error);

    if ([[error domain] isEqualToString:GKSessionErrorDomain]) {
        if([error code] == GKSessionCannotEnableError) {

            [self.delegate planningPokerServer:self withErrorReason:ErrorReasonNoNetworkCapabilities];

            [self endBroadcasting];
        }
    }
}

- (ServerState) getState {
    return serverState;
}

@end


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;

//STATUS : One method named getSharedContainersOwnedByUser not yet implemented --CLOSED

namespace Server.DBManager
{
    class CListM
    {
        SqlDataReader reader;
        SqlCommand command;

        /// <summary>
        /// This method insert record into CLIST table
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="cm"></param>
        /// <returns></returns>
        public Boolean insertIntoCList(SqlConnection connection, Model.CListModel cm)
        {
            try
            {
                command = new SqlCommand("INSERT INTO CLIST (UID, RID, READWRITE, OWNER) VALUES (@UID, @RID, @READWRITE, @OWNER)");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@UID", cm.getUid());
                command.Parameters.AddWithValue("@RID", cm.getRid());
                command.Parameters.AddWithValue("@OWNER", cm.getOwner());
                command.Parameters.AddWithValue("@READWRITE", cm.getReadwrite());
                command.ExecuteNonQuery();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("inserIntoCList method says->" + e.Message);
            }
            return false;
        }

        /// <summary>
        /// This method checks the user's permission on particular container
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="containerName"></param>
        /// <returns>NIL/READ/WRITE</returns>
        public String checkResourcePermission(SqlConnection connection, int uid, String containerName)
        {
            ResourceM resource = new ResourceM();
            Model.AzureContainerModel r = new Model.AzureContainerModel();
            r = resource.getResourceByContainerName(connection, containerName);
            int resourceID = r.getRid();
            try
            {
                command = new SqlCommand("SELECT READWRITE FROM CLIST WHERE RID = @RID AND UID = @UID");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@UID", uid);
                command.Parameters.AddWithValue("@RID", resourceID);
                reader = command.ExecuteReader();

                //If no record is available; it means no permission is granted to given user on given container
                if (!reader.HasRows)
                {
                    return "NIL";
                }

                int permission = 0;
                while (reader.Read())
                {
                    permission = reader.GetInt32(0);
                }
                reader.Close();

                if (permission == 0)
                {
                    return "READ";
                }
                else
                {
                    return "WRITE";
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("CListM class: checkResourcePermission method exception->"+ex.Message);
            }
            return "NIL";
        }

        /// <summary>
        /// This method returns the list of containers which are shared with given user
        /// each element seems like "CONTAINERNAME:OWNERFULLNAME:GIVENCONTAINERNAME" //User friendly manner
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="userid"></param>
        /// <returns>null/string array contains the name of containers</returns>
        public String[] getSharedContainersWithUser(SqlConnection connection, int userid) {
            String[] sharedContainers = null;
            try {
                command = new SqlCommand("SELECT RID, OWNER FROM CLIST WHERE UID = @UID");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@UID", userid);
                reader = command.ExecuteReader();

                //no containers shared with user
                if (!reader.HasRows)
                {
                    return null;
                }

                ResourceM r = new ResourceM();
                UserM u = new UserM();
                int currRid = 0;
                String ownerName = null;
                Model.AzureContainerModel cont = new Model.AzureContainerModel();
                List<String> containersString = new List<String>();
                while (reader.Read())
                {
                    currRid = reader.GetInt32(0);
                    cont = r.getResourceById(connection, currRid);
                    Console.WriteLine("Owner: " + reader.GetInt32(1));
                    ownerName = (u.getUserRecordByID(connection, (reader.GetInt32(1)))).getFullName();
                    containersString.Add((cont.getContainerName())+":"+ownerName+":"+(cont.getGivenName()));
                }
                reader.Close();

                sharedContainers = containersString.ToArray();
                return sharedContainers;
            }
            catch (SqlException ex)
            {
                Console.WriteLine("CListM class: getSharedContainersWithUser method Exception->"+ex.Message);
            }
            return null;
        }

        /// <summary>
        /// This method returns the list of containers which are shared by given ownerid
        /// each element seems like "CONTAINERNAME:GIVENNAME" //User friendly manner
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="ownerid"></param>
        /// <returns></returns>
        public String[] getSharedContainersOwnedByUser(SqlConnection connection, int ownerid)
        {
            String[] sharedContainers = null;
            try {
                command = new SqlCommand("SELECT RID FROM CLIST WHERE OWNER = @OWNER");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@OWNER", ownerid);
                reader = command.ExecuteReader();

                //no containers shared by ownerid
                if (!reader.HasRows)
                {
                    return null;
                }

                ResourceM r = new ResourceM();

                int currRid = 0;
                List<String> containersString = new List<String>();
                while (reader.Read())
                {
                    currRid = reader.GetInt32(0);
                    containersString.Add(((r.getResourceById(connection, currRid)).getContainerName()) + ":" + ((r.getResourceById(connection, currRid)).getGivenName()));
                }
                reader.Close();
                foreach (string author in containersString)
                {
                    Console.WriteLine(author);
                }
                sharedContainers = containersString.ToArray();
                return sharedContainers;
            }
            catch (SqlException ex)
            {
                Console.WriteLine("CListM class: getSharedContainersOwnedByUser method Exception->" + ex.Message);
            }
            return null;

        }

        /// <summary>
        /// This getSharedResourceByGivenName() method returns the shared folder model of givenname and uid
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="uid"></param>
        /// <param name="givenName"></param>
        /// <returns></returns>
        public Model.CListModel getSharedResourceByGivenName(SqlConnection connection, int uid, String givenName)
        {
            try
            {
                command = new SqlCommand("SELECT C.RID, C.UID, C.OWNER, C.READWRITE FROM CLIST C, CONTAINERS CO WHERE C.UID = @UID AND CO.GIVENNAME = @GIVENNAME AND C.RID = CO.RID");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@UID", uid);
                command.Parameters.AddWithValue("@GIVENNAME", givenName);
                reader = command.ExecuteReader();

                //no containers shared by ownerid
                if (!reader.HasRows)
                {
                    return null;
                }
                Model.CListModel cl = new Model.CListModel();

                while (reader.Read())
                {
                    cl.setRid(reader.GetInt32(0));
                    cl.setUid(reader.GetInt32(1));
                    cl.setOwner(reader.GetInt32(2));
                    cl.setReadwrite(reader.GetInt32(3));
                }

                reader.Close();
                return cl;
            }
            catch (SqlException ex)
            {
                Console.WriteLine("CLISTM class getSharedResouceByGivenName method exception->" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// This deleteEntryFromCLIST() method deletes the entry from the CLIST as per
        /// the given userid and containerID
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="userid"></param>
        /// <param name="containerID"></param>
        /// <returns></returns>
        public Boolean deleteUserEntryFromCLIST(SqlConnection connection, int userid, int containerID)
        {
            try
            {
                if (userid == 0)    //delete all records witth respect to given containerID
                {
                    command = new SqlCommand("DELETE FROM CLIST WHERE RID = @RID");
                    command.CommandType = CommandType.Text;
                    command.Connection = connection;
                    command.Parameters.AddWithValue("@RID", containerID);
                }
                else
                {
                    command = new SqlCommand("DELETE FROM CLIST WHERE UID = @UID AND RID = @RID");
                    command.CommandType = CommandType.Text;
                    command.Connection = connection;
                    command.Parameters.AddWithValue("@UID", userid);
                    command.Parameters.AddWithValue("@RID", containerID);
                }

                command.ExecuteNonQuery();
                return true;
            }
            catch(SqlException ex)
            {
                Console.WriteLine("CLISTM class deleteUserEntryFromCLIST method exception->"+ex.Message);
                return false;
            }
        }

        /// <summary>
        /// This isRecordExistsForContainID() method checks whether any record exists for given containerID
        /// which means it check whether any permission is granted to other user on given container
        /// </summary>
        /// <returns></returns>
        public Boolean isRecordExistsForContainerID(SqlConnection connection, int containerID)
        {
            try
            {
                command = new SqlCommand("SELECT * FROM CLIST WHERE RID = @RID");
                command.CommandType = CommandType.Text;
                command.Connection = connection;
                command.Parameters.AddWithValue("@RID", containerID);
                reader = command.ExecuteReader();

                //no containers shared by ownerid
                int count = 0;
                while(reader.Read())
                {
                    count++;
                }
                if (count == 0) { return false; }
                return true;
            }
            catch (SqlException ex)
            {
                Console.WriteLine("CLISTM class isRecordExistsForContainerID method exception->" + ex.Message);
                return false;
            }
        }
    }
}


text:
{% extends 'osdc/files/file_base.html' %}
{% load i18n %}
{% block title %}{% trans "Users" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Users") %}
{% endblock page_header %}

{% block main %}
  {{ table.render }}
{% endblock %}


text:
package  org.pentaho.di.trans.steps.monetdbbulkloader;

import org.junit.Ignore;
import org.junit.Test;

public class MonetDBBulkLoaderTest {

  static final String DB = "pentaho-instaview";
  static final int PORT = 50000;
  static final String USER = "monetdb";
  static final String PASSWORD = "monetdb";
  static final String HOST = "localhost";

  // not a real unit test: ignore it. depends on monetdb running and a specific table existing in it.
  // was created to help test/verify the transition away from mclient process to MapiSocket API.
  @Ignore
  @Test
  public void testExecuteQuery() throws Exception {

    String query = "SELECT * FROM instaview_20121031113843842";
    MonetDBBulkLoader.executeSql(query, HOST, PORT, USER, PASSWORD, DB);

    query = "SELECT * FROM badtable";
    MonetDBBulkLoader.executeSql(query, HOST, PORT, USER, PASSWORD, DB);

  }

}


text:
<?php
namespace FS\SolrBundle\Doctrine\ODM\Listener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use FS\SolrBundle\Solr;
use FS\SolrBundle\SolrQueryFacade;

class UpdateDocumentListener
{

    /**
     * @var Solr
     */
    private $solr = null;

    /**
     * @param Solr $solr
     */
    public function __construct(Solr $solr)
    {
        $this->solr = $solr;
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getDocument();

        try {
            $repo = $this->solr->getRepository($entity);
            $repo->update($entity);
        } catch (\RuntimeException $e) {
        }
    }
}


text:
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as operations from "./operations";

declare class AutoRestParameterizedCustomHostTestClient {
  /**
   * @class
   * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class.
   * @constructor
   *
   * @param {string} subscriptionId - The subscription id with value 'test12'.
   *
   * @param {object} [options] - The parameter options
   *
   * @param {Array} [options.filters] - Filters to be added to the request pipeline
   *
   * @param {object} [options.requestOptions] - Options for the underlying request object
   * {@link https://github.com/request/request#requestoptions-callback Options doc}
   *
   * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
   *
   * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'.
   *
   */
  constructor(subscriptionId: string, options?: ServiceClientOptions);

  subscriptionId: string;

  dnsSuffix: string;

  // Operation groups
  paths: operations.Paths;
}

export = AutoRestParameterizedCustomHostTestClient;


text:
import theano
import theano.tensor as T
from diktya.theano.border import add_border

from keras.backend.common import floatx, cast_to_floatx
import numpy as np
import warnings

def sobel(img, border_mode='zero'):
    filter = np.array([
        [1, 0, -1],
        [2, 0, -2],
        [1, 0, -1],
    ], dtype=floatx())
    img, conv_border = add_border(img, border=1, mode=border_mode)
    kernel_x = theano.shared(filter[np.newaxis, np.newaxis])
    kernel_y = theano.shared(np.transpose(filter)[np.newaxis, np.newaxis])
    conv_x = T.nnet.conv2d(img, kernel_x, border_mode=conv_border,
                           input_shape=(None, 1, None, None),
                           filter_shape=(1, 1, 3, 3))
    conv_y = T.nnet.conv2d(img, kernel_y, border_mode=conv_border,
                           input_shape=(None, 1, None, None),
                           filter_shape=(1, 1, 3, 3))
    return conv_x, conv_y

def gaussian_kernel_default_radius(sigma, window_radius=None):
    if window_radius is None:
        radius = T.cast(T.max(T.ceil(3*sigma)), 'int32')
        if type(sigma) in (float, int):
            return int(radius.eval())
        else:
            return radius
    else:
        return window_radius

def np_gaussian_kernel_1d(sigma, window_radius=None):
    assert type(sigma) in (float, int)
    if window_radius is None:
        window_radius = int(np.ceil(3*sigma))
    index = np.arange(2*window_radius + 1) - window_radius
    kernel = np.exp(-0.5*index**2/sigma**2)
    kernel = kernel / kernel.sum()
    return cast_to_floatx(kernel)

def np_gaussian_kernel_2d(sigma, window_radius=None):
    kernel = np_gaussian_kernel_1d(sigma, window_radius)
    kernel_2d = np.dot(kernel.reshape(-1, 1), kernel.reshape(1, -1))
    assert len(kernel_2d.shape) == 2
    return kernel_2d

def gaussian_kernel_1d(sigma, window_radius=None):
    if type(sigma) in (float, int):
        sigma = T.as_tensor_variable(sigma)
    if sigma.ndim == 0:
        sigma = sigma.reshape((1,))
    nb_sigmas = sigma.shape[0]
    sigma = sigma.reshape((nb_sigmas, 1))
    radius = gaussian_kernel_default_radius(sigma, window_radius)
    index = T.arange(2*radius + 1) - radius
    index = T.cast(index, 'float32')
    index = T.tile(index, nb_sigmas).reshape((nb_sigmas, 2*radius+1))
    kernel = T.exp(-0.5*index**2/sigma**2)
    kernel = kernel / kernel.sum(axis=1).dimshuffle(0, 'x')
    kernel = T.cast(kernel, 'float32')
    if type(sigma) in (float, int) and \
            type(window_radius) in (float, int, type(None)):
        evaluated_kernel = T.as_cuda_or_tensor_variable(kernel.eval())
        return evaluated_kernel
    return kernel

def _get_chained_w_h_conv_border(mode, axis):
    if type(mode) == int:
        if axis == 'w':
            return (0, mode)
        elif axis == 'h':
            return (mode, 0)
        else:
            Exception("Unknown axis {}".format(mode))
    else:
        return mode

def gaussian_filter_2d(input, sigma, window_radius=None,
                       border_mode='zero'):
    bs, ch, h, w = input.shape
    ndim = 4
    assert input.ndim == ndim, \
        "there must be {} dimensions, got {}".format(ndim, input.ndim)
    window_radius = gaussian_kernel_default_radius(sigma, window_radius)
    input = input.reshape((bs*ch, 1, h, w))
    filter_1d = gaussian_kernel_1d(sigma, window_radius)
    dimpattern_w = ('x', 'x', 0, 1)
    dimpattern_h = ('x', 'x', 1, 0)
    filter_w = filter_1d.dimshuffle(dimpattern_w)
    padded_input, conv_border = add_border(input, window_radius, border_mode)

    blur_w = T.nnet.conv2d(
        padded_input, filter_w,
        border_mode=_get_chained_w_h_conv_border(conv_border, 'w'),
        filter_shape=[1, 1, 1, None])
    filter_h = filter_1d.dimshuffle(dimpattern_h)

    blured = T.nnet.conv2d(
        blur_w, filter_h,
        border_mode=_get_chained_w_h_conv_border(conv_border, 'h'),
        filter_shape=[1, 1, None, 1])
    return blured.reshape((bs, ch, h, w))

def gaussian_filter_2d_variable_sigma(input, sigmas,
                                      window_radius=None,
                                      border_mode='zero'
                                      ):
    warnings.warn("gaussian_filter_2d_variable_sigma takes forever to compile.")

    def filter_sigma(idx, kernel):
        dimpattern_w = ('x', 'x', 'x', 0)
        dimpattern_h = ('x', 'x', 0, 'x')
        filter_w = kernel.dimshuffle(dimpattern_w)
        blur_w = T.nnet.conv2d(
            padded_input[idx:idx+1], filter_w,
            border_mode=_get_chained_w_h_conv_border(conv_border, 'w'),
            filter_shape=[1, 1, 1, None])
        filter_h = kernel.dimshuffle(dimpattern_h)
        return T.nnet.conv2d(
            blur_w, filter_h,
            border_mode=_get_chained_w_h_conv_border(conv_border, 'h'),
            filter_shape=[1, 1, None, 1])

    ndim = 4
    assert input.ndim == ndim, \
        "there must be {} dimensions, got {}".format(ndim, input.ndim)
    window_radius = gaussian_kernel_default_radius(sigmas, window_radius)
    padded_input, conv_border = add_border(input, window_radius, border_mode)
    kernel = gaussian_kernel_1d(sigmas, window_radius)
    blur, _ = theano.map(
        filter_sigma,
        sequences=[T.arange(sigmas.shape[0]), kernel])
    return blur.reshape(input.shape)


text:
import * as React from "react";
import * as PropTypes from "prop-types";

import MarkdownRender from "react-uwp/MarkdownRender";
import * as readMeText from "!raw!./README.md";

export interface DataProps {}

export interface ServerSideRenderingProps extends DataProps, React.HTMLAttributes<HTMLDivElement> {}

export default class ServerSideRendering extends React.Component<ServerSideRenderingProps> {
  static contextTypes = { theme: PropTypes.object };
  context: { theme: ReactUWP.ThemeType };

  render() {
    const {
      style,
      ...attributes
    } = this.props;
    const { theme } = this.context;

    return (
      <MarkdownRender
        {...attributes}
        style={theme.prefixStyle({ ...style, padding: "0 20px 60px" })}
        text={readMeText as any}
      />
    );
  }
}


text:
<?php

namespace CEOFESABundle\Form\Subscriber;

use CEOFESABundle\Repository\StructureRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ParcoursSubscriber implements EventSubscriberInterface
{
    /**
     * @param FormEvent $event
     */
    public function onPreSetData(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();
        $type = $data !== null ? $data->getPrcType()->getMtyType() : 'INTRA';

        if ($type === 'INTRA') {
            $form->add('prcStructure', 'entity', array(
                'class'         => 'CEOFESABundle\Entity\Structure',
                'property'      => 'strNom',
                'label'         => 'OF',
                'multiple'      => false,
                'query_builder' => function(StructureRepository $repository) {
                    return $repository->getIntra();
                },
            ));
        } elseif ($type === 'EXTERNE') {
            $form->add('prcStructure', 'entity', array(
                'class'         => 'CEOFESABundle\Entity\Structure',
                'property'      => 'strNom',
                'label'         => 'OF',
                'multiple'      => false,
                'query_builder' => function(StructureRepository $repository) use ($form) {
                    return $repository->getSoustraitants($form->getConfig()->getOption('structure'));
                }
            ));
        }
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (!isset($data['prcStructure']) || $data['prcStructure'] === null) {
            return;
        }

        $form = $event->getForm();
        $ofId = $data['prcStructure'];

        $form
            ->remove('prcStructure')
            ->add('prcStructure', 'entity', array(
                'class'         => 'CEOFESABundle\Entity\Structure',
                'property'      => 'strNom',
                'label'         => 'OF',
                'multiple'      => false,
                'query_builder' => function(StructureRepository $repo) use ($ofId) {
                    return $repo->getSoustraitant($ofId);
                }
            ));
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'onPreSetData',
            FormEvents::PRE_SUBMIT   => 'onPreSubmit',
        );
    }
}


text:
package org.displaytag.filter;

import java.io.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;

/**
 * A simple implementation of ServletOutputStream which wraps a ByteArrayOutputStream.
 *
 * @author Fabrizio Giustina
 *
 * @version $Revision$ ($Author$)
 */
public class SimpleServletOutputStream extends ServletOutputStream {

    /**
     * My outputWriter stream, a buffer.
     */
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    /**
     * {@inheritDoc}
     */
    @Override
    public void write(final int b) {
        this.outputStream.write(b);
    }

    /**
     * Get the contents of the outputStream.
     *
     * @return contents of the outputStream
     */
    @Override
    public String toString() {
        return this.outputStream.toString();
    }

    /**
     * Reset the wrapped ByteArrayOutputStream.
     */
    public void reset() {
        this.outputStream.reset();
    }

    /**
     * Checks if is ready.
     *
     * @return true, if is ready
     */
    // TODO Do not add override as this is intended for very old legacy support and otherwise has no value beyond
    // compilation.
    @Override
    public boolean isReady() {
        return false;
    }

    /**
     * Sets the write listener.
     *
     * @param writeListener
     *            the new write listener
     */
    // TODO Do not add override as this is intended for very old legacy support and otherwise has no value beyond
    // compilation.
    @Override
    public void setWriteListener(final WriteListener writeListener) {
        // TODO Not yet supported
    }
}