text:
<?php
declare(strict_types=1);

use Shopware\Components\Cart\Struct\Price;
use Shopware\Models\Article\Detail;
use Shopware\Models\Customer\Customer;
use Shopware\Models\Customer\PaymentData;
use Shopware\Models\Dispatch\Dispatch;
use Shopware\Models\Dispatch\ShippingCost;
use Shopware\Models\Order\Order;
use Shopware\Models\Payment\Payment;
use Shopware\Models\Shop\Currency;
use Shopware\Models\Shop\Shop;
use Shopware\Models\Tax\Tax;
use SwagBackendOrder\Components\ConfirmationMail\ConfirmationMailCreator;
use SwagBackendOrder\Components\ConfirmationMail\ConfirmationMailRepository;
use SwagBackendOrder\Components\ConfirmationMail\NumberFormatterWrapper;
use SwagBackendOrder\Components\Order\Struct\PositionStruct as OrderPositionStruct;
use SwagBackendOrder\Components\Order\Validator\InvalidOrderException;
use SwagBackendOrder\Components\Order\Validator\Validators\ProductContext;
use SwagBackendOrder\Components\PriceCalculation\DiscountType;
use SwagBackendOrder\Components\PriceCalculation\Result\PriceResult;
use SwagBackendOrder\Components\PriceCalculation\Result\TotalPricesResult;
use SwagBackendOrder\Components\PriceCalculation\Struct\PositionStruct;
use SwagBackendOrder\Components\PriceCalculation\Struct\RequestStruct;
use SwagBackendOrder\Components\PriceCalculation\TaxCalculation;

/**
 * @phpstan-import-type PositionArray from RequestStruct
 *
 * @phpstan-type TaxArray list<array{taxRate: float, tax: float}>
 * @phpstan-type CalculateBasketResult array{totalWithoutTax: float, sum: float, total: float, shippingCosts: float, shippingCostsNet: float, shippingCostsTaxRate: float, taxSum: float, positions: PositionArray, dispatchTaxRate: float, proportionalTaxCalculation: bool, taxes: TaxArray}
 */
class Shopware_Controllers_Backend_SwagBackendOrder extends Shopware_Controllers_Backend_ExtJs
{
    /**
     * Return a list of customer on search or return a single customer on select.
     */
    public function getCustomerAction(): void
    {
        $repository = $this->get('swag_backend_order.customer_repository');

        if ($filter = $this->getListRequestParam()) {
            $result = $repository->getList($filter);

            $this->view->assign([
                'data' => $result,
                'total' => \count($result),
                'success' => true,
            ]);

            return;
        }

        $customerId = (int) $this->Request()->get('searchParam');
        $result = $repository->get($customerId);

        $this->view->assign([
            'data' => $result,
            'total' => \count($result),
            'success' => true,
        ]);
    }

    public function createOrderAction(): void
    {
        $modelManager = $this->get('models');

        $orderHydrator = $this->get('swag_backend_order.order.order_hydrator');

        $orderValidator = $this->get('swag_backend_order.order.order_validator');

        $orderStruct = $orderHydrator->hydrateFromRequest($this->Request());
        $violations = $orderValidator->validate($orderStruct);
        if ($violations->getMessages()) {
            $this->view->assign([
                'success' => false,
                'violations' => $violations->getMessages(),
            ]);

            return;
        }

        $modelManager->getConnection()->beginTransaction();
        try {
            // we need to fake a shop instance if we want to use the Articles Module
            $shopRepository = $this->get('models')->getRepository(Shop::class);
            $shop = $shopRepository->getActiveById($orderStruct->getLanguageShopId());

            if ($shop === null) {
                throw new RuntimeException('Shop not found');
            }

            $this->get('shopware.components.shop_registration_service')->registerResources($shop);

            $orderService = $this->get('swag_backend_order.order.service');
            $order = $orderService->create($orderStruct);

            $modelManager->getConnection()->commit();

            if ($orderStruct->getSendMail()) {
                $this->sendOrderConfirmationMail($order);
            }
        } catch (InvalidOrderException $e) {
            $modelManager->getConnection()->rollBack();

            $this->view->assign([
                'success' => false,
                'message' => $e->getMessage(),
            ]);

            return;
        } catch (\Exception $e) {
            $modelManager->getConnection()->rollBack();

            $this->view->assign([
                'success' => false,
                'message' => $e->getMessage(),
            ]);

            return;
        }

        $this->get('events')->notify('Shopware_Modules_Order_SaveOrder_OrderCreated', [
            'subject' => $this,
            'orderId' => $order->getId(),
            'orderNumber' => $order->getNumber(),
        ]);

        $orderService = $this->container->get('swag_backend_order.b2b_order_service');
        $orderService->createB2BOrder($order);

        $this->view->assign([
            'success' => true,
            'orderId' => $order->getId(),
            'ordernumber' => $order->getNumber(),
        ]);
    }

    public function getProductsAction(): void
    {
        $limit = (int) $this->request->getParam('limit', 10);
        $offset = (int) $this->request->getParam('start', 0);
        $search = (string) $this->request->getParam('query');
        $shopId = $this->getShopId();

        $productSearch = $this->container->get('swag_backend_order.product_search');
        $result = $productSearch->findProducts($search, $shopId, $limit, $offset);

        $this->view->assign(
            [
                'success' => true,
                'data' => $result,
                'total' => $productSearch->getLastResultTotalCount(),
            ]
        );
    }

    public function getProductAction(): void
    {
        $params = $this->request->getParams();
        $number = $this->request->getParam('ordernumber');

        $productSearch = $this->container->get('swag_backend_order.product_search');
        $product = $productSearch->getProduct($number, $params, $this->getShopId(), $this->getCustomerGroupKey());

        $this->view->assign([
            'data' => $product,
            'success' => true,
        ]);
    }

    public function getDiscountAction(): void
    {
        $type = (int) $this->Request()->getParam('type');
        $value = (float) $this->Request()->getParam('value');
        $productName = $this->Request()->getParam('name');
        $totalAmount = (float) $this->Request()->getParam('currentTotal');
        $taxRate = (float) $this->Request()->getParam('tax');

        if ($type === DiscountType::DISCOUNT_ABSOLUTE && $totalAmount < $value) {
            $this->view->assign(['success' => false]);

            return;
        }

        $result = [
            'articleName' => $productName,
            'articleNumber' => OrderPositionStruct::DISCOUNT_ORDER_NUMBER_PREFIX . $type,
            'articleId' => 0,
            'price' => $value * -1,
            'mode' => 4,
            'quantity' => 1,
            'inStock' => 1,
            'isDiscount' => true,
            'discountType' => $type,
            'total' => $value * -1,
            'taxRate' => $taxRate,
        ];

        $this->view->assign([
            'data' => $result,
            'success' => true,
        ]);
    }

    /**
     * gets all available payments for the backend order
     */
    public function getPaymentAction(): void
    {
        $paymentTranslator = $this->get('swag_backend_order.payment_translator');

        $builder = $this->get('models')->createQueryBuilder();
        $builder->select(['payment'])
            ->from(Payment::class, 'payment')
            ->orderBy('payment.active', 'DESC');

        $paymentMethods = $builder->getQuery()->getArrayResult();

        $languageId = $this->getBackendLanguage();

        foreach ($paymentMethods as &$paymentMethod) {
            $paymentMethod = $paymentTranslator->translate($paymentMethod, $languageId);
        }
        unset($paymentMethod);

        $total = \count($paymentMethods);

        $this->view->assign(
            [
                'data' => $paymentMethods,
                'total' => $total,
                'success' => true,
            ]
        );
    }

    /**
     * method which selects all shipping costs
     */
    public function getShippingCostsAction(): void
    {
        $dispatchTranslator = $this->get('swag_backend_order.shipping_translator');

        $builder = $this->get('models')->createQueryBuilder();

        $builder->select(['dispatch', 'shipping'])
            ->from(ShippingCost::class, 'shipping')
            ->innerJoin('shipping.dispatch', 'dispatch')
            ->groupBy('dispatch.id')
            ->orderBy('dispatch.position', 'ASC');
        $shippingCosts = $builder->getQuery()->getArrayResult();

        $languageId = $this->getBackendLanguage();

        foreach ($shippingCosts as &$shippingCost) {
            $shippingCost['dispatch'] = $dispatchTranslator->translate($shippingCost['dispatch'], $languageId);
        }
        unset($shippingCost);

        $total = \count($shippingCosts);

        $this->view->assign(
            [
                'data' => $shippingCosts,
                'total' => $total,
                'success' => true,
            ]
        );
    }

    public function getCurrenciesAction(): void
    {
        $repository = $this->get('models')->getRepository(Currency::class);

        $builder = $repository->createQueryBuilder('c');
        $builder->select(
            [
                'c.id as id',
                'c.name as name',
                'c.currency as currency',
                'c.symbol as symbol',
                'c.factor as factor',
                'c.default as default',
            ]
        );

        $query = $builder->getQuery();

        $total = $this->get('models')->getQueryCount($query);

        $data = $query->getArrayResult();

        $this->View()->assign(
            [
                'success' => true,
                'data' => $data,
                'total' => $total,
            ]
        );
    }

    /**
     * reads the plugin config and passes it to the ext js application
     */
    public function getPluginConfigAction(): void
    {
        $configReader = $this->get('shopware.plugin.config_reader');
        $pluginConfig = $configReader->getByPluginName('SwagBackendOrder');

        $desktopTypes = $pluginConfig['desktopTypes'];
        $desktopTypes = \explode(',', $desktopTypes);
        $validationMail = $pluginConfig['validationMail'];

        $config = [];
        $config['desktopTypes'] = [];
        $count = 0;

        foreach ($desktopTypes as $desktopType) {
            $config['desktopTypes'][$count]['id'] = $count;
            $config['desktopTypes'][$count]['name'] = $desktopType;
            ++$count;
        }

        $config['validationMail'] = $validationMail;
        $config['sendMail'] = (bool) $pluginConfig['sendMail'];

        $total = \count($config);

        $this->view->assign(
            [
                'success' => true,
                'data' => $config,
                'total' => $total,
            ]
        );
    }

    /**
     * assigns the payment data for a user to ExtJs to show the data in the view
     */
    public function getCustomerPaymentDataAction(): void
    {
        $modelManager = $this->get('models');
        $request = $this->Request()->getParams();
        $customerId = $request['customerId'];
        $paymentId = $request['paymentId'];

        $paymentDataRepository = $modelManager->getRepository(PaymentData::class);
        $paymentModel = $paymentDataRepository->findBy(['paymentMeanId' => $paymentId, 'customer' => $customerId]);
        $paymentModel = $paymentModel[0];

        $accountHolder = false;
        if ($paymentModel !== null) {
            $paymentMean = $paymentModel->getPaymentMean();
            if ($paymentModel->getUseBillingData() && $paymentMean->getName() === 'sepa') {
                $accountHolder = $this->getAccountHolder($customerId);
            }
        }

        $payment = $this->get('models')->toArray($paymentModel);
        if ($accountHolder) {
            $payment['accountHolder'] = $accountHolder;
        }

        $this->view->assign([
            'success' => true,
            'data' => $payment,
        ]);
    }

    /**
     * assigns the shop data to ExtJs to show the data in the view
     */
    public function getLanguageSubShopsAction(): void
    {
        $mainShopId = $this->Request()->getParam('mainShopId');

        $builder = $this->get('models')->createQueryBuilder();
        $builder->select('shops')
            ->from(Shop::class, 'shops')
            ->where('shops.mainId = :mainShopId')
            ->orWhere('shops.id = :mainShopId')
            ->andWhere('shops.active = 1')
            ->setParameter('mainShopId', $mainShopId);

        $result = $builder->getQuery()->getArrayResult();

        // Gets the correct language name for every shop
        foreach ($result as &$shop) {
            $shopModel = $this->get('models')->find(Shop::class, $shop['id']);
            $shop['name'] = $shopModel->getLocale()->getLanguage();
        }
        unset($shop);
        $total = \count($result);

        $this->view->assign(
            [
                'data' => $result,
                'success' => true,
                'total' => $total,
            ]
        );
    }

    /**
     * checks if the product which was added or edited is no voucher or esd product
     */
    public function validateEditAction(): void
    {
        $data = $this->Request()->getParams();
        $productNumber = (string) $data['articleNumber'];
        $quantity = (int) $data['quantity'];

        $productContext = new ProductContext($productNumber, $quantity);

        $violations = $this->get('swag_backend_order.order.product_validator')->validate($productContext);

        if ($violations->getMessages()) {
            $this->view->assign([
                'success' => false,
                'violations' => $violations->getMessages(),
            ]);

            return;
        }

        $this->view->assign('success', true);
    }

    /**
     * calculates the tax for this order
     */
    public function calculateBasketAction(): void
    {
        $requestHydrator = $this->get('swag_backend_order.price_calculation.request_hydrator');
        $requestStruct = $requestHydrator->hydrateFromRequest($this->Request()->getParams());

        $config = $this->container->get('config');
        $proportionalTaxCalculation = ((bool) $config->get('proportionalTaxCalculation')) && !$requestStruct->isTaxFree();

        // Basket position price calculation
        $positionPrices = [];
        foreach ($requestStruct->getPositions() as $position) {
            $positionPrice = $this->getPositionPrice($position, $requestStruct);
            $totalPositionPrice = new PriceResult();
            $totalPositionPrice->setNet($this->getTotalPrice($positionPrice->getNet(), $position->getQuantity()));
            $totalPositionPrice->setGross($this->getTotalPrice($positionPrice->getGross(), $position->getQuantity()));
            $totalPositionPrice->setTaxRate($position->getTaxRate());

            if ($requestStruct->isDisplayNet()) {
                $calculatedGross = $positionPrice->getNet() * (1 + ($position->getTaxRate() / 100));
                $totalPositionPrice->setGross($this->getTotalPrice($calculatedGross, $position->getQuantity()));
            }

            // Don't set the total amount of the product if it's a discount.
            if (!$position->getIsDiscount()) {
                $positionPrices[] = $totalPositionPrice;

                $position->setPrice($positionPrice->getGross());

                // Use net prices if it's configured like that
                if ($requestStruct->isTaxFree() || $requestStruct->isDisplayNet()) {
                    $position->setPrice($positionPrice->getNet());
                }

                $position->setTotal($this->getTotalPrice($position->getPrice(), $position->getQuantity()));
            }
        }

        $dispatchPrice = $this->getShippingPrice($requestStruct);

        $totalPriceCalculator = $this->get('swag_backend_order.price_calculation.total_price_calculator');
        $totalPriceResult = $totalPriceCalculator->calculate($positionPrices, $dispatchPrice, $proportionalTaxCalculation);
        $result = $this->createBasketCalculationResult($totalPriceResult, $requestStruct, $proportionalTaxCalculation);
        $result['isTaxFree'] = $requestStruct->isTaxFree();
        $result['isDisplayNet'] = $requestStruct->isDisplayNet();

        $discountCalculator = $this->get('swag_backend_order.price_calculation.discount_calculator');
        $result = $discountCalculator->calculateDiscount($result);

        $this->view->assign([
            'data' => $result,
            'success' => true,
        ]);
    }

    private function sendOrderConfirmationMail(Order $orderModel): void
    {
        $confirmationMailCreator = new ConfirmationMailCreator(
            new TaxCalculation(),
            $this->get('swag_backend_order.payment_translator'),
            $this->get('swag_backend_order.shipping_translator'),
            new ConfirmationMailRepository($this->get('dbal_connection')),
            $this->get('models')->getRepository(Detail::class),
            $this->get('config'),
            new NumberFormatterWrapper(),
            $this->get('modules')->Articles()
        );

        try {
            $context = $confirmationMailCreator->prepareOrderConfirmationMailData($orderModel);
            $context['sOrderDetails'] = $confirmationMailCreator->prepareOrderDetailsConfirmationMailData(
                $orderModel,
                $orderModel->getLanguageSubShop()->getLocale()
            );

            $mail = $this->container->get('templatemail')->createMail('sORDER', $context);
            $mail->addTo($context['additional']['user']['email']);
            $mail->send();

            // If configured email to the shop owner
            $mailNotToShopOwner = $this->container->get('config')->get('no_order_mail');
            if (!$mailNotToShopOwner) {
                $mail->clearRecipients();
                $mail->addTo($this->container->get('config')->get('mail'));
                $mail->send();
            }
        } catch (\Exception $e) {
            $this->view->assign('mail', $e->getMessage());
        }
    }

    private function getBackendLanguage(): int
    {
        $auth = $this->container->get('plugins')->Backend()->Auth()->checkAuth();
        if (!$auth instanceof Shopware_Components_Auth) {
            throw new RuntimeException('User not logged in');
        }
        $identity = $auth->getIdentity();

        return (int) $identity->locale->getId();
    }

    private function getListRequestParam(): ?string
    {
        $data = $this->Request()->getParams();

        return $data['filter'][0]['value'];
    }

    private function getTotalPrice(float $price, int $quantity): float
    {
        return $price * $quantity;
    }

    private function getAccountHolder(int $customerId): string
    {
        $customer = $this->get('models')->find(Customer::class, $customerId);

        return $customer->getBilling()->getFirstName() . ' ' . $customer->getBilling()->getLastName();
    }

    /**
     * @return CalculateBasketResult
     */
    private function createBasketCalculationResult(
        TotalPricesResult $totalPriceResult,
        RequestStruct $requestStruct,
        bool $proportionalTaxCalculation
    ): array {
        $shippingCosts = $totalPriceResult->getShipping()->getRoundedGrossPrice();
        $productSum = $totalPriceResult->getSum()->getRoundedGrossPrice();
        $total = $totalPriceResult->getTotal()->getRoundedGrossPrice();
        $taxSum = $totalPriceResult->getTaxAmount();

        if ($requestStruct->isDisplayNet()) {
            $productSum = $totalPriceResult->getSum()->getRoundedNetPrice();
        }

        if ($requestStruct->isTaxFree()) {
            $productSum = $totalPriceResult->getSum()->getRoundedNetPrice();
            $total = $totalPriceResult->getTotal()->getRoundedNetPrice();
            $taxSum = 0.00;
        }

        // Total prices calculation
        $totalNetPrice = $totalPriceResult->getTotal()->getRoundedNetPrice();
        $shippingCostsNet = $totalPriceResult->getShipping()->getRoundedNetPrice();

        if ($proportionalTaxCalculation) {
            $proportionalTaxCalculator = $this->container->get('shopware.cart.proportional_tax_calculator');
            $prices = $this->getPricesFromPositions($requestStruct->getPositions());
            $tax = $proportionalTaxCalculator->calculate($shippingCosts, $prices, true);
            foreach ($tax as $price) {
                $totalPriceResult->addTax($price->getTaxRate(), $price->getTax());
            }
        }

        return [
            'totalWithoutTax' => $totalNetPrice,
            'sum' => $productSum,
            'total' => $total,
            'shippingCosts' => $shippingCosts,
            'shippingCostsNet' => $shippingCostsNet,
            'shippingCostsTaxRate' => $totalPriceResult->getShipping()->getTaxRate(),
            'taxSum' => $taxSum,
            'positions' => $requestStruct->getPositionsArray(),
            'dispatchTaxRate' => $totalPriceResult->getShipping()->getTaxRate(),
            'proportionalTaxCalculation' => $proportionalTaxCalculation && !$requestStruct->isTaxFree(),
            'taxes' => $this->convertTaxes($totalPriceResult->getTaxes()),
        ];
    }

    /**
     * @param array<string|int, float> $taxes
     *
     * @return TaxArray
     */
    private function convertTaxes(array $taxes): array
    {
        $result = [];
        foreach ($taxes as $taxRate => $tax) {
            $result[] = [
                'taxRate' => (float) $taxRate,
                'tax' => \round($tax, 2),
            ];
        }

        return $result;
    }

    private function getPositionPrice(PositionStruct $position, RequestStruct $requestStruct): PriceResult
    {
        $priceContextFactory = $this->get('swag_backend_order.price_calculation.price_context_factory');
        $productCalculator = $this->get('swag_backend_order.price_calculation.product_calculator');

        $previousPriceContext = $priceContextFactory->create(
            $position->getPrice(),
            $position->getTaxRate(),
            $requestStruct->isPreviousDisplayNet(),
            $requestStruct->isPreviousTaxFree(),
            $requestStruct->getPreviousCurrencyId()
        );
        $basePrice = $productCalculator->calculateBasePrice($previousPriceContext);

        $currentPriceContext = $priceContextFactory->create(
            $basePrice,
            $position->getTaxRate(),
            true,
            $requestStruct->isTaxFree(),
            $requestStruct->getCurrencyId()
        );

        return $productCalculator->calculate($currentPriceContext);
    }

    /**
     * @param float[] $basketTaxRates
     *
     * @throws \RuntimeException
     */
    private function getDispatchTaxRate(?int $dispatchId, array $basketTaxRates = []): float
    {
        if ($dispatchId === null) {
            return 0.00;
        }

        $dispatch = $this->getModelManager()->find(Dispatch::class, $dispatchId);

        if ($dispatch === null) {
            throw new \RuntimeException('Can not find given dispatch with id ' . $dispatchId);
        }

        $taxId = $dispatch->getTaxCalculation();
        $tax = $this->getModelManager()->find(Tax::class, $taxId);

        if ($tax instanceof Tax) {
            return (float) $tax->getTax();
        }

        if (empty($basketTaxRates)) {
            return 0.00;
        }

        return $this->getHighestDispatchTaxRate($basketTaxRates);
    }

    /**
     * @param float[] $basketTaxRates
     */
    private function getHighestDispatchTaxRate(array $basketTaxRates): float
    {
        return (float) \max($basketTaxRates);
    }

    private function getShippingPrice(RequestStruct $requestStruct): PriceResult
    {
        $dispatchTaxRate = $this->getDispatchTaxRate($requestStruct->getDispatchId(), $requestStruct->getBasketTaxRates());
        $priceContextFactory = $this->get('swag_backend_order.price_calculation.price_context_factory');
        $shippingCalculator = $this->get('swag_backend_order.price_calculation.shipping_calculator');

        // Get base/gross shipping costs (even if tax free)
        $previousPriceContext = $priceContextFactory->create(
            $requestStruct->getShippingCosts(),
            $dispatchTaxRate,
            $requestStruct->isPreviousDisplayNet(),
            $requestStruct->isPreviousTaxFree(),
            $requestStruct->getPreviousCurrencyId()
        );
        $baseShippingPrice = $shippingCalculator->calculateBasePrice($previousPriceContext);

        // Calculate actual gross & net shipping costs for order
        $currentPriceContext = $priceContextFactory->create(
            $baseShippingPrice,
            $dispatchTaxRate,
            $requestStruct->isDisplayNet(),
            $requestStruct->isTaxFree(),
            $requestStruct->getCurrencyId()
        );

        return $shippingCalculator->calculate($currentPriceContext);
    }

    private function getShopId(): int
    {
        $shopId = (int) $this->Request()->getParam('shopId');

        if ($shopId === 0) {
            $shopRepo = $this->get('models')->getRepository(Shop::class);
            $shopId = $shopRepo->getActiveDefault()->getId();
        }

        return $shopId;
    }

    private function getCustomerGroupKey(): string
    {
        $customerId = (int) $this->Request()->getParam('customerId');

        // default customer group key of shopware
        $customerGroupKey = 'EK';

        if ($customerId !== 0) {
            $customerRepo = $this->get('swag_backend_order.customer_repository');
            $customer = $customerRepo->get($customerId);
            $customerGroupKey = $customer['groupKey'];
        }

        return $customerGroupKey;
    }

    /**
     * @param array<PositionStruct> $positions
     *
     * @return array<Price>
     */
    private function getPricesFromPositions(array $positions): array
    {
        $prices = [];
        foreach ($positions as $position) {
            $price = new Price(
                $position->getPrice(),
                $position->getNetPrice(),
                $position->getTaxRate(),
                $position->getNetPrice() * ($position->getTaxRate() / 100)
            );
            $prices[] = $price;
        }

        return $prices;
    }
}


text:
using namespace azule;
using namespace azule;
using namespace azule;
using namespace azule;
using namespace azule;
using namespace azule;
using namespace azule::pong;
using namespace azule;

struct Pong::Impl
{
	Impl()
	{
		this->font.loadFromFile((Configuration::Instance().getPathData() / "fonts/sansation.ttf").string());
	}

	std::shared_ptr<Engine> engine{std::make_unique<Engine>()};
	ScopedConnection connection;
	sf::SoundBuffer soundBuffer;
	sf::Sound sound{soundBuffer};
	sf::Font font;
};

Pong::Pong()
{
	auto window = std::make_shared<Window>();
	window->addChild(std::make_unique<RenderSystem>());
	window->addChild(std::make_unique<TextSystem>());
	window->addChild(std::make_unique<PhysicsRenderSystem>());
	this->pimpl->engine->addChild(window);

	auto manager = std::make_shared<EntityDatabase>();
	this->pimpl->engine->addChild(manager);
	this->pimpl->engine->addChild(std::make_shared<PlayerInputSystem>());
	this->pimpl->engine->addChild(std::make_shared<AudioSystem>());
	this->pimpl->engine->addChild(std::make_shared<PaddleAISystem>());
	this->pimpl->engine->addChild(std::make_shared<PhysicsSystem>());

	const auto metersW = static_cast<float>(PixelsToMeters(window->getWidth()));
	const auto metersH = static_cast<float>(PixelsToMeters(window->getHeight()));

	// Player 1
	auto paddle = manager->addEntity();
	auto rec = std::make_shared<sf::RectangleShape>();
	rec->setSize({1.0, 3.0});
	rec->setFillColor(sf::Color::White);
	rec->setOrigin(rec->getSize().x / 2.0f, rec->getSize().y / 2.0f);
	// paddle->addComponent<std::shared_ptr<sf::Drawable>>(rec);

	auto kinematicP1 = paddle->addComponent<KinematicComponent>();
	kinematicP1->BodyType = KinematicComponent::Type::Kinematic;

	auto boxColP1 = paddle->addComponent<BoxCollisionComponent>();
	boxColP1->Width = rec->getSize().x;
	boxColP1->Height = rec->getSize().y;

	auto t = paddle->addComponent<TransformComponent>();
	t->Position = {5, 10};

	auto input = paddle->addComponent<InputComponent>();
	input->addKeyBinding(sf::Keyboard::Key::Up, [](Entity& e, bool isPressed) {
		auto k = e.getChild<KinematicComponent>();
		k->LinearVelocity.y = isPressed == true ? -20.0f : 0.0f;
	});

	input->addKeyBinding(sf::Keyboard::Key::Down, [](Entity& e, bool isPressed) {
		auto k = e.getChild<KinematicComponent>();
		k->LinearVelocity.y = isPressed == true ? 20.0f : 0.0f;
	});

	// Player 2
	auto paddle2 = manager->addEntity();
	auto ai = paddle2->addComponent<PaddleAIComponent>();
	(void)ai;
	auto rec2 = std::make_shared<sf::RectangleShape>();
	rec2->setSize({1.0, 3.0});
	rec2->setFillColor(sf::Color::White);
	rec2->setOrigin(rec2->getSize().x / 2, rec2->getSize().y / 2);
	// paddle2->addComponent<std::shared_ptr<sf::Drawable>>(rec2);
	auto bodyP2 = paddle2->addComponent<KinematicComponent>();
	bodyP2->BodyType = KinematicComponent::Type::Kinematic;

	auto boxP2 = paddle2->addComponent<BoxCollisionComponent>();
	boxP2->Width = rec2->getSize().x;
	boxP2->Height = rec2->getSize().y;

	auto t2 = paddle2->addComponent<TransformComponent>();
	t2->Position = {35, 10};

	// Ball
	auto ball = manager->addEntity();
	// ai->setBall(*ball);
	auto circle = std::make_shared<sf::CircleShape>();
	circle->setRadius(0.5f);
	circle->setFillColor(sf::Color::White);
	circle->setOrigin(circle->getRadius(), circle->getRadius());
	// ball->addComponent<std::shared_ptr<sf::Drawable>>(circle);

	auto bodyBall = ball->addComponent<KinematicComponent>();
	bodyBall->BodyType = KinematicComponent::Type::Dynamic;
	bodyBall->LinearVelocity = {5.0, 0.0};

	auto circleP = ball->addComponent<CircleCollisionComponent>();
	circleP->Radius = circle->getRadius();
	circleP->Restitution = 1.0;
	circleP->Friction = 0.0;

	auto p = ball->addComponent<TransformComponent>();
	p->Position = {10, 10};

	// Top wall
	auto topWall = manager->addEntity();
	topWall->addComponent<TransformComponent>();
	auto twBody = topWall->addComponent<KinematicComponent>();
	twBody->BodyType = KinematicComponent::Type::Static;

	auto twEdge = topWall->addComponent<EdgeCollisionComponent>();
	twEdge->Vertex1 = {0.0, 1.0};
	twEdge->Vertex2 = {metersW, 1.0};

	// Bottom wall
	auto bottomWall = manager->addEntity();
	bottomWall->addComponent<TransformComponent>();
	auto bwBody = bottomWall->addComponent<KinematicComponent>();
	bwBody->BodyType = KinematicComponent::Type::Static;

	auto bwEdge = bottomWall->addComponent<EdgeCollisionComponent>();
	bwEdge->Vertex1 = {0.0, metersH - 1.0};
	bwEdge->Vertex2 = {metersW, metersH - 1.0};

	// Left Wall
	auto leftWall = manager->addEntity();
	leftWall->addComponent<TransformComponent>();
	auto lwBody = leftWall->addComponent<KinematicComponent>();
	lwBody->BodyType = KinematicComponent::Type::Static;

	auto lwEdge = leftWall->addComponent<EdgeCollisionComponent>();
	lwEdge->Vertex1 = {1.0, 0.0};
	lwEdge->Vertex2 = {1.0, metersH};
	lwEdge->IsSensor = true;

	// Right Wall
	auto rightWall = manager->addEntity();
	rightWall->addComponent<TransformComponent>();
	auto rwBody = rightWall->addComponent<KinematicComponent>();
	rwBody->BodyType = KinematicComponent::Type::Static;

	auto rwEdge = rightWall->addComponent<EdgeCollisionComponent>();
	rwEdge->Vertex1 = {metersW - 1.0, 0.0};
	rwEdge->Vertex2 = {metersW - 1.0, metersH};
	rwEdge->IsSensor = true;

	// Score 1
	auto score1 = manager->addEntity();
	auto text1 = std::make_shared<sf::Text>();
	text1->setString("0");
	text1->setFont(this->pimpl->font);
	text1->setCharacterSize(60);
	auto tb1 = text1->getLocalBounds();
	text1->setOrigin(tb1.width / 2.0f, tb1.height / 2.0f);
	// score1->addComponent<std::shared_ptr<sf::Text>>(text1);
	auto st1 = score1->addComponent<TransformComponent>();
	st1->Position = {window->getWidth() / 4.0, 100};

	// Score 2
	auto score2 = manager->addEntity();
	auto text2 = std::make_shared<sf::Text>();
	text2->setString("0");
	text2->setFont(this->pimpl->font);
	text2->setCharacterSize(60);
	auto tb2 = text2->getLocalBounds();
	text2->setOrigin(tb2.width / 2.0f, tb2.height / 2.0f);
	// score2->addComponent<std::shared_ptr<sf::Text>>(text2);
	auto st2 = score2->addComponent<TransformComponent>();

	st2->Position = {window->getWidth() - st1->Position.y, 100};

	auto& config = Configuration::Instance();
	this->pimpl->soundBuffer.loadFromFile((config.getPathData() / "audio/ball.wav").string());
	// ball->addComponent<sf::Sound>(this->pimpl->soundBuffer);

	// Handle what happens when the ball crosses behind the paddles.
	// Handle playing sounds when the ball collides with the paddles.
	this->pimpl->connection = EventQueue::Instance().addEventHandler([=](auto evt) mutable {
		auto evtCollision = dynamic_cast<CollisionEvent*>(evt);

		if(evtCollision != nullptr)
		{
			// if(evtCollision->getEntityA() == leftWall || evtCollision->getEntityA() == rightWall)
			{
				auto t = ball->getChild<TransformComponent>();
				t->Position = {metersW / 2, metersH / 2};

				auto b = ball->getChild<KinematicComponent>();
				b->LinearVelocity = {10.0f, 2.0f};

				// if(evtCollision->getEntityA() == leftWall)
				{
					// auto text = *score2->getChild<std::shared_ptr<sf::Text>>();
					// auto score = std::stoi(text->getString().toAnsiString());
					// text->setString(std::to_string(++score));
				}

				// if(evtCollision->getEntityA() == rightWall)
				{
					// auto text = *score1->getChild<std::shared_ptr<sf::Text>>();
					// auto score = std::stoi(text->getString().toAnsiString());
					// text->setString(std::to_string(++score));
				}
			}
			// else
			{
				// ball->getChild<sf::Sound>()->play();
				auto v = ball->getChild<KinematicComponent>()->LinearVelocity;
				ball->getChild<KinematicComponent>()->LinearVelocity = {v.x * 1.1f, v.y * 1.1f};
			}
		}
	});
}

Pong::~Pong()
{
}

int Pong::run()
{
	this->pimpl->engine->setEngineState(EngineState::State::StartUp);

	while(this->pimpl->engine->getEngineState().getState() < EngineState::State::Shutdown)
	{
		this->pimpl->engine->frame();
	}

	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
module FlashHelper

  def display_flash(flash)
    ret = []
    flash.each do |name, msg|
      ret << content_tag(:div, msg, :id => "flash_#{name}")
    end
    ret
  end

end


text:
<!doctype html>

  <meta charset="utf-8">
  <title>AngularWindowComponent</title>
  <base href="/angular-window-component/example/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="styles.2e839b6230f65269af62.bundle.css" rel="stylesheet"/>

  <wc-root></wc-root>


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.rightArithShiftDependencies = void 0;

var _dependenciesTyped = require("./dependenciesTyped.generated");

var _factoriesNumber = require("../../factoriesNumber.js");

/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
var rightArithShiftDependencies = {
  typedDependencies: _dependenciesTyped.typedDependencies,
  createRightArithShift: _factoriesNumber.createRightArithShift
};
exports.rightArithShiftDependencies = rightArithShiftDependencies;


text:
<?php

namespace frontend\models;

use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use common\models\User;
/**
 * This is the model class for table "project_main_files_notes".
 *
 * @property integer $id
 * @property integer $fileId
 * @property integer $note
 * @property integer $typeId
 * @property integer $creUserId
 * @property string $creTime
 *
 * @property User $creUser
 * @property ProjectMainFiles $file
 * @property ProjectFilesNotesType $type
 */
class ProjectMainFilesNotes extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_main_files_notes';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fileId', 'note', 'typeId'], 'required'],
            [['creTime'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'fileId' => 'File ID',
            'note' => 'Note',
            'typeId' => 'Type ID',
            'creUserId' => 'Cre User ID',
            'creTime' => 'Cre Time',
        ];
    }

    public function behaviors() {

        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['creTime'],
                ],
                'value' => new Expression( 'NOW()' ),
            ],
            'createstamp' => [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['creUserId' ],
                ],
                'value' => function ($event)
        {
            return Yii::$app->user->identity->id;
        }
            ]
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreUser()
    {
        return $this->hasOne(User::className(), ['id' => 'creUserId']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getFile()
    {
        return $this->hasOne(ProjectMainFiles::className(), ['id' => 'fileId']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getType()
    {
        return $this->hasOne(ProjectFilesNotesType::className(), ['id' => 'typeId']);
    }
}


text:
namespace Ploeh.TestTypeFoundation
{
    public interface IInterface
    {
        object MakeIt(object obj);
    }
}


text:
#include "config.h"
#include "core/layout/HitTestResult.h"

#include "core/HTMLNames.h"
#include "core/dom/DocumentMarkerController.h"
#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/shadow/ComposedTreeTraversal.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
#include "core/fetch/ImageResource.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/HTMLTextAreaElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/layout/LayoutImage.h"
#include "core/page/FrameTree.h"
#include "core/rendering/RenderTextFragment.h"
#include "core/svg/SVGElement.h"
#include "platform/scroll/Scrollbar.h"

namespace blink {

using namespace HTMLNames;

HitTestResult::HitTestResult()
    : m_isOverWidget(false)
{
}

HitTestResult::HitTestResult(const LayoutPoint& point)
    : m_hitTestLocation(point)
    , m_pointInInnerNodeFrame(point)
    , m_isOverWidget(false)
{
}

HitTestResult::HitTestResult(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding)
    : m_hitTestLocation(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding)
    , m_pointInInnerNodeFrame(centerPoint)
    , m_isOverWidget(false)
{
}

HitTestResult::HitTestResult(const HitTestLocation& other)
    : m_hitTestLocation(other)
    , m_pointInInnerNodeFrame(m_hitTestLocation.point())
    , m_isOverWidget(false)
{
}

HitTestResult::HitTestResult(const HitTestResult& other)
    : m_hitTestLocation(other.m_hitTestLocation)
    , m_innerNode(other.innerNode())
    , m_innerPossiblyPseudoNode(other.m_innerPossiblyPseudoNode)
    , m_innerNonSharedNode(other.innerNonSharedNode())
    , m_pointInInnerNodeFrame(other.m_pointInInnerNodeFrame)
    , m_localPoint(other.localPoint())
    , m_innerURLElement(other.URLElement())
    , m_scrollbar(other.scrollbar())
    , m_isOverWidget(other.isOverWidget())
{
    // Only copy the NodeSet in case of rect hit test.
    m_rectBasedTestResult = adoptPtrWillBeNoop(other.m_rectBasedTestResult ? new NodeSet(*other.m_rectBasedTestResult) : 0);
}

HitTestResult::~HitTestResult()
{
}

HitTestResult& HitTestResult::operator=(const HitTestResult& other)
{
    m_hitTestLocation = other.m_hitTestLocation;
    m_innerNode = other.innerNode();
    m_innerPossiblyPseudoNode = other.innerPossiblyPseudoNode();
    m_innerNonSharedNode = other.innerNonSharedNode();
    m_pointInInnerNodeFrame = other.m_pointInInnerNodeFrame;
    m_localPoint = other.localPoint();
    m_innerURLElement = other.URLElement();
    m_scrollbar = other.scrollbar();
    m_isOverWidget = other.isOverWidget();

    // Only copy the NodeSet in case of rect hit test.
    m_rectBasedTestResult = adoptPtrWillBeNoop(other.m_rectBasedTestResult ? new NodeSet(*other.m_rectBasedTestResult) : 0);

    return *this;
}

DEFINE_TRACE(HitTestResult)
{
    visitor->trace(m_innerNode);
    visitor->trace(m_innerPossiblyPseudoNode);
    visitor->trace(m_innerNonSharedNode);
    visitor->trace(m_innerURLElement);
    visitor->trace(m_scrollbar);
#if ENABLE(OILPAN)
    visitor->trace(m_rectBasedTestResult);
#endif
}

PositionWithAffinity HitTestResult::position() const
{
    if (!m_innerPossiblyPseudoNode)
        return PositionWithAffinity();
    LayoutObject* renderer = this->renderer();
    if (!renderer)
        return PositionWithAffinity();
    if (m_innerPossiblyPseudoNode->isPseudoElement() && m_innerPossiblyPseudoNode->pseudoId() == BEFORE)
        return Position(m_innerNode, Position::PositionIsBeforeChildren).downstream();
    return renderer->positionForPoint(localPoint());
}

LayoutObject* HitTestResult::renderer() const
{
    return m_innerNode ? m_innerNode->renderer() : 0;
}

void HitTestResult::setToShadowHostIfInClosedShadowRoot()
{
    if (Node* node = innerNode()) {
        if (ShadowRoot* containingShadowRoot = node->containingShadowRoot()) {
            if (containingShadowRoot->type() == ShadowRoot::ClosedShadowRoot)
                setInnerNode(node->shadowHost());
        }
    }

    if (Node* node = innerNonSharedNode()) {
        if (ShadowRoot* containingShadowRoot = node->containingShadowRoot()) {
            if (containingShadowRoot->type() == ShadowRoot::ClosedShadowRoot)
                setInnerNonSharedNode(node->shadowHost());
        }
    }
}

void HitTestResult::setInnerNode(Node* n)
{
    m_innerPossiblyPseudoNode = n;
    if (n && n->isPseudoElement())
        n = n->parentOrShadowHostNode();
    m_innerNode = n;
}

void HitTestResult::setInnerNonSharedNode(Node* n)
{
    if (n && n->isPseudoElement())
        n = n->parentOrShadowHostNode();
    m_innerNonSharedNode = n;
}

void HitTestResult::setURLElement(Element* n)
{
    m_innerURLElement = n;
}

void HitTestResult::setScrollbar(Scrollbar* s)
{
    m_scrollbar = s;
}

LocalFrame* HitTestResult::innerNodeFrame() const
{
    if (m_innerNonSharedNode)
        return m_innerNonSharedNode->document().frame();
    if (m_innerNode)
        return m_innerNode->document().frame();
    return 0;
}

bool HitTestResult::isSelected() const
{
    if (!m_innerNonSharedNode)
        return false;

    if (LocalFrame* frame = m_innerNonSharedNode->document().frame())
        return frame->selection().contains(m_hitTestLocation.point());
    return false;
}

String HitTestResult::spellingToolTip(TextDirection& dir) const
{
    dir = LTR;
    // Return the tool tip string associated with this point, if any. Only markers associated with bad grammar
    // currently supply strings, but maybe someday markers associated with misspelled words will also.
    if (!m_innerNonSharedNode)
        return String();

    DocumentMarker* marker = m_innerNonSharedNode->document().markers().markerContainingPoint(m_hitTestLocation.point(), DocumentMarker::Grammar);
    if (!marker)
        return String();

    if (LayoutObject* renderer = m_innerNonSharedNode->renderer())
        dir = renderer->style()->direction();
    return marker->description();
}

String HitTestResult::title(TextDirection& dir) const
{
    dir = LTR;
    // Find the title in the nearest enclosing DOM node.
    // For <area> tags in image maps, walk the tree for the <area>, not the <img> using it.
    for (Node* titleNode = m_innerNode.get(); titleNode; titleNode = ComposedTreeTraversal::parent(*titleNode)) {
        if (titleNode->isElementNode()) {
            String title = toElement(titleNode)->title();
            if (!title.isNull()) {
                if (LayoutObject* renderer = titleNode->renderer())
                    dir = renderer->style()->direction();
                return title;
            }
        }
    }
    return String();
}

const AtomicString& HitTestResult::altDisplayString() const
{
    if (!m_innerNonSharedNode)
        return nullAtom;

    if (isHTMLImageElement(*m_innerNonSharedNode)) {
        HTMLImageElement& image = toHTMLImageElement(*m_innerNonSharedNode);
        return image.getAttribute(altAttr);
    }

    if (isHTMLInputElement(*m_innerNonSharedNode)) {
        HTMLInputElement& input = toHTMLInputElement(*m_innerNonSharedNode);
        return input.alt();
    }

    return nullAtom;
}

Image* HitTestResult::image() const
{
    if (!m_innerNonSharedNode)
        return 0;

    LayoutObject* renderer = m_innerNonSharedNode->renderer();
    if (renderer && renderer->isImage()) {
        LayoutImage* image = toLayoutImage(renderer);
        if (image->cachedImage() && !image->cachedImage()->errorOccurred())
            return image->cachedImage()->imageForRenderer(image);
    }

    return 0;
}

IntRect HitTestResult::imageRect() const
{
    if (!image())
        return IntRect();
    return m_innerNonSharedNode->renderBox()->absoluteContentQuad().enclosingBoundingBox();
}

KURL HitTestResult::absoluteImageURL() const
{
    if (!m_innerNonSharedNode)
        return KURL();

    LayoutObject* renderer = m_innerNonSharedNode->renderer();
    if (!(renderer && renderer->isImage()))
        return KURL();

    AtomicString urlString;
    if (isHTMLEmbedElement(*m_innerNonSharedNode)
        || isHTMLImageElement(*m_innerNonSharedNode)
        || isHTMLInputElement(*m_innerNonSharedNode)
        || isHTMLObjectElement(*m_innerNonSharedNode)
        || isSVGImageElement(*m_innerNonSharedNode)) {
        urlString = toElement(*m_innerNonSharedNode).imageSourceURL();
    } else {
        return KURL();
    }

    return m_innerNonSharedNode->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
}

KURL HitTestResult::absoluteMediaURL() const
{
    if (HTMLMediaElement* mediaElt = mediaElement())
        return mediaElt->currentSrc();
    return KURL();
}

HTMLMediaElement* HitTestResult::mediaElement() const
{
    if (!m_innerNonSharedNode)
        return 0;

    if (!(m_innerNonSharedNode->renderer() && m_innerNonSharedNode->renderer()->isMedia()))
        return 0;

    if (isHTMLMediaElement(*m_innerNonSharedNode))
        return toHTMLMediaElement(m_innerNonSharedNode);
    return 0;
}

KURL HitTestResult::absoluteLinkURL() const
{
    if (!m_innerURLElement)
        return KURL();
    return m_innerURLElement->hrefURL();
}

bool HitTestResult::isLiveLink() const
{
    return m_innerURLElement && m_innerURLElement->isLiveLink();
}

bool HitTestResult::isMisspelled() const
{
    if (!innerNode() || !innerNode()->renderer())
        return false;
    VisiblePosition pos(innerNode()->renderer()->positionForPoint(localPoint()));
    if (pos.isNull())
        return false;
    return m_innerNonSharedNode->document().markers().markersInRange(
        makeRange(pos, pos).get(), DocumentMarker::MisspellingMarkers()).size() > 0;
}

bool HitTestResult::isOverLink() const
{
    return m_innerURLElement && m_innerURLElement->isLink();
}

String HitTestResult::textContent() const
{
    if (!m_innerURLElement)
        return String();
    return m_innerURLElement->textContent();
}

// FIXME: This function needs a better name and may belong in a different class. It's not
// really isContentEditable(); it's more like needsEditingContextMenu(). In many ways, this
// function would make more sense in the ContextMenu class, except that WebElementDictionary
// hooks into it. Anyway, we should architect this better.
bool HitTestResult::isContentEditable() const
{
    if (!m_innerNonSharedNode)
        return false;

    if (isHTMLTextAreaElement(*m_innerNonSharedNode))
        return !toHTMLTextAreaElement(*m_innerNonSharedNode).isDisabledOrReadOnly();

    if (isHTMLInputElement(*m_innerNonSharedNode)) {
        HTMLInputElement& inputElement = toHTMLInputElement(*m_innerNonSharedNode);
        return !inputElement.isDisabledOrReadOnly() && inputElement.isTextField();
    }

    return m_innerNonSharedNode->hasEditableStyle();
}

bool HitTestResult::addNodeToRectBasedTestResult(Node* node, const HitTestRequest& request, const HitTestLocation& locationInContainer, const LayoutRect& rect)
{
    // If it is not a rect-based hit test, this method has to be no-op.
    // Return false, so the hit test stops.
    if (!isRectBasedTest())
        return false;

    // If node is null, return true so the hit test can continue.
    if (!node)
        return true;

    mutableRectBasedTestResult().add(node);

    bool regionFilled = rect.contains(locationInContainer.boundingBox());
    return !regionFilled;
}

bool HitTestResult::addNodeToRectBasedTestResult(Node* node, const HitTestRequest& request, const HitTestLocation& locationInContainer, const FloatRect& rect)
{
    // If it is not a rect-based hit test, this method has to be no-op.
    // Return false, so the hit test stops.
    if (!isRectBasedTest())
        return false;

    // If node is null, return true so the hit test can continue.
    if (!node)
        return true;

    mutableRectBasedTestResult().add(node);

    bool regionFilled = rect.contains(locationInContainer.boundingBox());
    return !regionFilled;
}

void HitTestResult::append(const HitTestResult& other)
{
    ASSERT(isRectBasedTest() && other.isRectBasedTest());

    if (!m_scrollbar && other.scrollbar()) {
        setScrollbar(other.scrollbar());
    }

    if (!m_innerNode && other.innerNode()) {
        m_innerNode = other.innerNode();
        m_innerPossiblyPseudoNode = other.innerPossiblyPseudoNode();
        m_innerNonSharedNode = other.innerNonSharedNode();
        m_localPoint = other.localPoint();
        m_pointInInnerNodeFrame = other.m_pointInInnerNodeFrame;
        m_innerURLElement = other.URLElement();
        m_isOverWidget = other.isOverWidget();
    }

    if (other.m_rectBasedTestResult) {
        NodeSet& set = mutableRectBasedTestResult();
        for (NodeSet::const_iterator it = other.m_rectBasedTestResult->begin(), last = other.m_rectBasedTestResult->end(); it != last; ++it)
            set.add(it->get());
    }
}

const HitTestResult::NodeSet& HitTestResult::rectBasedTestResult() const
{
    if (!m_rectBasedTestResult)
        m_rectBasedTestResult = adoptPtrWillBeNoop(new NodeSet);
    return *m_rectBasedTestResult;
}

HitTestResult::NodeSet& HitTestResult::mutableRectBasedTestResult()
{
    if (!m_rectBasedTestResult)
        m_rectBasedTestResult = adoptPtrWillBeNoop(new NodeSet);
    return *m_rectBasedTestResult;
}

void HitTestResult::resolveRectBasedTest(Node* resolvedInnerNode, const LayoutPoint& resolvedPointInMainFrame)
{
    ASSERT(isRectBasedTest());
    ASSERT(m_hitTestLocation.containsPoint(FloatPoint(resolvedPointInMainFrame)));
    m_hitTestLocation = HitTestLocation(resolvedPointInMainFrame);
    m_pointInInnerNodeFrame = resolvedPointInMainFrame;
    m_innerNode = nullptr;
    m_innerNonSharedNode = nullptr;
    m_innerPossiblyPseudoNode = nullptr;
    m_rectBasedTestResult = nullptr;

    // Update the HitTestResult as if the supplied node had been hit in normal point-based hit-test.
    // Note that we don't know the local point after a rect-based hit-test, but we never use
    // it so shouldn't bother with the cost of computing it.
    resolvedInnerNode->renderer()->updateHitTestResult(*this, LayoutPoint());
    ASSERT(!isRectBasedTest());
}

Element* HitTestResult::innerElement() const
{
    for (Node* node = m_innerNode.get(); node; node = NodeRenderingTraversal::parent(*node)) {
        if (node->isElementNode())
            return toElement(node);
    }

    return 0;
}

} // namespace blink


text:
<?php

namespace Sonata\NewsBundle\Model;

use Sonata\CoreBundle\Model\ManagerInterface;
use Sonata\CoreBundle\Model\PageableManagerInterface;

interface CommentManagerInterface extends ManagerInterface, PageableManagerInterface
{
    /**
     * Update the number of comment for a comment.
     */
    public function updateCommentsCount(PostInterface $post = null);
}


text:
package com.hazelcast.internal.nio.tcp;

import com.hazelcast.cluster.Address;
import com.hazelcast.instance.EndpointQualifier;
import com.hazelcast.instance.ProtocolType;
import com.hazelcast.internal.cluster.impl.BindMessage;
import com.hazelcast.internal.nio.IOService;
import com.hazelcast.internal.nio.Packet;
import com.hazelcast.logging.ILogger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class BindRequest {

    private final ILogger logger;

    private final IOService ioService;

    private final TcpIpConnection connection;
    private final Address remoteEndPoint;
    private final boolean reply;

    BindRequest(ILogger logger, IOService ioService, TcpIpConnection connection, Address remoteEndPoint, boolean reply) {
        this.logger = logger;
        this.ioService = ioService;
        this.connection = connection;
        this.remoteEndPoint = remoteEndPoint;
        this.reply = reply;
    }

    public void send() {
        connection.setEndPoint(remoteEndPoint);
        ioService.onSuccessfulConnection(remoteEndPoint);
        //make sure bind packet is the first packet sent to the end point.
        if (logger.isFinestEnabled()) {
            logger.finest("Sending bind packet to " + remoteEndPoint);
        }
        BindMessage bind = new BindMessage((byte) 1, getConfiguredLocalAddresses(), remoteEndPoint, reply, ioService.getUuid());
        byte[] bytes = ioService.getSerializationService().toBytes(bind);
        Packet packet = new Packet(bytes).setPacketType(Packet.Type.BIND);
        connection.write(packet);
        //now you can send anything...
    }

    Map<ProtocolType, Collection<Address>> getConfiguredLocalAddresses() {
        Map<ProtocolType, Collection<Address>> addressMap = new HashMap<ProtocolType, Collection<Address>>();
        Map<EndpointQualifier, Address> addressesPerEndpointQualifier = ioService.getThisAddresses();
        for (Map.Entry<EndpointQualifier, Address> addressEntry : addressesPerEndpointQualifier.entrySet()) {
            Collection<Address> addresses = addressMap.get(addressEntry.getKey().getType());
            if (addresses == null) {
                addresses = new ArrayList<Address>();
                addressMap.put(addressEntry.getKey().getType(), addresses);
            }
            addresses.add(addressEntry.getValue());
        }
        return addressMap;
    }
}


text:
using NUnit.Framework;

namespace IIS.SLSharp.Examples.Tests
{
    [SetUpFixture]
    public sealed class TestState
    {
        public static readonly ITestRuntime Runtime = new OpenTKTestRuntime.OpenTKTestRuntime();

        private static bool _initialized;

        public static void Initialize()
        {
            if (_initialized)
                return;
            Runtime.Initialize();
            _initialized = true;
        }

        public static void Cleanup()
        {
            if (!_initialized)
                return;
            Runtime.Cleanup();
            _initialized = false;
        }

        [SetUp]
        public static void AssemblyInit()
        {
            Initialize(); // first init
        }

        [TearDown]
        public static void AssemblyCleanup()
        {
        }
    }
}


text:
package com.hiroapp.main;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Window;

public class SplashScreen extends Activity implements Callback, Runnable {

	private Handler handler;
	private int splash_interval = 3000;
	private String TAG = this.getClass().getSimpleName();
	private SharedPreferences preferences;
	private Thread thread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splashscreenlayout);

		preferences = this.getSharedPreferences(getString(R.string.app_name),
				Activity.MODE_WORLD_WRITEABLE);

		getPreferenceValue();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		handler = new Handler(this);
		thread = new Thread(this);
		thread.start();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Thread.sleep(splash_interval);
			handler.sendEmptyMessage(0);
		} catch (InterruptedException ex) {
		}
	}

	/**
	 *  Start the MainActivity when Splash interval is complete.
	 */
	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		if (msg.what == 0) {
			// load pick band activity
			Intent intent = null;
			intent = new Intent(SplashScreen.this, MainActivity.class);
			startActivity(intent);
			finish(); // finish the splash screen
		}
		return false;
	}

	/**
	 *  Get the Preference value
	 */
	public void getPreferenceValue() {

//		boolean isBattery = preferences.getBoolean("isbattery", true);
//		boolean isnotification = preferences.getBoolean("isnotification", true);
//		boolean isSoundAlert = preferences.getBoolean("isSoundAlert", true);
//		boolean isHeroBeepAlert = preferences.getBoolean("isHeroBeepAlert",
//				true);
//		boolean isbeepHigh = preferences.getBoolean("isbeepHigh", true);
//		boolean isbeepVolume = preferences.getBoolean("isbeepVolumeHigh", true);
//
//		String disRing = preferences.getString("DisconnectRing", "");
		String phoneRing = preferences.getString("PhoneRing", "");

		SharedPreferences.Editor editor1 = preferences.edit();
//		editor1.putBoolean("isbattery", isBattery);
//		editor1.putBoolean("isbeepHigh", isbeepHigh);
//		editor1.putBoolean("isbeepVolumeHigh", isbeepVolume);
//		editor1.putBoolean("isnotification", isnotification);
//		editor1.putBoolean("isSoundAlert", isSoundAlert);
//		editor1.putBoolean("isHeroBeepAlert", isHeroBeepAlert);
//		editor1.putString("DisconnectRing", disRing);
		editor1.putString("PhoneRing", phoneRing);
		editor1.commit();

	}

	/**
	 *  called when Activity is destroy and remove the handler.
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		if(thread != null){
			thread.interrupt();
			thread = null;

			if(handler != null && handler.hasMessages(0))
				handler.removeMessages(0);

		}

	}

}


text:
<?php

class QodeIconsFontElegant implements iIconCollection {

	public $icons;
	public $title;
	public $param;
	public $styleUrl;

	function __construct($title = "", $param = "") {
		$this->icons = array();
		$this->socialIcons = array();
		$this->title = $title;
		$this->param = $param;
		$this->setIconsArray();
		$this->setSocialIconsArray();
		$this->styleUrl = QODE_ROOT . "/css/elegant-icons/style.min.css";
	}

	private function setIconsArray() {
		$this->icons = array(
			'' => '',
			'arrow_back' => 'arrow_back',
			'arrow_carrot-2down' => 'arrow_carrot-2down',
			'arrow_carrot-2down_alt2' => 'arrow_carrot-2down_alt2',
			'arrow_carrot-2dwnn_alt' => 'arrow_carrot-2dwnn_alt',
			'arrow_carrot-2left' => 'arrow_carrot-2left',
			'arrow_carrot-2left_alt' => 'arrow_carrot-2left_alt',
			'arrow_carrot-2left_alt2' => 'arrow_carrot-2left_alt2',
			'arrow_carrot-2right' => 'arrow_carrot-2right',
			'arrow_carrot-2right_alt' => 'arrow_carrot-2right_alt',
			'arrow_carrot-2right_alt2' => 'arrow_carrot-2right_alt2',
			'arrow_carrot-2up' => 'arrow_carrot-2up',
			'arrow_carrot-2up_alt' => 'arrow_carrot-2up_alt',
			'arrow_carrot-2up_alt2' => 'arrow_carrot-2up_alt2',
			'arrow_carrot-down' => 'arrow_carrot-down',
			'arrow_carrot-down_alt' => 'arrow_carrot-down_alt',
			'arrow_carrot-down_alt2' => 'arrow_carrot-down_alt2',
			'arrow_carrot-left' => 'arrow_carrot-left',
			'arrow_carrot-left_alt' => 'arrow_carrot-left_alt',
			'arrow_carrot-left_alt2' => 'arrow_carrot-left_alt2',
			'arrow_carrot-right' => 'arrow_carrot-right',
			'arrow_carrot-right_alt' => 'arrow_carrot-right_alt',
			'arrow_carrot-right_alt2' => 'arrow_carrot-right_alt2',
			'arrow_carrot-up' => 'arrow_carrot-up',
			'arrow_carrot-up_alt2' => 'arrow_carrot-up_alt2',
			'arrow_carrot_up_alt' => 'arrow_carrot_up_alt',
			'arrow_condense' => 'arrow_condense',
			'arrow_condense_alt' => 'arrow_condense_alt',
			'arrow_down' => 'arrow_down',
			'arrow_down_alt' => 'arrow_down_alt',
			'arrow_expand' => 'arrow_expand',
			'arrow_expand_alt' => 'arrow_expand_alt',
			'arrow_expand_alt2' => 'arrow_expand_alt2',
			'arrow_expand_alt3' => 'arrow_expand_alt3',
			'arrow_left' => 'arrow_left',
			'arrow_left-down' => 'arrow_left-down',
			'arrow_left-down_alt' => 'arrow_left-down_alt',
			'arrow_left-right' => 'arrow_left-right',
			'arrow_left-right_alt' => 'arrow_left-right_alt',
			'arrow_left-up' => 'arrow_left-up',
			'arrow_left-up_alt' => 'arrow_left-up_alt',
			'arrow_left_alt' => 'arrow_left_alt',
			'arrow_move' => 'arrow_move',
			'arrow_right' => 'arrow_right',
			'arrow_right-down' => 'arrow_right-down',
			'arrow_right-down_alt' => 'arrow_right-down_alt',
			'arrow_right-up' => 'arrow_right-up',
			'arrow_right-up_alt' => 'arrow_right-up_alt',
			'arrow_right_alt' => 'arrow_right_alt',
			'arrow_triangle-down' => 'arrow_triangle-down',
			'arrow_triangle-down_alt' => 'arrow_triangle-down_alt',
			'arrow_triangle-down_alt2' => 'arrow_triangle-down_alt2',
			'arrow_triangle-left' => 'arrow_triangle-left',
			'arrow_triangle-left_alt' => 'arrow_triangle-left_alt',
			'arrow_triangle-left_alt2' => 'arrow_triangle-left_alt2',
			'arrow_triangle-right' => 'arrow_triangle-right',
			'arrow_triangle-right_alt' => 'arrow_triangle-right_alt',
			'arrow_triangle-right_alt2' => 'arrow_triangle-right_alt2',
			'arrow_triangle-up' => 'arrow_triangle-up',
			'arrow_triangle-up_alt' => 'arrow_triangle-up_alt',
			'arrow_triangle-up_alt2' => 'arrow_triangle-up_alt2',
			'arrow_up' => 'arrow_up',
			'arrow_up-down' => 'arrow-up-down',
			'arrow_up-down_alt' => 'arrow_up-down_alt',
			'arrow_up_alt' => 'arrow_up_alt',
			'icon_adjust-horiz' => 'icon_adjust-horiz',
			'icon_adjust-vert' => 'icon_adjust-vert',
			'icon_archive' => 'icon_archive',
			'icon_archive_alt' => 'icon_archive_alt',
			'icon_bag' => 'icon_bag',
			'icon_bag_alt' => 'icon_bag_alt',
			'icon_balance' => 'icon_balance',
			'icon_blocked' => 'icon_blocked',
			'icon_book' => 'icon_book',
			'icon_book_alt' => 'icon_book_alt',
			'icon_box-checked' => 'icon_box-checked',
			'icon_box-empty' => 'icon_box-empty',
			'icon_box-selected' => 'icon_box-selected',
			'icon_briefcase' => 'icon_briefcase',
			'icon_briefcase_alt' => 'icon_briefcase_alt',
			'icon_building' => 'icon_building',
			'icon_building_alt' => 'icon_building_alt',
			'icon_calculator_alt' => 'icon_calculator_alt',
			'icon_calendar' => 'icon_calendar',
			'icon_calulator' => 'icon_calulator',
			'icon_camera' => 'icon_camera',
			'icon_camera_alt' => 'icon_camera_alt',
			'icon_cart' => 'icon_cart',
			'icon_cart_alt' => 'icon_cart_alt',
			'icon_chat' => 'icon_chat',
			'icon_chat_alt' => 'icon_chat_alt',
			'icon_check' => 'icon_check',
			'icon_check_alt' => 'icon_check_alt',
			'icon_check_alt2' => 'icon_check_alt2',
			'icon_circle-empty' => 'icon_circle-empty',
			'icon_circle-slelected' => 'icon_circle-slelected',
			'icon_clipboard' => 'icon_clipboard',
			'icon_clock' => 'icon_clock',
			'icon_clock_alt' => 'icon_clock_alt',
			'icon_close' => 'icon_close',
			'icon_close_alt' => 'icon_close_alt',
			'icon_close_alt2' => 'icon_close_alt2',
			'icon_cloud' => 'icon_cloud',
			'icon_cloud-download' => 'icon_cloud-download',
			'icon_cloud-download_alt' => 'icon_cloud-download_alt',
			'icon_cloud-upload' => 'icon_cloud-upload',
			'icon_cloud-upload_alt' => 'icon_cloud-upload_alt',
			'icon_cloud_alt' => 'icon_cloud_alt',
			'icon_cog' => 'icon_cog',
			'icon_cogs' => 'icon_cogs',
			'icon_comment' => 'icon_comment',
			'icon_comment_alt' => 'icon_comment_alt',
			'icon_compass' => 'icon_compass',
			'icon_compass_alt' => 'icon_compass_alt',
			'icon_cone' => 'icon_cone',
			'icon_cone_alt' => 'icon_cone_alt',
			'icon_contacts' => 'icon_contacts',
			'icon_contacts_alt' => 'icon_contacts_alt',
			'icon_creditcard' => 'icon_creditcard',
			'icon_currency' => 'icon_currency',
			'icon_currency_alt' => 'icon_currency_alt',
			'icon_cursor' => 'icon_cursor',
			'icon_cursor_alt' => 'icon_cursor_alt',
			'icon_datareport' => 'icon_datareport',
			'icon_datareport_alt' => 'icon_datareport_alt',
			'icon_desktop' => 'icon_desktop',
			'icon_dislike' => 'icon_dislike',
			'icon_dislike_alt' => 'icon_dislike_alt',
			'icon_document' => 'icon_document',
			'icon_document_alt' => 'icon_document_alt',
			'icon_documents' => 'icon_documents',
			'icon_documents_alt' => 'icon_documents_alt',
			'icon_download' => 'icon_download',
			'icon_drawer' => 'icon_drawer',
			'icon_drawer_alt' => 'icon_drawer_alt',
			'icon_drive' => 'icon_drive',
			'icon_drive_alt' => 'icon_drive_alt',
			'icon_easel' => 'icon_easel',
			'icon_easel_alt' => 'icon_easel_alt',
			'icon_error-circle' => 'icon_error-circle',
			'icon_error-circle_alt' => 'icon_error-circle_alt',
			'icon_error-oct' => 'icon_error-oct',
			'icon_error-oct_alt' => 'icon_error-oct_alt',
			'icon_error-triangle' => 'icon_error-triangle',
			'icon_error-triangle_alt' => 'icon_error-triangle_alt',
			'icon_film' => 'icon_film',
			'icon_floppy' => 'icon_floppy',
			'icon_floppy_alt' => 'icon_floppy_alt',
			'icon_flowchart' => 'icon_flowchart',
			'icon_flowchart_alt' => 'icon_flowchart_alt',
			'icon_folder' => 'icon_folder',
			'icon_folder-add' => 'icon_folder-add',
			'icon_folder-add_alt' => 'icon_folder-add_alt',
			'icon_folder-alt' => 'icon_folder-alt',
			'icon_folder-open' => 'icon_folder-open',
			'icon_folder-open_alt' => 'icon_folder-open_alt',
			'icon_folder_download' => 'icon_folder_download',
			'icon_folder_upload' => 'icon_folder_upload',
			'icon_genius' => 'icon_genius',
			'icon_gift' => 'icon_gift',
			'icon_gift_alt' => 'icon_gift_alt',
			'icon_globe' => 'icon_globe',
			'icon_globe-2' => 'icon_globe-2',
			'icon_globe_alt' => 'icon_globe_alt',
			'icon_grid-2x2' => 'icon_grid-2x2',
			'icon_grid-3x3' => 'icon_grid-3x3',
			'icon_group' => 'icon_group',
			'icon_headphones' => 'icon_headphones',
			'icon_heart' => 'icon_heart',
			'icon_heart_alt' => 'icon_heart_alt',
			'icon_hourglass' => 'icon_hourglass',
			'icon_house' => 'icon_house',
			'icon_house_alt' => 'icon_house_alt',
			'icon_id' => 'icon_id',
			'icon_id-2' => 'icon_id-2',
			'icon_id-2_alt' => 'icon_id-2_alt',
			'icon_id_alt' => 'icon_id_alt',
			'icon_image' => 'icon_image',
			'icon_images' => 'icon_images',
			'icon_info' => 'icon_info',
			'icon_info_alt' => 'icon_info_alt',
			'icon_key' => 'icon_key',
			'icon_key_alt' => 'icon_key_alt',
			'icon_laptop' => 'icon_laptop',
			'icon_lifesaver' => 'icon_lifesaver',
			'icon_lightbulb' => 'icon_lightbulb',
			'icon_lightbulb_alt' => 'icon_lightbulb_alt',
			'icon_like' => 'icon_like',
			'icon_like_alt' => 'icon_like_alt',
			'icon_link' => 'icon_link',
			'icon_link_alt' => 'icon_link_alt',
			'icon_loading' => 'icon_loading',
			'icon_lock' => 'icon_lock',
			'icon_lock-open' => 'icon_lock-open',
			'icon_lock-open_alt' => 'icon_lock-open_alt',
			'icon_lock_alt' => 'icon_lock_alt',
			'icon_mail' => 'icon_mail',
			'icon_mail_alt' => 'icon_mail_alt',
			'icon_map' => 'icon_map',
			'icon_map_alt' => 'icon_map_alt',
			'icon_menu' => 'icon_menu',
			'icon_menu-circle_alt' => 'icon_menu-circle_alt',
			'icon_menu-circle_alt2' => 'icon_menu-circle_alt2',
			'icon_menu-square_alt' => 'icon_menu-square_alt',
			'icon_menu-square_alt2' => 'icon_menu-square_alt2',
			'icon_mic' => 'icon_mic',
			'icon_mic_alt' => 'icon_mic_alt',
			'icon_minus-06' => 'icon_minus-06',
			'icon_minus-box' => 'icon_minus-box',
			'icon_minus_alt' => 'icon_minus_alt',
			'icon_minus_alt2' => 'icon_minus_alt2',
			'icon_mobile' => 'icon_mobile',
			'icon_mug' => 'icon_mug',
			'icon_mug_alt' => 'icon_mug_alt',
			'icon_music' => 'icon_music',
			'icon_ol' => 'icon_ol',
			'icon_paperclip' => 'icon_paperclip',
			'icon_pause' => 'icon_pause',
			'icon_pause_alt' => 'icon_pause_alt',
			'icon_pause_alt2' => 'icon_pause_alt2',
			'icon_pencil' => 'icon_pencil',
			'icon_pencil-edit' => 'icon_pencil-edit',
			'icon_pencil-edit_alt' => 'icon_pencil-edit_alt',
			'icon_pencil_alt' => 'icon_pencil_alt',
			'icon_pens' => 'icon_pens',
			'icon_pens_alt' => 'icon_pens_alt',
			'icon_percent' => 'icon_percent',
			'icon_percent_alt' => 'icon_percent_alt',
			'icon_phone' => 'icon_phone',
			'icon_piechart' => 'icon_piechart',
			'icon_pin' => 'icon_pin',
			'icon_pin_alt' => 'icon_pin_alt',
			'icon_plus' => 'icon_plus',
			'icon_plus-box' => 'icon_plus-box',
			'icon_plus_alt' => 'icon_plus_alt',
			'icon_plus_alt2' => 'icon_plus_alt2',
			'icon_printer' => 'icon_printer',
			'icon_printer-alt' => 'icon_printer-alt',
			'icon_profile' => 'icon_profile',
			'icon_pushpin' => 'icon_pushpin',
			'icon_pushpin_alt' => 'icon_pushpin_alt',
			'icon_puzzle' => 'icon_puzzle',
			'icon_puzzle_alt' => 'icon_puzzle_alt',
			'icon_question' => 'icon_question',
			'icon_question_alt' => 'icon_question_alt',
			'icon_question_alt2' => 'icon_question_alt2',
			'icon_quotations' => 'icon_quotations',
			'icon_quotations_alt' => 'icon_quotations_alt',
			'icon_quotations_alt2' => 'icon_quotations_alt2',
			'icon_refresh' => 'icon_refresh',
			'icon_ribbon' => 'icon_ribbon',
			'icon_ribbon_alt' => 'icon_ribbon_alt',
			'icon_rook' => 'icon_rook',
			'icon_search' => 'icon_search',
			'icon_search-2' => 'icon_search-2',
			'icon_search_alt' => 'icon_search_alt',
			'icon_shield' => 'icon_shield',
			'icon_shield_alt' => 'icon_shield_alt',
			'icon_star' => 'icon_star',
			'icon_star-half' => 'icon_star-half',
			'icon_star-half_alt' => 'icon_star-half_alt',
			'icon_star_alt' => 'icon_star_alt',
			'icon_stop' => 'icon_stop',
			'icon_stop_alt' => 'icon_stop_alt',
			'icon_stop_alt2' => 'icon_stop_alt2',
			'icon_table' => 'icon_table',
			'icon_tablet' => 'icon_tablet',
			'icon_tag' => 'icon_tag',
			'icon_tag_alt' => 'icon_tag_alt',
			'icon_tags' => 'icon_tags',
			'icon_tags_alt' => 'icon_tags_alt',
			'icon_target' => 'icon_target',
			'icon_tool' => 'icon_tool',
			'icon_toolbox' => 'icon_toolbox',
			'icon_toolbox_alt' => 'icon_toolbox_alt',
			'icon_tools' => 'icon_tools',
			'icon_trash' => 'icon_trash',
			'icon_trash_alt' => 'icon_trash_alt',
			'icon_ul' => 'icon_ul',
			'icon_upload' => 'icon_upload',
			'icon_vol-mute' => 'icon_vol-mute',
			'icon_vol-mute_alt' => 'icon_vol-mute_alt',
			'icon_volume-high' => 'icon_volume-high',
			'icon_volume-high_alt' => 'icon_volume-high_alt',
			'icon_volume-low' => 'icon_volume-low',
			'icon_volume-low_alt' => 'icon_volume-low_alt',
			'icon_wallet' => 'icon_wallet',
			'icon_wallet_alt' => 'icon_wallet_alt',
			'icon_zoom-in' => 'icon_zoom-in',
			'icon_zoom-in_alt' => 'icon_zoom-in_alt',
			'icon_zoom-out' => 'icon_zoom-out',
			'icon_zoom-out_alt' => 'icon_zoom-out_alt',
			'social_blogger' => 'social_blogger',
			'social_blogger_circle' => 'social_blogger_circle',
			'social_blogger_square' => 'social_blogger_square',
			'social_delicious' => 'social_delicious',
			'social_delicious_circle' => 'social_delicious_circle',
			'social_delicious_square' => 'social_delicious_square',
			'social_deviantart' => 'social_deviantart',
			'social_deviantart_circle' => 'social_deviantart_circle',
			'social_deviantart_square' => 'social_deviantart_square',
			'social_dribbble' => 'social_dribbble',
			'social_dribbble_circle' => 'social_dribbble_circle',
			'social_dribbble_square' => 'social_dribbble_square',
			'social_facebook' => 'social_facebook',
			'social_facebook_circle' => 'social_facebook_circle',
			'social_facebook_square' => 'social_facebook_square',
			'social_flickr' => 'social_flickr',
			'social_flickr_circle' => 'social_flickr_circle',
			'social_flickr_square' => 'social_flickr_square',
			'social_googledrive' => 'social_googledrive',
			'social_googledrive_alt2' => 'social_googledrive_alt2',
			'social_googledrive_square' => 'social_googledrive_square',
			'social_googleplus' => 'social_googleplus',
			'social_googleplus_circle' => 'social_googleplus_circle',
			'social_googleplus_square' => 'social_googleplus_square',
			'social_instagram' => 'social_instagram',
			'social_instagram_circle' => 'social_instagram_circle',
			'social_instagram_square' => 'social_instagram_square',
			'social_linkedin' => 'social_linkedin',
			'social_linkedin_circle' => 'social_linkedin_circle',
			'social_linkedin_square' => 'social_linkedin_square',
			'social_myspace' => 'social_myspace',
			'social_myspace_circle' => 'social_myspace_circle',
			'social_myspace_square' => 'social_myspace_square',
			'social_picassa' => 'social_picassa',
			'social_picassa_circle' => 'social_picassa_circle',
			'social_picassa_square' => 'social_picassa_square',
			'social_pinterest' => 'social_pinterest',
			'social_pinterest_circle' => 'social_pinterest_circle',
			'social_pinterest_square' => 'social_pinterest_square',
			'social_rss' => 'social_rss',
			'social_rss_circle' => 'social_rss_circle',
			'social_rss_square' => 'social_rss_square',
			'social_share' => 'social_share',
			'social_share_circle' => 'social_share_circle',
			'social_share_square' => 'social_share_square',
			'social_skype' => 'social_skype',
			'social_skype_circle' => 'social_skype_circle',
			'social_skype_square' => 'social_skype_square',
			'social_spotify' => 'social_spotify',
			'social_spotify_circle' => 'social_spotify_circle',
			'social_spotify_square' => 'social_spotify_square',
			'social_stumbleupon_circle' => 'social_stumbleupon_circle',
			'social_stumbleupon_square' => 'social_stumbleupon_square',
			'social_tumbleupon' => 'social_tumbleupon',
			'social_tumblr' => 'social_tumblr',
			'social_tumblr_circle' => 'social_tumblr_circle',
			'social_tumblr_square' => 'social_tumblr_square',
			'social_twitter' => 'social_twitter',
			'social_twitter_circle' => 'social_twitter_circle',
			'social_twitter_square' => 'social_twitter_square',
			'social_vimeo' => 'social_vimeo',
			'social_vimeo_circle' => 'social_vimeo_circle',
			'social_vimeo_square' => 'social_vimeo_square',
			'social_wordpress' => 'social_wordpress',
			'social_wordpress_circle' => 'social_wordpress_circle',
			'social_wordpress_square' => 'social_wordpress_square',
			'social_youtube' => 'social_youtube',
			'social_youtube_circle' => 'social_youtube_circle',
			'social_youtube_square' => 'social_youtube_square'
		);
	}

	private function setSocialIconsArray() {

		$this->socialIcons = array(
			"" => "",
			"social_blogger" => "Blogger",
			"social_blogger_circle" => "Blogger circle",
			"social_blogger_square" => "Blogger square",
			"social_delicious" => "Delicious",
			"social_delicious_circle" => "Delicious circle",
			"social_delicious_square" => "Delicious square",
			"social_deviantart" => "Deviantart",
			"social_deviantart_circle" => "Deviantart circle",
			"social_deviantart_square" => "Deviantart square",
			"social_dribbble" => "Dribbble",
			"social_dribbble_circle" => "Dribbble circle",
			"social_dribbble_square" => "Dribbble square",
			"social_facebook" => "Facebook",
			"social_facebook_circle" => "Facebook circle",
			"social_facebook_square" => "Facebook square",
			"social_flickr" => "Flickr",
			"social_flickr_circle" => "Flickr circle",
			"social_flickr_square" => "Flickr square",
			"social_googledrive" => "Googledrive",
			"social_googledrive_alt2" => "Googledrive alt2",
			"social_googledrive_square" => "Googledrive square",
			"social_googleplus" => "Googleplus",
			"social_googleplus_circle" => "Googleplus circle",
			"social_googleplus_square" => "Googleplus square",
			"social_instagram" => "Instagram",
			"social_instagram_circle" => "Instagram circle",
			"social_instagram_square" => "Instagram square",
			"social_linkedin" => "Linkedin",
			"social_linkedin_circle" => "Linkedin circle",
			"social_linkedin_square" => "Linkedin square",
			"social_myspace" => "Myspace",
			"social_myspace_circle" => "myspace circle",
			"social_myspace_square" => "myspace square",
			"social_picassa" => "Picassa",
			"social_picassa_circle" => "Picassa circle",
			"social_picassa_square" => "Picassa square",
			"social_pinterest" => "Pinterest",
			"social_pinterest_circle" => "Pinterest circle",
			"social_pinterest_square" => "Pinterest square",
			"social_rss" => "Rss",
			"social_rss_circle" => "Rss circle",
			"social_rss_square" => "Rss square",
			"social_share" => "Share",
			"social_share_circle" => "Share circle",
			"social_share_square" => "Share square",
			"social_skype" => "Skype",
			"social_skype_circle" => "Skype circle",
			"social_skype_square" => "Skype square",
			"social_spotify" => "Spotify",
			"social_spotify_circle" => "Spotify circle",
			"social_spotify_square" => "Spotify square",
			"social_stumbleupon_circle" => "Stumbleupon circle",
			"social_stumbleupon_square" => "Stumbleupon square",
			"social_tumbleupon" => "Stumbleupon",
			"social_tumblr" => "Tumblr",
			"social_tumblr_circle" => "Tumblr circle",
			"social_tumblr_square" => "Tumblr square",
			"social_twitter" => "Twitter",
			"social_twitter_circle" => "Twitter circle",
			"social_twitter_square" => "Twitter square",
			"social_vimeo" => "Vimeo",
			"social_vimeo_circle" => "Vimeo circle",
			"social_vimeo_square" => "Vimeo square",
			"social_wordpress" => "Wordpress",
			"social_wordpress_circle" => "Wordpress circle",
			"social_wordpress_square" => "Wordpress square",
			"social_youtube" => "Youtube",
			"social_youtube_circle" => "Youtube circle",
			"social_youtube_square" => "Youtube square"
		);
	}

	public function getIconsArray() {
		return $this->icons;
	}

	public function getSocialIconsArray() {

		return $this->socialIcons;
	}

	public function getSocialIconsArrayVC() {
		return array_flip($this->getSocialIconsArray());
	}

	public function render($icon, $params = array()) {
		$html = '';
		extract($params);
		$iconAttributesString = '';
		$iconClass = '';
		if (isset($icon_attributes) && count($icon_attributes)) {
			foreach ($icon_attributes as $icon_attr_name => $icon_attr_val) {
				if ($icon_attr_name === 'class') {
					$iconClass = $icon_attr_val;
					unset($icon_attributes[$icon_attr_name]);
				} else {
					$iconAttributesString .= $icon_attr_name . '="' . $icon_attr_val . '" ';
				}
			}
		}

		if (isset($before_icon) && $before_icon !== '') {
			$beforeIconAttrString = '';
			if (isset($before_icon_attributes) && count($before_icon_attributes)) {
				foreach ($before_icon_attributes as $before_icon_attr_name => $before_icon_attr_val) {
					$beforeIconAttrString .= $before_icon_attr_name . '="' . $before_icon_attr_val . '" ';
				}
			}

			$html .= '<' . $before_icon . ' ' . $beforeIconAttrString . '>';
		}

		$html .= '<span aria-hidden="true" class="qode_icon_font_elegant ' . $icon . ' ' . $iconClass . '" ' . $iconAttributesString . '></span>';

		if (isset($before_icon) && $before_icon !== '') {
			$html .= '</' . $before_icon . '>';
		}

		return $html;
	}

	public function getSearchIcon($params = array()) {

		return $this->render('icon_search', $params);
	}

	public function getSearchClose($params = array()) {

		return $this->render('icon_close', $params);
	}

	public function getMenuSideIcon() {

		return $this->render('icon_menu');
	}

	public function getBackToTopIcon() {

		return $this->render('arrow_carrot-up ');
	}

	public function getMobileMenuIcon() {

		return $this->render('icon_menu');
	}

	public function getQuoteIcon() {

		return $this->render('icon_quotations');
	}

	public function getFacebookIcon() {

		return 'social_facebook';
	}

	public function getTwitterIcon() {

		return 'social_twitter';
	}

	public function getGooglePlusIcon() {

		return 'social_googleplus';
	}

	public function getLinkedInIcon() {

		return 'social_linkedin';
	}

	public function getTumblrIcon() {

		return 'social_tumblr ';
	}

	public function getPinterestIcon() {

		return 'social_pinterest';
	}

	public function getVKIcon() {

		return '';
	}

}


text:
<?php

namespace Symfony\Component\Security\Core\Exception;

/**
 * An authentication exception where you can control the message shown to the user.
 *
 * Be sure that the message passed to this exception is something that
 * can be shown safely to your user. In other words, avoid catching
 * other exceptions and passing their message directly to this class.
 *
 * @author Ryan Weaver <ryan@knpuniversity.com>
 */
class CustomUserMessageAuthenticationException extends AuthenticationException
{
    private $messageKey;

    private $messageData = array();

    public function __construct($message = '', array $messageData = array(), $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);

        $this->setSafeMessage($message, $messageData);
    }

    /**
     * Set a message that will be shown to the user.
     *
     * @param string $messageKey  The message or message key
     * @param array  $messageData Data to be passed into the translator
     */
    public function setSafeMessage($messageKey, array $messageData = array())
    {
        $this->messageKey = $messageKey;
        $this->messageData = $messageData;
    }

    public function getMessageKey()
    {
        return $this->messageKey;
    }

    public function getMessageData()
    {
        return $this->messageData;
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return serialize(array(
            parent::serialize(),
            $this->messageKey,
            $this->messageData,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($str)
    {
        list($parentData, $this->messageKey, $this->messageData) = unserialize($str);

        parent::unserialize($parentData);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="@string/prefs_personalization_category_title" >
        <com.yegorov.alexey.preferences.PreferenceList
            android:title="@string/prefs_model_title"
            android:summary="%s"
            android:key="@string/prefs_model_key"
            android:defaultValue="assets/models/R2-D2/R2-D2.dae"
            android:entries="@array/prefs_model_entries"
            android:entryValues="@array/prefs_model_values" />
    </PreferenceCategory>

</PreferenceScreen>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Jariangprasert, Archer, Elix & Anusarnsunthorn, Mycotaxon 85: 290 (2003)

#### Original name
Pertusaria alboaspera var. deficiens Jariangpr. & A.W. Archer

### Remarks
null


text:
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Reports;
using JetBrains.Annotations;
using Perfolizer.Mathematics.OutlierDetection;
using Xunit;

namespace BenchmarkDotNet.Tests.Engine
{
    public class EngineResultStageTests
    {
        [Fact]
        public void OutliersTest()
        {
            var measurements = new List<Measurement>();
            Add(measurements, 100);
            Add(measurements, 101);
            Add(measurements, 102);
            Add(measurements, 103);
            Add(measurements, 104);
            Add(measurements, 500); // It's an outlier

            CheckResults(5, measurements, OutlierMode.RemoveUpper);
            CheckResults(5, measurements, OutlierMode.RemoveAll);

            CheckResults(6, measurements, OutlierMode.DontRemove);
            CheckResults(6, measurements, OutlierMode.RemoveLower);
        }

        [AssertionMethod]
        private static void CheckResults(int expectedResultCount, List<Measurement> measurements, OutlierMode outlierMode)
        {
            Assert.Equal(expectedResultCount, new RunResults(null, measurements, outlierMode, default, default).GetMeasurements().Count());
        }

        private static void Add(List<Measurement> measurements, int time)
        {
            measurements.Add(new Measurement(1, IterationMode.Workload, IterationStage.Actual, measurements.Count + 1, 1, time));
        }
    }
}


text:
package com.google.security.zynamics.binnavi.Startup;

import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.API.plugins.IBatchPlugin;
import com.google.security.zynamics.binnavi.Plugins.IPluginRegistry;

/**
 * Contains code for executing batch plugins.
 */
public final class CBatchPluginExecuter {
  /**
   * You are not supposed to instantiate this.
   */
  private CBatchPluginExecuter() {
  }

  /**
   * Executes a batch plugin. This can be used to start BinNavi in batch mode and just execute a
   * plugin.
   *
   * @param pluginName The name of the plugin.
   * @param pluginRegistry The plugin registry that holds all active plugins.
   */
  public static <T> void execute(final String pluginName,
      final IPluginRegistry<com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T>> pluginRegistry) {
    for (final com.google.security.zynamics.binnavi.api2.plugins.IPlugin<T> plugin : pluginRegistry) {
      if ((plugin instanceof IBatchPlugin) && plugin.getName().equals(pluginName)) {
        // ESCA-JAVA0166:
        try {
          ((IBatchPlugin) plugin).run();
        } catch (final Exception exception) {
          CUtilityFunctions.logException(exception);

          return;
        }
      }
    }
  }

}


text:
<!DOCTYPE HTML>

  <title>voice-commands.js</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">

    You need to allow access to your microphone.

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>

Demo

Github

 0">

 2">

Ready to use voice-commands.js? Just say "go to github"

 1">

Hi {{name}}! Nice to meet you.

Let's use some commands. Say "open nav"

 0">

Great, thanks.

What's your name?

(just start talking back)

        Here's what I'm hearing:

{{result.transcript}} ({{(result.confidence * 100).toFixed(0)}}%)

 0" href="https://github.com/jimmybyrum/voice-commands.js">


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using Microsoft.VisualStudio.Shell.Interop;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;

namespace Microsoft.VisualStudioTools.Project.Automation
{
    /// <summary>
    /// Helper class that handle the scope of an automation function.
    /// It should be used inside a "using" directive to define the scope of the
    /// automation function and make sure that the ExitAutomation method is called.
    /// </summary>
    internal sealed class AutomationScope : IDisposable
    {
        private IVsExtensibility3 extensibility;
        private bool inAutomation;
        private bool isDisposed;

        /// <summary>
        /// Defines the beginning of the scope of an automation function. This constuctor
        /// calls EnterAutomationFunction to signal the Shell that the current function is
        /// changing the status of the automation objects.
        /// </summary>
        public AutomationScope(IServiceProvider provider)
        {
            Utilities.ArgumentNotNull(nameof(provider), provider);

            this.extensibility = provider.GetService(typeof(EnvDTE.IVsExtensibility)) as IVsExtensibility3;
            if (null == this.extensibility)
            {
                throw new InvalidOperationException();
            }
            ErrorHandler.ThrowOnFailure(this.extensibility.EnterAutomationFunction());
            this.inAutomation = true;
        }

        /// <summary>
        /// Ends the scope of the automation function. This function is also called by the
        /// Dispose method.
        /// </summary>
        public void ExitAutomation()
        {
            if (this.inAutomation)
            {
                ErrorHandler.ThrowOnFailure(this.extensibility.ExitAutomationFunction());
                this.inAutomation = false;
            }
        }

        /// <summary>
        /// Gets the IVsExtensibility3 interface used in the automation function.
        /// </summary>
        public IVsExtensibility3 Extensibility => this.extensibility;
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        #region IDisposable Members
        private void Dispose(bool disposing)
        {
            if (!this.isDisposed)
            {
                if (disposing)
                {
                    ExitAutomation();
                }

                this.isDisposed = true;
            }
        }
        #endregion
    }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser.framehost;

import org.chromium.base.UnguessableToken;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content_public.browser.RenderFrameHost;
import org.chromium.mojo.system.impl.CoreImpl;
import org.chromium.services.service_manager.InterfaceProvider;

/**
 * The RenderFrameHostImpl Java wrapper to allow communicating with the native RenderFrameHost
 * object.
 */
@JNINamespace("content")
public class RenderFrameHostImpl implements RenderFrameHost {
    private long mNativeRenderFrameHostAndroid;
    // mDelegate can be null.
    private final RenderFrameHostDelegate mDelegate;
    private final boolean mIncognito;
    private final InterfaceProvider mInterfaceProvider;

    private RenderFrameHostImpl(long nativeRenderFrameHostAndroid, RenderFrameHostDelegate delegate,
            boolean isIncognito, int nativeInterfaceProviderHandle) {
        mNativeRenderFrameHostAndroid = nativeRenderFrameHostAndroid;
        mDelegate = delegate;
        mIncognito = isIncognito;
        mInterfaceProvider =
                new InterfaceProvider(CoreImpl.getInstance()
                                              .acquireNativeHandle(nativeInterfaceProviderHandle)
                                              .toMessagePipeHandle());
    }

    @CalledByNative
    private static RenderFrameHostImpl create(long nativeRenderFrameHostAndroid,
            RenderFrameHostDelegate delegate, boolean isIncognito,
            int nativeInterfaceProviderHandle) {
        return new RenderFrameHostImpl(
                nativeRenderFrameHostAndroid, delegate, isIncognito, nativeInterfaceProviderHandle);
    }

    @CalledByNative
    private void clearNativePtr() {
        mNativeRenderFrameHostAndroid = 0;
    }

    /**
     * Get the delegate associated with this RenderFrameHost.
     *
     * @return The delegate associated with this RenderFrameHost.
     */
    public RenderFrameHostDelegate getRenderFrameHostDelegate() {
        return mDelegate;
    }

    @Override
    public String getLastCommittedURL() {
        if (mNativeRenderFrameHostAndroid == 0) return null;
        return nativeGetLastCommittedURL(mNativeRenderFrameHostAndroid);
    }

    @Override
    public InterfaceProvider getRemoteInterfaces() {
        return mInterfaceProvider;
    }

    /**
     * Returns whether we're in incognito mode.
     *
     * TODO(timloh): This function shouldn't really be on here. If we end up
     * needing more logic from the native BrowserContext, we should add a
     * wrapper for that and move this function there.
     */
    public boolean isIncognito() {
        return mIncognito;
    }

    /**
     * Return the AndroidOverlay routing token for this RenderFrameHostImpl.
     */
    public UnguessableToken getAndroidOverlayRoutingToken() {
        if (mNativeRenderFrameHostAndroid == 0) return null;
        return nativeGetAndroidOverlayRoutingToken(mNativeRenderFrameHostAndroid);
    }

    private native String nativeGetLastCommittedURL(long nativeRenderFrameHostAndroid);
    private native UnguessableToken nativeGetAndroidOverlayRoutingToken(
            long nativeRenderFrameHostAndroid);
}


text:
package com.tritondigital.counters

import _root_.akka.util.ByteString

import scala.runtime.ScalaRunTime

object Metric {
  private [this] val validCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-_./"
  private [this] val validCharacterSet = validCharacters.toSet
  private [this] val validationMessage = s"Metrics and tags can only contain characters among '$validCharacters': "

  def apply(name: String, value: Long, tags: Seq[Tag]): Metric =
    Metric(name, LongValue(value), tags)
  def apply(name: String, value: Double, tags: Seq[Tag]): Metric =
    Metric(name, DoubleValue(value), tags)
  def apply(name: String, value: Long): Metric =
    Metric(name, LongValue(value))
  def apply(name: String, value: Double): Metric =
    Metric(name, DoubleValue(value))

  def validate(metricOrTagName: String) {
    require(metricOrTagName.forall(validCharacters.contains(_)), validationMessage + metricOrTagName)
  }

  /**
   * Clean a metric or tag name in order to be compatible with all publishers.
   * @return a normalized metric / tag name.
   */
  def clean(metricOrTagName: String) =
    metricOrTagName.filter(validCharacterSet.contains)
}

/**
 * A metrics suitable for ingestion in a Datadog time series database. Although it can in theory be published anywhere, this is closely modeled after OpenTSDB metric model and binary protocol.
 */
case class Metric(name: String, value: MetricValue, tags: Seq[Tag] = Nil, tstamp: Long = (System.currentTimeMillis() / 1000L)) {
  require(tags.size <= 8, s"Cannot create metrics with more than 8 tags: ${tags.map { case Tag(k,v) => s"$k=$v" }.mkString(", ")}")
  Metric.validate(name)
  Metric.validate(name)

  // See http://docs.datadoghq.com/guides/dogstatsd/#datagram-format
  private [counters] val toDatadogBytes = {
    val tagsStr = tags.map { case Tag(k, v) => s"$k:$v" }.mkString(",")
    val tagsSection =
      if (tagsStr.isEmpty) tagsStr
      else "|#" + tagsStr

    ByteString(s"$name:${value.toDatadogString}|g$tagsSection")
  }

  private [counters] lazy val key = MetricKey(name, tags)
}

sealed trait MetricValue {
  def toDatadogString: String
  def toDouble: Double
}

case class LongValue(value: Long) extends MetricValue {
  val toDatadogString = value.toString
  val toDouble = value.toDouble
}

case class DoubleValue(value: Double) extends MetricValue {
  val toDatadogString = value.toString
  val toDouble = value
}

private [counters] case class MetricKey(name: String, tags: Seq[Tag]) {
  // Since this class is expressly designed to serve has a HashMap key, cache the hashCode immediately, so it does not get recomputed over and over again.
  override val hashCode = ScalaRunTime._hashCode(this)
}