text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Context\Api\Admin;

use ApiPlatform\Core\Api\IriConverterInterface;
use Behat\Behat\Context\Context;
use Sylius\Behat\Client\ApiClientInterface;
use Sylius\Behat\Client\ResponseCheckerInterface;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Product\Model\ProductOption;
use Sylius\Component\Product\Model\ProductOptionInterface;
use Symfony\Component\HttpFoundation\Response;
use Webmozart\Assert\Assert;

final class ManagingProductsContext implements Context
{
    public const SORT_TYPES = ['ascending' => 'asc', 'descending' => 'desc'];

    /** @var ApiClientInterface */
    private $client;

    /** @var ApiClientInterface */
    private $adminUsersClient;

    /** @var ApiClientInterface */
    private $productReviewsClient;

    /** @var ResponseCheckerInterface */
    private $responseChecker;

    /** @var IriConverterInterface */
    private $iriConverter;

    /** @var SharedStorageInterface */
    private $sharedStorage;

    public function __construct(
        ApiClientInterface $client,
        ApiClientInterface $adminUsersClient,
        ApiClientInterface $productReviewsClient,
        ResponseCheckerInterface $responseChecker,
        IriConverterInterface $iriConverter,
        SharedStorageInterface $sharedStorage
    ) {
        $this->client = $client;
        $this->adminUsersClient = $adminUsersClient;
        $this->productReviewsClient = $productReviewsClient;
        $this->responseChecker = $responseChecker;
        $this->iriConverter = $iriConverter;
        $this->sharedStorage = $sharedStorage;
    }

    /**
     * @When I start sorting products by name
     * @When I sort the products :sortType by name
     * @When I switch the way products are sorted :sortType by name
     * @Given the products are already sorted :sortType by name
     */
    public function iStartSortingProductsByName(string $sortType = 'ascending'): void
    {
        $this->client->sort([
            'translation.name' => self::SORT_TYPES[$sortType],
            'localeCode' => $this->getAdminLocaleCode(),
        ]);
    }

    /**
     * @Given I am browsing products
     * @When I browse products
     * @When I want to browse products
     */
    public function iWantToBrowseProducts(): void
    {
        $this->client->index();
    }

    /**
     * @When I change my locale to :localeCode
     */
    public function iSwitchTheLocaleToTheLocale(string $localeCode): void
    {
        /** @var AdminUserInterface $adminUser */
        $adminUser = $this->sharedStorage->get('administrator');

        $this->adminUsersClient->buildUpdateRequest((string) $adminUser->getId());

        $this->adminUsersClient->updateRequestData(['localeCode' => $localeCode]);
        $this->adminUsersClient->update();
    }

    /**
     * @When I want to create a new configurable product
     * @When I want to create a new simple product
     */
    public function iWantToCreateANewConfigurableProduct(): void
    {
        $this->client->buildCreateRequest();
    }

    /**
     * @When I specify its code as :code
     * @When I do not specify its code
     */
    public function iSpecifyItsCodeAs(string $code = null): void
    {
        $this->client->addRequestData('code', $code);
    }

    /**
     * @When I name it :name in :localeCode
     * @When I rename it to :name in :localeCode
     * @When I do not name it
     */
    public function iRenameItToIn(?string $name = null, string $localeCode = 'en_US'): void
    {
        $data['translations'][$localeCode]['locale'] = $localeCode;

        if ($name !== null) {
            $data['translations'][$localeCode]['name'] = $name;
        }

        $this->client->updateRequestData($data);
    }

    /**
     * @When /^I set its(?:| default) price to "(?:€|£|\$)([^"]+)" for ("[^"]+" channel)$/
     */
    public function iSetItsPriceTo(string $price, ChannelInterface $channel): void
    {
        $localeCode = $channel->getLocales()->first()->getCode();

        $data = [
            'translations' => [
                $localeCode => [
                    'locale' => $localeCode,
                    'price' => $price,
                ],
            ],
            'channel' => $this->iriConverter->getIriFromItem($channel),
        ];

        $this->client->updateRequestData($data);
    }

    /**
     * @When I set its slug to :slug
     * @When I set its slug to :slug in :localeCode
     * @When I remove its slug
     */
    public function iSetItsSlugTo(?string $slug = null, $localeCode = 'en_US'): void
    {
        $data = [
            'translations' => [
                $localeCode => [
                    'locale' => $localeCode,
                    'slug' => $slug,
                ],
            ],
        ];

        $this->client->updateRequestData($data);
    }

    /**
     * @When I (try to) add it
     */
    public function iAddIt(): void
    {
        $this->client->create();
    }

    /**
     * @When I add the :productOption option to it
     */
    public function iAddTheOptionToIt(ProductOption $productOption): void
    {
        /** @var ProductInterface $product */
        $product = $this->sharedStorage->get('product');

        $productOptions = $this->responseChecker->getValue($this->client->show($product->getCode()), 'options');

        $productOptions[] = $this->iriConverter->getIriFromItem($productOption);

        $this->client->updateRequestData(['options' => $productOptions]);
    }

    /**
     * @When /^I choose main (taxon "[^"]+")$/
     */
    public function iChooseMainTaxon(TaxonInterface $taxon): void
    {
        $this->client->updateRequestData(['mainTaxon' => $this->iriConverter->getIriFromItem($taxon)]);
    }

    /**
     * @When I (try to) save my changes
     */
    public function iSaveMyChanges(): void
    {
        $this->client->update();
    }

    /**
     * @When I filter them by :taxon taxon
     */
    public function iFilterThemByTaxon(TaxonInterface $taxon): void
    {
        $this->client->addFilter('productTaxons.taxon.code', $taxon->getCode());
        $this->client->filter();
    }

    /**
     * @When I start sorting products by code
     * @When I switch the way products are sorted :sortType by code
     */
    public function iSwitchTheWayProductsAreSortedByCode(string $sortType = 'ascending'): void
    {
        $this->client->sort(['code' => self::SORT_TYPES[$sortType]]);
    }

    /**
     * @When I (try to) delete the :product product
     */
    public function iDeleteProduct(ProductInterface $product): void
    {
        $this->client->delete($product->getCode());
    }

    /**
     * @When /^I want to modify (this product)$/
     * @When I (want to) modify the :product product
     */
    public function iWantToModifyAProduct(ProductInterface $product): void
    {
        $this->client->buildUpdateRequest($product->getCode());
    }

    /**
     * @When I enable slug modification
     * @When I enable slug modification in :localeCode
     */
    public function iEnableSlugModification(string $localeCode = 'en_US'): void
    {
        $data['translations'][$localeCode]['slug'] = '';

        $this->client->updateRequestData($data);
    }

    /**
     * @Then I should see the product :productName in the list
     * @Then the product :productName should appear in the store
     * @Then the product :productName should be in the shop
     * @Then this product should still be named :productName
     */
    public function theProductShouldAppearInTheShop(string $productName): void
    {
        $response = $this->client->index();

        Assert::true(
            $this->responseChecker->hasItemWithTranslation($response, 'en_US', 'name', $productName)
        );
    }

    /**
     * @When I remove its name from :localeCode translation
     */
    public function iRemoveItsNameFromTranslation(string $localeCode): void
    {
        $this->client->updateRequestData([
            'translations' => [
                $localeCode => [
                    'name' => '',
                    'locale' => $localeCode,
                ],
            ],
        ]);
    }

    /**
     * @Then I should be notified that it has been successfully created
     */
    public function iShouldBeNotifiedThatItHasBeenSuccessfullyCreated(): void
    {
        $res = $this->client->getLastResponse();
        Assert::true($this->responseChecker->isCreationSuccessful($this->client->getLastResponse()));
    }

    /**
     * @Then I should be notified that it has been successfully edited
     */
    public function iShouldBeNotifiedThatItHasBeenSuccessfullyEdited(): void
    {
        Assert::true(
            $this->responseChecker->isUpdateSuccessful($this->client->getLastResponse()),
            'Product could not be edited'
        );
    }

    /**
     * @Then I should be notified that this product is in use and cannot be deleted
     */
    public function iShouldBeNotifiedThatThisProductIsInUseAndCannotBeDeleted(): void
    {
        Assert::false(
            $this->responseChecker->isDeletionSuccessful($this->client->getLastResponse()),
            'Product can be deleted, but it should not'
        );
    }

    /**
     * @Then I should be notified that it has been successfully deleted
     */
    public function iShouldBeNotifiedThatItHasBeenSuccessfullyDeleted(): void
    {
        Assert::true(
            $this->responseChecker->isDeletionSuccessful($this->client->getLastResponse()),
            'Product still exists, but it should not'
        );
    }

    /**
     * @Then /^I should be notified that (code|name) is required$/
     */
    public function iShouldBeNotifiedThatIsRequired(string $element): void
    {
        Assert::contains(
            $this->responseChecker->getError($this->client->getLastResponse()),
            sprintf('Please enter product %s.', $element)
        );
    }

    /**
     * @Then I should be notified that code has to be unique
     */
    public function iShouldBeNotifiedThatCodeHasToBeUnique(): void
    {
        Assert::contains(
            $this->responseChecker->getError($this->client->getLastResponse()),
            'Product code must be unique.'
        );
    }

    /**
     * @Then I should see :count products in the list
     */
    public function iShouldSeeProductsInTheList(int $count): void
    {
        Assert::count($this->responseChecker->getCollection($this->client->getLastResponse()), $count);
    }

    /**
     * @Then I should see a product with :field :value
     */
    public function iShouldSeeProductWith(string $field, string $value): void
    {
        Assert::true(
            $this->hasProductWithFieldValue($this->client->getLastResponse(), $field, $value),
            sprintf('Product has not %s with %s', $field, $value)
        );
    }

    /**
     * @Then I should not see any product with :field :value
     */
    public function iShouldNotSeeAnyProductWith(string $field, string $value): void
    {
        Assert::false(
            $this
                ->responseChecker
                ->hasItemWithTranslation($this->client->getLastResponse(), 'en_US', $field, $value),
            sprintf('Product with %s set as %s still exists, but it should not', $field, $value)
        );
    }

    /**
     * @Then I should not be able to edit its code
     */
    public function iShouldNotBeAbleToEditItsCode(): void
    {
        $this->client->addRequestData('code', '_NEW');
        $this->client->update();
        $this->client->index();

        Assert::false(
            $this->responseChecker->hasItemOnPositionWithValue(
                $this->client->getLastResponse(),
                0,
                'code',
                '/api/v2/admin/products/_NEW'
            ),
            sprintf('It was possible to change %s', '_NEW')
        );
    }

    /**
     * @Then /^(this product) main (taxon should be "[^"]+")$/
     * @Then main taxon of product :product should be :taxon
     */
    public function thisProductMainTaxonShouldBe(ProductInterface $product, TaxonInterface $taxon): void
    {
        $response = $this->client->show($product->getCode());

        $mainTaxon = $this->responseChecker->getValue($response, 'mainTaxon');

        Assert::same($mainTaxon, $this->iriConverter->getIriFromItem($taxon));
    }

    /**
     * @Then /^(this product) name should be "([^"]+)"$/
     */
    public function thisProductNameShouldBe(ProductInterface $product, string $name): void
    {
        $response = $this->client->show($product->getCode());

        Assert::true(
            $this->responseChecker->hasTranslation($response, 'en_US', 'name', $name),
            sprintf('Product\'s name %s does not exist', $name)
        );
    }

    /**
     * @Then /^(this product) should not exist in the product catalog$/
     */
    public function productShouldNotExist(ProductInterface $product): void
    {
        $response = $this->client->index();

        Assert::false(
            $this->responseChecker->hasItemWithValue($response, 'code', $product->getCode()),
            sprintf('Product with name %s still exists, but it should not', $product->getName())
        );
    }

    /**
     * @Then /^(this product) should have (?:a|an) ("[^"]+" option)$/
     */
    public function thisProductShouldHaveOption(ProductInterface $product, ProductOptionInterface $productOption): void
    {
        $response = $this->client->show($product->getCode());

        $productFromResponse = $this->responseChecker->getResponseContent($response);

        Assert::true(
            in_array($this->iriConverter->getIriFromItem($productOption), $productFromResponse['options'], true),
            sprintf('Product with option %s does not exist', $productOption->getName())
        );
    }

    /**
     * @Then the first product on the list should have :field :value
     */
    public function theFirstProductOnTheListShouldHave(string $field, string $value): void
    {
        $products = $this->responseChecker->getCollection($this->client->getLastResponse());

        Assert::same($this->getFieldValueOfFirstProduct($products[0], $field), $value);
    }

    /**
     * @Then /^the slug of the ("[^"]+" product) should(?:| still) be "([^"]+)"$/
     * @Then /^the slug of the ("[^"]+" product) should(?:| still) be "([^"]+)" (in the "[^"]+" locale)$/
     */
    public function productSlugShouldBe(ProductInterface $product, string $slug, $localeCode = 'en_US'): void
    {
        $response = $this->client->show($product->getCode());

        Assert::true(
            $this->responseChecker->hasTranslation($response, $localeCode, 'slug', $slug),
            sprintf('Product\'s slug %s does not exist', $slug)
        );
    }

    /**
     * @Then /^there should be no reviews of (this product)$/
     */
    public function thereAreNoProductReviews(ProductInterface $product): void
    {
        $response = $this->productReviewsClient->index();

        Assert::isEmpty(
            $this->responseChecker->getCollectionItemsWithValue(
                $response,
                'reviewSubject',
                $this->iriConverter->getIriFromItem($product)
            ),
            'Should be no reviews, but some exist'
        );
    }

    /**
     * @Then /^(this product) should still exist in the product catalog$/
     */
    public function productShouldExistInTheProductCatalog(ProductInterface $product): void
    {
        $response = $this->client->index();
        $code = $product->getCode();

        Assert::true(
            $this->responseChecker->hasItemWithValue($response, 'code', $code),
            sprintf('Product with code %s does not exist', $code)
        );
    }

    /**
     * @Then /^the (product "[^"]+") should still have an accessible image$/
     */
    public function productShouldStillHaveAnAccessibleImage(ProductInterface $product): void
    {
        $response = $this->client->show($product->getCode());

        Assert::true($this->hasProductImage($response, $product), 'Image does not exists');
    }

    /**
     * @Then /^product with (name|code) "([^"]+)" should not be added$/
     */
    public function productWithNameShouldNotBeAdded(string $field, string $value): void
    {
        Assert::false($this->hasProductWithFieldValue($this->client->index(), $field, $value));
    }

    private function getAdminLocaleCode(): string
    {
        /** @var AdminUserInterface $adminUser */
        $adminUser = $this->sharedStorage->get('administrator');

        $response = $this->adminUsersClient->show((string) $adminUser->getId());

        return $this->responseChecker->getValue($response, 'localeCode');
    }

    private function getFieldValueOfFirstProduct(array $product, string $field): ?string
    {
        if ($field === 'code') {
            return $product['code'];
        }

        if ($field === 'name') {
            return $product['translations'][$this->getAdminLocaleCode()]['name'];
        }

        return null;
    }

    private function hasProductImage(Response $response, ProductInterface $product): bool
    {
        $productFromResponse = $this->responseChecker->getResponseContent($response);

        return
            isset($productFromResponse['images'][0]) &&
            str_contains($productFromResponse['images'][0]['path'], $product->getImages()->first()->getPath())
        ;
    }

    private function hasProductWithFieldValue(Response $response, string $field, string $value): bool
    {
        if ($field === 'code') {
            return $this->responseChecker->hasItemWithValue($response, $field, $value);
        }

        if ($field === 'name') {
            return $this->responseChecker->hasItemWithTranslation($response, $this->getAdminLocaleCode(), $field, $value);
        }

        return false;
    }
}


text:
<?php
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
$a = ucwords($person->firstname);
$b = ucwords($person->lastname);
$this->title = "Update $a $b's information";
$this->params['breadcrumbs'][] = ['label' => "$a $b", 'url' => '/persons/web/person/' . $person->id];
$this->params['breadcrumbs'][] = ['label' => 'Update'];
?>

    <?php $form = ActiveForm::begin(); ?>

        First Name:
        <input class="form-control" type="text" name="firstname" id="firstname" placeholder="Jane" required value="<?= ucwords($person->firstname) ?>">

        Last Name:
        <input class="form-control" type="text" name="lastname" id="lastname" placeholder="Doe" required value="<?= ucwords($person->lastname) ?>">

        Date of Birth:
        <input class="form-control" type="text" name="dob" id="dob" placeholder="mm/dd/yy" required value="<?= date('m\/d\/Y', strtotime($person->dob)) ?>">

        Zip Code:
        <input class="form-control" type="text" name="zip" id="zip" placeholder="12345" maxlength="5" required value="<?= $person->zip ?>">

        <button type="submit" class="btn btn-primary">Submit</button>
        Cancel

    <?php $form::end(); ?>

redpajama_set_name: RedPajamaGithub


text:
// Code generated by protoc-gen-go.
// source: simple-service.proto
// DO NOT EDIT!

/*
Package foo_service is a generated protocol buffer package.

It is generated from these files:
	simple-service.proto

It has these top-level messages:
	HelloRequest
	HelloResponse
	CountToRequest
	CountToResponse
	MessageRequest
	Message
*/
package foo_service

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/AmandaCameron/protoc-gen-gokit/protobuf/google/api"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

type HelloRequest struct {
	Who string `protobuf:"bytes,1,opt,name=who" json:"who,omitempty"`
}

func (m *HelloRequest) Reset()                    { *m = HelloRequest{} }
func (m *HelloRequest) String() string            { return proto.CompactTextString(m) }
func (*HelloRequest) ProtoMessage()               {}
func (*HelloRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

type HelloResponse struct {
	Response string `protobuf:"bytes,1,opt,name=response" json:"response,omitempty"`
}

func (m *HelloResponse) Reset()                    { *m = HelloResponse{} }
func (m *HelloResponse) String() string            { return proto.CompactTextString(m) }
func (*HelloResponse) ProtoMessage()               {}
func (*HelloResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }

type CountToRequest struct {
	Target int32 `protobuf:"varint,1,opt,name=target" json:"target,omitempty"`
}

func (m *CountToRequest) Reset()                    { *m = CountToRequest{} }
func (m *CountToRequest) String() string            { return proto.CompactTextString(m) }
func (*CountToRequest) ProtoMessage()               {}
func (*CountToRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }

type CountToResponse struct {
	Response string `protobuf:"bytes,1,opt,name=response" json:"response,omitempty"`
}

func (m *CountToResponse) Reset()                    { *m = CountToResponse{} }
func (m *CountToResponse) String() string            { return proto.CompactTextString(m) }
func (*CountToResponse) ProtoMessage()               {}
func (*CountToResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }

type MessageRequest struct {
	MessageBody *Message `protobuf:"bytes,1,opt,name=messageBody" json:"messageBody,omitempty"`
}

func (m *MessageRequest) Reset()                    { *m = MessageRequest{} }
func (m *MessageRequest) String() string            { return proto.CompactTextString(m) }
func (*MessageRequest) ProtoMessage()               {}
func (*MessageRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }

func (m *MessageRequest) GetMessageBody() *Message {
	if m != nil {
		return m.MessageBody
	}
	return nil
}

type Message struct {
	Hello string `protobuf:"bytes,1,opt,name=hello" json:"hello,omitempty"`
	World string `protobuf:"bytes,2,opt,name=world" json:"world,omitempty"`
}

func (m *Message) Reset()                    { *m = Message{} }
func (m *Message) String() string            { return proto.CompactTextString(m) }
func (*Message) ProtoMessage()               {}
func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }

func init() {
	proto.RegisterType((*HelloRequest)(nil), "example.foo_service.HelloRequest")
	proto.RegisterType((*HelloResponse)(nil), "example.foo_service.HelloResponse")
	proto.RegisterType((*CountToRequest)(nil), "example.foo_service.CountToRequest")
	proto.RegisterType((*CountToResponse)(nil), "example.foo_service.CountToResponse")
	proto.RegisterType((*MessageRequest)(nil), "example.foo_service.MessageRequest")
	proto.RegisterType((*Message)(nil), "example.foo_service.Message")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion3

// Client API for FooService service

type FooServiceClient interface {
	SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error)
	PostHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error)
	PostMessage(ctx context.Context, in *MessageRequest, opts ...grpc.CallOption) (*Message, error)
	CountTo(ctx context.Context, in *CountToRequest, opts ...grpc.CallOption) (*CountToResponse, error)
}

type fooServiceClient struct {
	cc *grpc.ClientConn
}

func NewFooServiceClient(cc *grpc.ClientConn) FooServiceClient {
	return &fooServiceClient{cc}
}

func (c *fooServiceClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error) {
	out := new(HelloResponse)
	err := grpc.Invoke(ctx, "/example.foo_service.FooService/SayHello", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *fooServiceClient) PostHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloResponse, error) {
	out := new(HelloResponse)
	err := grpc.Invoke(ctx, "/example.foo_service.FooService/PostHello", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *fooServiceClient) PostMessage(ctx context.Context, in *MessageRequest, opts ...grpc.CallOption) (*Message, error) {
	out := new(Message)
	err := grpc.Invoke(ctx, "/example.foo_service.FooService/PostMessage", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *fooServiceClient) CountTo(ctx context.Context, in *CountToRequest, opts ...grpc.CallOption) (*CountToResponse, error) {
	out := new(CountToResponse)
	err := grpc.Invoke(ctx, "/example.foo_service.FooService/CountTo", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for FooService service

type FooServiceServer interface {
	SayHello(context.Context, *HelloRequest) (*HelloResponse, error)
	PostHello(context.Context, *HelloRequest) (*HelloResponse, error)
	PostMessage(context.Context, *MessageRequest) (*Message, error)
	CountTo(context.Context, *CountToRequest) (*CountToResponse, error)
}

func RegisterFooServiceServer(s *grpc.Server, srv FooServiceServer) {
	s.RegisterService(&_FooService_serviceDesc, srv)
}

func _FooService_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(HelloRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FooServiceServer).SayHello(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/example.foo_service.FooService/SayHello",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FooServiceServer).SayHello(ctx, req.(*HelloRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _FooService_PostHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(HelloRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FooServiceServer).PostHello(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/example.foo_service.FooService/PostHello",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FooServiceServer).PostHello(ctx, req.(*HelloRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _FooService_PostMessage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(MessageRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FooServiceServer).PostMessage(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/example.foo_service.FooService/PostMessage",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FooServiceServer).PostMessage(ctx, req.(*MessageRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _FooService_CountTo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(CountToRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(FooServiceServer).CountTo(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/example.foo_service.FooService/CountTo",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(FooServiceServer).CountTo(ctx, req.(*CountToRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _FooService_serviceDesc = grpc.ServiceDesc{
	ServiceName: "example.foo_service.FooService",
	HandlerType: (*FooServiceServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "SayHello",
			Handler:    _FooService_SayHello_Handler,
		},
		{
			MethodName: "PostHello",
			Handler:    _FooService_PostHello_Handler,
		},
		{
			MethodName: "PostMessage",
			Handler:    _FooService_PostMessage_Handler,
		},
		{
			MethodName: "CountTo",
			Handler:    _FooService_CountTo_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: fileDescriptor0,
}

func init() { proto.RegisterFile("simple-service.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
	// 380 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xac, 0x93, 0xc1, 0x4e, 0xf2, 0x40,
	0x10, 0xc7, 0x03, 0x04, 0x28, 0xd3, 0x0f, 0x3e, 0xb3, 0x10, 0x25, 0x0d, 0x26, 0x58, 0x3d, 0x90,
	0x18, 0xda, 0x04, 0xe3, 0x85, 0x83, 0x07, 0x4c, 0x8c, 0x17, 0x13, 0x02, 0x9e, 0xbc, 0x98, 0x15,
	0xd6, 0xd2, 0xa4, 0x74, 0x6a, 0x77, 0x11, 0x89, 0xf1, 0xe2, 0x2b, 0xf8, 0x38, 0x3e, 0x86, 0xaf,
	0xe0, 0x83, 0x98, 0xee, 0x2e, 0xa4, 0x26, 0xd8, 0x78, 0xf0, 0xb6, 0x33, 0xfb, 0x9f, 0xf9, 0x75,
	0xfe, 0x3b, 0x85, 0x06, 0xf7, 0xe7, 0x51, 0xc0, 0xba, 0x9c, 0xc5, 0x8f, 0xfe, 0x84, 0x39, 0x51,
	0x8c, 0x02, 0x49, 0x9d, 0x3d, 0xd1, 0x24, 0xed, 0xdc, 0x23, 0xde, 0xea, 0x2b, 0xab, 0xe5, 0x21,
	0x7a, 0x01, 0x73, 0x69, 0xe4, 0xbb, 0x34, 0x0c, 0x51, 0x50, 0xe1, 0x63, 0xc8, 0x55, 0x89, 0xdd,
	0x86, 0x7f, 0x97, 0x2c, 0x08, 0x70, 0xc4, 0x1e, 0x16, 0x8c, 0x0b, 0xb2, 0x03, 0x85, 0xe5, 0x0c,
	0x9b, 0xb9, 0x76, 0xae, 0x53, 0x19, 0x25, 0x47, 0xfb, 0x18, 0xaa, 0x5a, 0xc1, 0x23, 0x0c, 0x39,
	0x23, 0x16, 0x18, 0xb1, 0x3e, 0x6b, 0xdd, 0x26, 0xb6, 0x3b, 0x50, 0x3b, 0xc7, 0x45, 0x28, 0xae,
	0x37, 0x0d, 0x77, 0xa1, 0x24, 0x68, 0xec, 0x31, 0x21, 0xb5, 0xc5, 0x91, 0x8e, 0xec, 0x2e, 0xfc,
	0xdf, 0x28, 0x7f, 0xd1, 0x78, 0x08, 0xb5, 0x2b, 0xc6, 0x39, 0xf5, 0xd8, 0xba, 0xf1, 0x19, 0x98,
	0x73, 0x95, 0x19, 0xe0, 0x74, 0x25, 0x0b, 0xcc, 0x5e, 0xcb, 0xd9, 0x62, 0x81, 0xb3, 0xae, 0x4c,
	0x17, 0xd8, 0xa7, 0x50, 0xd6, 0x79, 0xd2, 0x80, 0xe2, 0x2c, 0x19, 0x51, 0x53, 0x55, 0x90, 0x64,
	0x97, 0x18, 0x07, 0xd3, 0x66, 0x5e, 0x65, 0x65, 0xd0, 0x7b, 0x2f, 0x00, 0x5c, 0x20, 0x8e, 0x55,
	0x6b, 0x42, 0xc1, 0x18, 0xd3, 0x95, 0x34, 0x88, 0x1c, 0x6c, 0x85, 0xa7, 0xed, 0xb5, 0xec, 0x2c,
	0x89, 0x1e, 0xb5, 0xf6, 0xfa, 0xf1, 0xf9, 0x96, 0x37, 0x48, 0xc9, 0x55, 0xdf, 0xe1, 0x41, 0x65,
	0x88, 0x5c, 0xfc, 0x29, 0xa3, 0x2e, 0x19, 0x55, 0x4b, 0x33, 0xfa, 0xc9, 0x4b, 0x13, 0x04, 0x33,
	0x01, 0xad, 0x5d, 0x39, 0xcc, 0xf4, 0x52, 0xc3, 0x32, 0x0d, 0xb7, 0xf7, 0x25, 0x66, 0xcf, 0x32,
	0x5c, 0xed, 0x7c, 0x3f, 0xfd, 0x04, 0x24, 0x82, 0xb2, 0xde, 0x81, 0x1f, 0x60, 0xdf, 0x77, 0xc9,
	0x3a, 0xca, 0x16, 0xe9, 0xd9, 0x2c, 0x09, 0x6d, 0x10, 0xe2, 0x4e, 0x92, 0x1b, 0x57, 0xa0, 0xfb,
	0xac, 0x96, 0xee, 0x65, 0x50, 0xbd, 0x31, 0x53, 0xa5, 0x77, 0x25, 0xf9, 0x13, 0x9c, 0x7c, 0x05,
	0x00, 0x00, 0xff, 0xff, 0xf9, 0x28, 0xc3, 0x29, 0x4f, 0x03, 0x00, 0x00,
}


text:
set -eu

cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/../../.."

export GOPATH=$PWD/../../../..
export PATH="$GOPATH/bin:$PATH"

./bin/install-tools

ginkgo -r -cover -covermode count

gover
GIT_BRANCH="$( git name-rev --name-only HEAD )" goveralls \
  -coverprofile=gover.coverprofile \
  -service concourse \
  -repotoken "$COVERALLS_TOKEN"


text:
package ru.stqa.pft.addressbook.tests;

import org.openqa.selenium.remote.BrowserType;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;

import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class TestBase {

	protected static final ApplicationManager app = new ApplicationManager(System.getProperty("browser", BrowserType.FIREFOX));

	public static final String dataProvider = app.getProperties().getProperty("provider.format");
	private static final int asd = 917;
	@BeforeSuite
	public void setUp() throws Exception {
		app.init();
	}

	@AfterSuite
	public void tearDown() {
		app.stop();
	}

	public static String dataProvider(){
		return app.getProperties().getProperty("provider.format");
	}

	public void verifyGroupListInUI(){
		if(Boolean.getBoolean("verifyUI")){
			Groups dbGroups = app.db().groups();
			Groups uiGroups = app.group().all();
			assertThat(uiGroups, equalTo(dbGroups.stream()
						.map((g)->new GroupData().withId(g.getId()).withName(g.getName()))
						.collect(Collectors.toSet())));
		}
	}
}


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

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

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

    /**
     *

     * A list of DatasetEntry objects.
     *

     */
    private java.util.List<DatasetEntry> entries;
    /**
     *

     * The time when the request was made.
     *

     */
    private java.util.Date timestamp;
    /**
     *

     * The status of the dataset content.
     *

     */
    private DatasetContentStatus status;

    /**
     *

     * A list of DatasetEntry objects.
     *

     *
     * @return A list of DatasetEntry objects.
     */

    public java.util.List<DatasetEntry> getEntries() {
        return entries;
    }

    /**
     *

     * A list of DatasetEntry objects.
     *

     *
     * @param entries
     *        A list of DatasetEntry objects.
     */

    public void setEntries(java.util.Collection<DatasetEntry> entries) {
        if (entries == null) {
            this.entries = null;
            return;
        }

        this.entries = new java.util.ArrayList<DatasetEntry>(entries);
    }

    /**
     *

     * A list of DatasetEntry objects.
     *

     *

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

     *
     * @param entries
     *        A list of DatasetEntry objects.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetDatasetContentResult withEntries(DatasetEntry... entries) {
        if (this.entries == null) {
            setEntries(new java.util.ArrayList<DatasetEntry>(entries.length));
        }
        for (DatasetEntry ele : entries) {
            this.entries.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of DatasetEntry objects.
     *

     *
     * @param entries
     *        A list of DatasetEntry objects.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetDatasetContentResult withEntries(java.util.Collection<DatasetEntry> entries) {
        setEntries(entries);
        return this;
    }

    /**
     *

     * The time when the request was made.
     *

     *
     * @param timestamp
     *        The time when the request was made.
     */

    public void setTimestamp(java.util.Date timestamp) {
        this.timestamp = timestamp;
    }

    /**
     *

     * The time when the request was made.
     *

     *
     * @return The time when the request was made.
     */

    public java.util.Date getTimestamp() {
        return this.timestamp;
    }

    /**
     *

     * The time when the request was made.
     *

     *
     * @param timestamp
     *        The time when the request was made.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetDatasetContentResult withTimestamp(java.util.Date timestamp) {
        setTimestamp(timestamp);
        return this;
    }

    /**
     *

     * The status of the dataset content.
     *

     *
     * @param status
     *        The status of the dataset content.
     */

    public void setStatus(DatasetContentStatus status) {
        this.status = status;
    }

    /**
     *

     * The status of the dataset content.
     *

     *
     * @return The status of the dataset content.
     */

    public DatasetContentStatus getStatus() {
        return this.status;
    }

    /**
     *

     * The status of the dataset content.
     *

     *
     * @param status
     *        The status of the dataset content.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetDatasetContentResult withStatus(DatasetContentStatus status) {
        setStatus(status);
        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 (getEntries() != null)
            sb.append("Entries: ").append(getEntries()).append(",");
        if (getTimestamp() != null)
            sb.append("Timestamp: ").append(getTimestamp()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof GetDatasetContentResult == false)
            return false;
        GetDatasetContentResult other = (GetDatasetContentResult) obj;
        if (other.getEntries() == null ^ this.getEntries() == null)
            return false;
        if (other.getEntries() != null && other.getEntries().equals(this.getEntries()) == false)
            return false;
        if (other.getTimestamp() == null ^ this.getTimestamp() == null)
            return false;
        if (other.getTimestamp() != null && other.getTimestamp().equals(this.getTimestamp()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getEntries() == null) ? 0 : getEntries().hashCode());
        hashCode = prime * hashCode + ((getTimestamp() == null) ? 0 : getTimestamp().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        return hashCode;
    }

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

}


text:
"""
    {{ project_name }}.libs.common.middleware
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    This module contains middleware that is common to {{ project_name }}

    :copyright: (c) 2015
"""

class PjaxMiddleware(object):
    """
    If the request was made via PJAX, add the original request path to the
    response.
    """
    def process_response(self, request, response):
        if 'HTTP_X_PJAX' in request.META:
            response['X-PJAX-URL'] = request.path
        return response


text:
import Service = require("./classes/Service");
import Plugin = require("./classes/Plugin");
import PluginManager = require("./classes/PluginManager");
import Utils = require("./classes/Utils");
import YamlParser = require("./classes/YamlParser");
import AwsProvider = require("./plugins/aws/provider/awsProvider");

declare namespace Serverless {
    interface Options {
        function?: string;
        watch?: boolean;
        extraServicePath?: string;
        stage: string | null;
        region: string | null;
        noDeploy?: boolean;
    }

    interface Config {
        servicePath: string;
    }

    interface FunctionDefinition {
        name: string;
        package: Package;
        runtime?: string;
        handler: string;
        timeout?: number;
        memorySize?: number;
        environment?: { [ name: string ]: string };
    }

    interface Event {
        eventName: string;
    }

    interface Package {
        include: string[];
        exclude: string[];
        artifact?: string;
        individually?: boolean;
    }
}

declare class Serverless {
    constructor(config?: {});

    init(): Promise<any>;
    run(): Promise<any>;

    setProvider(name: string, provider: AwsProvider): null;
    getProvider(name: string): AwsProvider;

    getVersion(): string;

    cli: {
        log(message: string): null;
    };

    providers: {};
    utils: Utils;
    variables: {};
    yamlParser: YamlParser;
    pluginManager: PluginManager;

    config: Serverless.Config;
    serverlessDirPath: string;

    service: Service;
    version: string;
}

export = Serverless;


text:
package edu.upc.eetac.dsa.beeter.entity;

/**
 * Created by Enric on 26/03/2016.
 */
public enum Role {
    registered
}


text:
class PackageAddonType < ActiveRecord::Base
  has_many :invoice_addon_line_items

  validates :name, presence: true
  validates :price, :total_spots, presence: true, numericality: {greater_than: 0}

  def remaining
    total_spots - (invoice_addon_line_items.map &:quantity).sum
  end
end


text:
<?php

/*
* <auto-generated>
*     This code was generated by a Codezu.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

namespace Mozu\Api\Contracts\CommerceRuntime\Fulfillment;

/**
*	Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping.
*/
class FulfillmentAction
{
	/**
	*The name of the fulfillment action to perform for the purchased product. Options include "Ship" or "PickUp" (in-store pick-up).
	*/
	public $actionName;

	/**
	*The digital package ID identifies the package to update on the order.
	*/
	public $digitalPackageIds;

	/**
	*Array list of unique IDs of packages in a shipment planned for or finished a shipping fulfillment action.
	*/
	public $packageIds;

	/**
	*Array list of in-store pickups for which to perform the fulfillment action.
	*/
	public $pickupIds;

}

?>


text:
using Nancy.Metadata.Module;
using Nancy.Swagger;

namespace OmniSharp.Rename.Metadata
{
    public class RenameMetadataModule : MetadataModule<SwaggerRouteData>
    {
        public RenameMetadataModule()
        {
            Describe["Rename"] = desc => desc.AsSwagger(builder => builder
                .ResourcePath("/rename")
                .BodyParam<RenameRequest>()
                .Response(200)
                .Model<RenameResponse>());
        }
    }
}


text:
import datetime
import os
import os.path
import requests
import json
from bs4 import BeautifulSoup
import arrow
from peewee import *
from models import Aufmacher, Author, Image, TweetJob
from config import db
import untangle

DOWNLOAD_URL = "http://www.zeit.de"

def get_article_data(unique_id):
    obj = untangle.parse(unique_id)

    try:
        article = obj.article
    except AttributeError:
        try:
            article = obj.link
        except AttributeError:
            try:
                article = obj.gallery
            except AttributeError:
                article = obj.video

    head = article.head
    body = article.body

    # author_unique_id = head.author["href"]
    # author_name = head.author.display_name.cdata.strip()
    # author_image_id = head.author.image["base-id"].strip()
    # author_image_copyright = head.author.image.copyright.cdata.strip()

    supertitle = body.supertitle.cdata.strip()
    title = body.title
    if isinstance(title, list):
        title = title[0]
    title = title.cdata.strip()
    subtitle = body.subtitle.cdata.strip()

    try:
        image_id = head.image["base-id"].strip()
        image_copyright = head.image.copyright.cdata.strip()
        image_caption = head.image.bu.cdata.strip()
    except AttributeError:
        image_id = None

    first_released = None
    for attribute in head.attribute:
        if attribute["name"] == "date_first_released":
            first_released = arrow.get(attribute.cdata).datetime

    # author = Author.get_or_create(
    #    unique_id=author_unique_id,
    #    defaults={
    #        "name": author_name
    #    })
    #
    # if author[1]:
    #    author_image = Image.get_or_create(
    #        unique_id=author_image_id,
    #        defaults={
    #            "copyright": author_image_copyright
    #        })
    #    author[0].image = author_image[0]
    #    author[0].save()

    article_image = None
    if image_id and len(image_id):
        article_image = Image.get_or_create(
            unique_id=image_id,
            defaults={"copyright": image_copyright, "caption": image_caption},
        )[0]

    aufmacher = Aufmacher.create(
        unique_id=unique_id,
        supertitle=supertitle,
        title=title,
        subtitle=subtitle,
        first_released=first_released,
        # author=author[0],
        image=article_image,
    )

    TweetJob.create(aufmacher=aufmacher)

    return aufmacher

def scrape():
    r = requests.get(DOWNLOAD_URL)
    soup = BeautifulSoup(r.text, "html.parser")

    teaser = soup.select(".main article")

    if len(teaser):
        teaser = teaser[0]
    else:
        return

    unique_id = teaser["data-unique-id"].strip().replace("https", "http")

    db.connect()
    db.create_tables([Image, Author, Aufmacher, TweetJob], safe=True)

    possible_duplicate = Aufmacher.select().where(Aufmacher.unique_id == unique_id)
    if not len(possible_duplicate):
        get_article_data(unique_id)

    db.close()

if __name__ == "__main__":
    scrape()


text:
## particles.js

### A lightweight JavaScript library for creating particles.

Load particles.js and configure the particles:

**index.html**
```html
<div id="particles-js"></div>

<script src="particles.js"></script>
```

**app.js**
```javascript
/* particlesJS('dom-id', params);
/* @dom-id : set the html tag id [string, optional, default value : particles-js]
/* @params: set the params [object, optional, default values : check particles.js] */

/* config dom id (optional) + config particles params */
particlesJS('particles-js', {
  particles: {
    color: '#fff',
    shape: 'circle', // "circle", "edge" or "triangle"
    opacity: 1,
    size: 4,
    size_random: true,
    nb: 150,
    line_linked: {
      enable_auto: true,
      distance: 100,
      color: '#fff',
      opacity: 1,
      width: 1,
      condensed_mode: {
        enable: false,
        rotateX: 600,
        rotateY: 600
      }
    },
    anim: {
      enable: true,
      speed: 1
    }
  },
  interactivity: {
    enable: true,
    mouse: {
      distance: 250
    },
    detect_on: 'canvas', // "canvas" or "window"
    mode: 'grab',
    line_linked: {
      opacity: .5
    },
    events: {
      onclick: {
        enable: true,
        mode: 'push', // "push" or "remove" (particles)
        nb: 4
      }
    }
  },
  /* Retina Display Support */
  retina_detect: true
});
```

### ***Live Demo***
CodePen demo

GitHub demo


text:
package com.freud.dcom.utgard.cases;

import static com.freud.opc.utgard.BaseConfiguration.CONFIG_CLSID;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_DOMAIN;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_HOST;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_PASSWORD;
import static com.freud.opc.utgard.BaseConfiguration.CONFIG_USERNAME;
import static com.freud.opc.utgard.BaseConfiguration.getEntryValue;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIClsid;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.openscada.opc.dcom.common.EventHandler;
import org.openscada.opc.dcom.common.KeyedResult;
import org.openscada.opc.dcom.common.KeyedResultSet;
import org.openscada.opc.dcom.common.Result;
import org.openscada.opc.dcom.common.ResultSet;
import org.openscada.opc.dcom.common.impl.OPCCommon;
import org.openscada.opc.dcom.da.OPCDATASOURCE;
import org.openscada.opc.dcom.da.OPCITEMDEF;
import org.openscada.opc.dcom.da.OPCITEMRESULT;
import org.openscada.opc.dcom.da.OPCITEMSTATE;
import org.openscada.opc.dcom.da.impl.OPCGroupStateMgt;
import org.openscada.opc.dcom.da.impl.OPCItemMgt;
import org.openscada.opc.dcom.da.impl.OPCServer;
import org.openscada.opc.dcom.da.impl.OPCSyncIO;

/**
 * 同步读取Item
 *
 * @author Freud
 *
 */
public class DCOMTest4 {

	public static void main(String[] args) throws Exception {
		JISystem.setAutoRegisteration(true);

		/**
		 * Session获取
		 */
		JISession _session = JISession.createSession(
				getEntryValue(CONFIG_DOMAIN), getEntryValue(CONFIG_USERNAME),
				getEntryValue(CONFIG_PASSWORD));

		final JIComServer comServer = new JIComServer(
				JIClsid.valueOf(getEntryValue(CONFIG_CLSID)),
				getEntryValue(CONFIG_HOST), _session);

		final IJIComObject serverObject = comServer.createInstance();

		OPCServer server = new OPCServer(serverObject);

		/**
		 * 添加一个Group的信息
		 */
		OPCGroupStateMgt group = server.addGroup("test", true, 100, 1234, 60,
				0.0f, 1033);

		testItems(server, group, new String[] { "Saw-toothed Waves.Int2",
				"Saw-toothed Waves.test2" });

		// clean up
		server.removeGroup(group, true);
	}

	private static void showError(final OPCCommon common, final int errorCode)
			throws JIException {
		System.out.println(String.format("Error (%X): '%s'", errorCode,
				common.getErrorString(errorCode, 1033)));
	}

	private static void showError(final OPCServer server, final int errorCode)
			throws JIException {
		showError(server.getCommon(), errorCode);
	}

	private static boolean dumpOPCITEMRESULT(
			final KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result) {
		int failed = 0;
		for (final KeyedResult<OPCITEMDEF, OPCITEMRESULT> resultEntry : result) {
			System.out.println("==================================");
			System.out.println(String.format("Item: '%s' ", resultEntry
					.getKey().getItemID()));

			System.out.println(String.format("Error Code: %08x",
					resultEntry.getErrorCode()));
			if (!resultEntry.isFailed()) {
				System.out.println(String.format("Server Handle: %08X",
						resultEntry.getValue().getServerHandle()));
				System.out.println(String.format("Data Type: %d", resultEntry
						.getValue().getCanonicalDataType()));
				System.out.println(String.format("Access Rights: %d",
						resultEntry.getValue().getAccessRights()));
				System.out.println(String.format("Reserved: %d", resultEntry
						.getValue().getReserved()));
			} else {
				failed++;
			}
		}
		return failed == 0;
	}

	private static void testItems(final OPCServer server,
			final OPCGroupStateMgt group, final String... itemIDs)
			throws IllegalArgumentException, UnknownHostException, JIException {

		final OPCItemMgt itemManagement = group.getItemManagement();
		final List<OPCITEMDEF> items = new ArrayList<OPCITEMDEF>(itemIDs.length);
		for (final String id : itemIDs) {
			final OPCITEMDEF item = new OPCITEMDEF();
			item.setItemID(id);
			item.setClientHandle(new Random().nextInt());
			items.add(item);
		}

		final OPCITEMDEF[] itemArray = items.toArray(new OPCITEMDEF[0]);

		System.out.println("Validate");
		KeyedResultSet<OPCITEMDEF, OPCITEMRESULT> result = itemManagement
				.validate(itemArray);
		if (!dumpOPCITEMRESULT(result)) {
			return;
		}

		// now add them to the group
		System.out.println("Add");
		result = itemManagement.add(itemArray);
		if (!dumpOPCITEMRESULT(result)) {
			return;
		}

		// get the server handle array
		final Integer[] serverHandles = new Integer[itemArray.length];
		for (int i = 0; i < itemArray.length; i++) {
			serverHandles[i] = new Integer(result.get(i).getValue()
					.getServerHandle());
		}

		// set them active
		System.out.println("Activate");
		final ResultSet<Integer> resultSet = itemManagement.setActiveState(
				true, serverHandles);
		for (final Result<Integer> resultEntry : resultSet) {
			System.out.println(String.format("Item: %08X, Error: %08X",
					resultEntry.getValue(), resultEntry.getErrorCode()));
		}

		// set client handles
		System.out.println("Set client handles");
		final Integer[] clientHandles = new Integer[serverHandles.length];
		for (int i = 0; i < serverHandles.length; i++) {
			clientHandles[i] = i;
		}
		itemManagement.setClientHandles(serverHandles, clientHandles);

		System.out.println("Create async IO 2.0 object");
		// OPCAsyncIO2 asyncIO2 = group.getAsyncIO2 ();
		// connect handler

		System.out.println("attach");
		final EventHandler eventHandler = group.attach(new DumpDataCallback());

		// sleep
		try {
			System.out.println("Waiting...");
			Thread.sleep(10 * 1000);
		} catch (final InterruptedException e) {
			e.printStackTrace();
		}

		eventHandler.detach();

		// sync IO - read
		final OPCSyncIO syncIO = group.getSyncIO();
		// OPCAsyncIO2 asyncIO2 = group.getAsyncIO2 ();
		/*
		 * System.out.println ( "attach..enable" ); asyncIO2.setEnable ( true );
		 * System.out.println ( "attach..refresh" ); asyncIO2.refresh (
		 * (short)1, 1 );
		 */

		final KeyedResultSet<Integer, OPCITEMSTATE> itemState = syncIO.read(
				OPCDATASOURCE.OPC_DS_DEVICE, serverHandles);
		for (final KeyedResult<Integer, OPCITEMSTATE> itemStateEntry : itemState) {
			final int errorCode = itemStateEntry.getErrorCode();
			System.out
					.println(String
							.format("Server ID: %08X, Value: %s, Timestamp: %d/%d (%Tc), Quality: %d, Error: %08X",
									itemStateEntry.getKey(), itemStateEntry
											.getValue().getValue(),
									itemStateEntry.getValue().getTimestamp()
											.getHigh(),
									itemStateEntry.getValue().getTimestamp()
											.getLow(), itemStateEntry
											.getValue().getTimestamp()
											.asCalendar(), itemStateEntry
											.getValue().getQuality(), errorCode));
			if (errorCode != 0) {
				showError(server, errorCode);
			}
		}

		// set them inactive
		System.out.println("In-Active");
		itemManagement.setActiveState(false, serverHandles);

		// finally remove them again
		System.out.println("Remove");
		itemManagement.remove(serverHandles);
	}

}


text:
namespace extensions {

namespace {

void SuccessCallback(bool* did_respond,
                     ExtensionFunction::ResponseType type,
                     const base::ListValue& results,
                     const std::string& error,
                     functions::HistogramValue histogram_value) {
  EXPECT_EQ(ExtensionFunction::ResponseType::SUCCEEDED, type);
  *did_respond = true;
}

void FailCallback(bool* did_respond,
                  ExtensionFunction::ResponseType type,
                  const base::ListValue& results,
                  const std::string& error,
                  functions::HistogramValue histogram_value) {
  EXPECT_EQ(ExtensionFunction::ResponseType::FAILED, type);
  *did_respond = true;
}

class ValidationFunction : public UIThreadExtensionFunction {
 public:
  explicit ValidationFunction(bool should_succeed)
      : should_succeed_(should_succeed), did_respond_(false) {
    set_response_callback(base::Bind(
        (should_succeed ? &SuccessCallback : &FailCallback), &did_respond_));
  }

  ResponseAction Run() override {
    EXPECT_TRUE(should_succeed_);
    return RespondNow(NoArguments());
  }

  bool did_respond() { return did_respond_; }

 private:
  ~ValidationFunction() override {}
  bool should_succeed_;
  bool did_respond_;
};
}  // namespace

using ChromeExtensionFunctionUnitTest = ExtensionServiceTestBase;

TEST_F(ChromeExtensionFunctionUnitTest, SimpleFunctionTest) {
  scoped_refptr<ValidationFunction> function(new ValidationFunction(true));
  function->RunWithValidation()->Execute();
  EXPECT_TRUE(function->did_respond());
}

TEST_F(ChromeExtensionFunctionUnitTest, BrowserShutdownValidationFunctionTest) {
  TestingBrowserProcess::GetGlobal()->SetShuttingDown(true);
  scoped_refptr<ValidationFunction> function(new ValidationFunction(false));
  function->RunWithValidation()->Execute();
  TestingBrowserProcess::GetGlobal()->SetShuttingDown(false);
  EXPECT_TRUE(function->did_respond());
}

}  // namespace extensions


text:
package org.teavm.jso.webaudio;

import org.teavm.jso.JSObject;
import org.teavm.jso.JSProperty;

public interface AudioListener extends JSObject {
    @JSProperty
    void setDopplerFactor(float value);

    @JSProperty
    float getDopplerFactor();

    @JSProperty
    void setSpeedOfSound(float value);

    @JSProperty
    float getSpeedOfSound();

    void setPosition(float x, float y, float z);

    void setOrientation(float x, float y, float z, float xUp, float yUp, float zUp);

    void setVelocity(float x, float y, float z);
}


text:
(function(angular) {
	'use strict';

	/**
	 * @namespace services
	 * @memberOf ngMaps
	 */
	angular.module('ngMaps.services', []);

})(window.angular);