text:
<?php

namespace Magento\Swatches\Test\Unit\Helper;

class DataTest extends \PHPUnit_Framework_TestCase
{
    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Helper\Image */
    protected $imageHelperMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory */
    protected $productCollectionFactoryMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Product\Collection */
    protected $productCollectionMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\ConfigurableProduct\Model\Product\Type\Configurable */
    protected $configurableMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ProductFactory */
    protected $productModelFactoryMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product */
    protected $productMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Store\Model\StoreManager */
    protected $storeManagerMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory */
    protected $swatchCollectionFactoryMock;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\ResourceModel\Eav\Attribute */
    protected $attributeMock;

    /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */
    protected $objectManager;

    /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager|\Magento\Swatches\Helper\Data */
    protected $swatchHelperObject;

    /** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Api\ProductRepositoryInterface */
    protected $productRepoMock;

    protected function setUp()
    {
        $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->imageHelperMock = $this->getMock('\Magento\Catalog\Helper\Image', [], [], '', false);
        $this->productCollectionFactoryMock = $this->getMock(
            '\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );

        $this->productMock = $this->getMock('\Magento\Catalog\Model\Product', [], [], '', false);

        $this->productCollectionMock = $this->objectManager->getCollectionMock(
            '\Magento\Catalog\Model\ResourceModel\Product\Collection',
            [
                $this->productMock,
                $this->productMock,
            ]
        );

        $this->configurableMock = $this->getMock(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable',
            [],
            [],
            '',
            false
        );
        $this->productModelFactoryMock = $this->getMock(
            '\Magento\Catalog\Model\ProductFactory',
            ['create'],
            [],
            '',
            false
        );

        $this->productRepoMock = $this->getMock('\Magento\Catalog\Api\ProductRepositoryInterface', [], [], '', false);

        $this->storeManagerMock = $this->getMock('\Magento\Store\Model\StoreManager', [], [], '', false);
        $this->swatchCollectionFactoryMock = $this->getMock(
            '\Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory',
            ['create'],
            [],
            '',
            false
        );

        $this->attributeMock = $this->getMock('\Magento\Catalog\Model\ResourceModel\Eav\Attribute', [], [], '', false);

        $this->swatchHelperObject = $this->objectManager->getObject(
            '\Magento\Swatches\Helper\Data',
            [
                'productCollectionFactory' => $this->productCollectionFactoryMock,
                'configurable' => $this->configurableMock,
                'productRepository' => $this->productRepoMock,
                'storeManager' => $this->storeManagerMock,
                'swatchCollectionFactory' => $this->swatchCollectionFactoryMock,
                'imageHelper' => $this->imageHelperMock,
            ]
        );
    }

    public function dataForAdditionalData()
    {
        $additionalData = [
            'swatch_input_type' => 'visual',
            'update_product_preview_image' => 1,
            'use_product_image_for_swatch' => 0
        ];
        return [
            [
                serialize($additionalData),
                [
                    'getData' => 1,
                    'setData' => 3,
                ]
            ],
            [
                null,
                [
                    'getData' => 1,
                    'setData' => 0,
                ]
            ],
        ];
    }

    /**
     * @dataProvider dataForAssembleEavAttribute
     */
    public function testAssembleAdditionalDataEavAttribute($dataFromDb, $attributeData)
    {
        $this->attributeMock
            ->expects($this->at(0))
            ->method('getData')
            ->with('additional_data')
            ->will($this->returnValue($dataFromDb));

        $i = 1;
        foreach ($attributeData as $key => $value) {
            $this->attributeMock
                ->expects($this->at($i))
                ->method('getData')
                ->with($key)
                ->willReturn($value);
            $i++;
        }

        $this->attributeMock->expects($this->once())->method('setData');

        $this->swatchHelperObject->assembleAdditionalDataEavAttribute($this->attributeMock);
    }

    public function dataForAssembleEavAttribute()
    {
        $additionalData = [
            'swatch_input_type' => 'visual',
            'update_product_preview_image' => 1,
            'use_product_image_for_swatch' => 0
        ];
        return [
            [
                serialize($additionalData),
                [
                    'swatch_input_type' => 'visual',
                    'update_product_preview_image' => 1,
                    'use_product_image_for_swatch' => 1,
                ],
            ],
            [
                null,
                [
                    'swatch_input_type' => null,
                    'update_product_preview_image' => 0,
                    'use_product_image_for_swatch' => 0,
                ],
            ],
        ];
    }

    /**
     * @dataProvider dataForVariationWithSwatchImage
     */
    public function testLoadFirstVariationWithSwatchImage($imageTypes, $expected, $requiredAttributes)
    {
        $this->getSwatchAttributes($this->productMock);
        $this->getUsedProducts($imageTypes + $requiredAttributes);

        $result = $this->swatchHelperObject->loadFirstVariationWithSwatchImage($this->productMock, $requiredAttributes);

        if ($expected === false) {
            $this->assertFalse($result);
        } else {
            $this->assertInstanceOf('\Magento\Catalog\Model\Product', $result);
        }
    }

    public function dataForVariationWithSwatchImage()
    {
        return [
            [
                [
                    'image' => '/m/a/magento.png',
                    'small_image' => '/m/a/magento.png',
                    'thumbnail' => '/m/a/magento.png',
                    'swatch_image' => '/m/a/magento.png', //important
                ],
                '\Magento\Catalog\Model\Product',
                ['color' => 31]
            ],
            [
                [
                    'image' => '/m/a/magento.png',
                    'small_image' => '/m/a/magento.png',
                    'thumbnail' => '/m/a/magento.png',
                ],
                false,
                ['size' => 31]
            ],
        ];
    }

    /**
     * @dataProvider dataForCreateSwatchProductByFallback
     */
    public function testLoadVariationByFallback($product)
    {
        $this->getSwatchAttributes($product);

        $this->prepareVariationCollection();

        $this->productCollectionMock->method('getFirstItem')->willReturn($this->productMock);
        $this->productMock->method('getId')->willReturn(95);
        $this->productModelFactoryMock->method('create')->willReturn($this->productMock);
        $this->productMock->method('load')->with(95)->will($this->returnSelf());

        $this->swatchHelperObject->loadVariationByFallback($this->productMock, ['color' => 31]);
    }

    /**
     * @dataProvider dataForVariationWithImage
     */
    public function testLoadFirstVariationWithImage($imageTypes, $expected, $requiredAttributes)
    {
        $this->getSwatchAttributes($this->productMock);
        $this->getUsedProducts($imageTypes + $requiredAttributes);

        $result = $this->swatchHelperObject->loadFirstVariationWithImage($this->productMock, $requiredAttributes);

        if ($expected === false) {
            $this->assertFalse($result);
        } else {
            $this->assertInstanceOf('\Magento\Catalog\Model\Product', $result);
        }
    }

    public function dataForVariationWithImage()
    {
        return [
            [
                [
                    'image' => '/m/a/magento.png', //important
                    'small_image' => '/m/a/magento.png',
                    'thumbnail' => '/m/a/magento.png',
                    'swatch_image' => '/m/a/magento.png',
                ],
                '\Magento\Catalog\Model\Product',
                ['color' => 31]
            ],
            [
                [
                    'small_image' => '/m/a/magento.png',
                    'thumbnail' => '/m/a/magento.png',
                    'swatch_image' => '/m/a/magento.png',
                ],
                false,
                ['size' => 31]
            ],
        ];
    }

    public function testLoadFirstVariationWithImageNoProduct()
    {
        $result = $this->swatchHelperObject->loadVariationByFallback($this->productMock, ['color' => 31]);
        $this->assertFalse($result);
    }

    public function testLoadVariationByFallbackWithoutProduct()
    {
        $result = $this->swatchHelperObject->loadFirstVariationWithImage($this->productMock, ['color' => 31]);
        $this->assertFalse($result);
    }

    /**
     * @dataProvider dataForMediaGallery
     */
    public function testGetProductMediaGallery($mediaGallery, $image)
    {
        $this->productMock->expects($this->once())->method('getMediaAttributeValues')->willReturn($mediaGallery);
        $this->productMock->expects($this->any())->method('getId')->willReturn(95);

        $this->imageHelperMock->expects($this->any())
            ->method('init')
            ->willReturnMap([
                [$this->productMock, 'product_page_image_large', [], $this->imageHelperMock],
                [$this->productMock, 'product_page_image_medium', [], $this->imageHelperMock],
                [$this->productMock, 'product_page_image_small', [], $this->imageHelperMock],
            ]);

        $this->imageHelperMock->expects($this->any())
            ->method('setImageFile')
            ->with($image)
            ->willReturnSelf();
        $this->imageHelperMock->expects($this->any())
            ->method('constrainOnly')
            ->willReturnSelf();
        $this->imageHelperMock->expects($this->any())
            ->method('keepAspectRatio')
            ->willReturnSelf();
        $this->imageHelperMock->expects($this->any())
            ->method('keepFrame')
            ->willReturnSelf();
        $this->imageHelperMock->expects($this->any())
            ->method('getUrl')
            ->willReturn('http://full_path_to_image/magento1.png');

        $this->productRepoMock->expects($this->any())
            ->method('getById')
            ->with(95)
            ->willReturn($this->productMock);

        $mediaObject = $this->getMock('\Magento\Framework\DataObject', [], [], '', false);
        $iterator = new \ArrayIterator([$mediaObject]);
        $mediaCollectionMock = $this->getMock('\Magento\Framework\Data\Collection', [], [], '', false);
        $mediaCollectionMock->expects($this->any())->method('getIterator')->willReturn($iterator);
        $mediaObject->method('getData')->withConsecutive(
            ['value_id'],
            ['file']
        )->willReturnOnConsecutiveCalls(
            0,
            $image
        );
        $this->productMock->method('getMediaGalleryImages')->willReturn($mediaCollectionMock);

        $this->swatchHelperObject->getProductMediaGallery($this->productMock);
    }

    public function dataForMediaGallery()
    {
        return [
            [
                [
                    'image' => '/m/a/magento1.png',
                    'small_image' => '/m/a/magento2.png',
                    'thumbnail' => '/m/a/magento3.png',
                    'swatch_image' => '/m/a/magento4.png',
                ],
                '/m/a/magento1.png'
            ],
            [
                [
                    'small_image' => '/m/a/magento4.png',
                    'thumbnail' => '/m/a/magento5.png',
                    'swatch_image' => '/m/a/magento6.png',
                ],
                '/m/a/magento4.png'
            ],
            [
                [],
                ''
            ],
        ];
    }

    protected function getSwatchAttributes()
    {
        $this->getAttributesFromConfigurable();
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(true);
        $this->attributeMock->method('getData')->with('swatch_input_type')->willReturn('visual');
    }

    protected function getUsedProducts(array $attributes)
    {
        $this->productMock
            ->expects($this->atLeastOnce())
            ->method('getTypeInstance')
            ->willReturn($this->configurableMock);

        $product1 = $this->getMock('\Magento\Catalog\Model\Product', ['hasData'], [], '', false);
        $product1->setData($attributes);

        $product2 = $this->getMock('\Magento\Catalog\Model\Product', ['hasData'], [], '', false);
        $product2->setData($attributes);

        $simpleProducts = [$product2, $product1];

        $this->configurableMock->expects($this->once())->method('getUsedProducts')->with($this->productMock)
            ->willReturn($simpleProducts);

    }

    protected function getAttributesFromConfigurable()
    {
        $this->productMock
            ->expects($this->atLeastOnce())
            ->method('getTypeInstance')
            ->willReturn($this->configurableMock);

        $confAttribute = $this->getMock(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute',
            [],
            [],
            '',
            false
        );

        $this->configurableMock
            ->expects($this->any())
            ->method('getConfigurableAttributes')
            ->with($this->productMock)
            ->willReturn([$confAttribute, $confAttribute]);

        $confAttribute
            ->expects($this->any())
            ->method('__call')
            ->with('getProductAttribute')
            ->willReturn($this->attributeMock);
    }

    protected function prepareVariationCollection()
    {
        $this->productCollectionFactoryMock
            ->expects($this->any())
            ->method('create')
            ->willReturn($this->productCollectionMock);

        $this->addfilterByParent();
    }

    protected function addfilterByParent()
    {
        $this->productCollectionMock
            ->method('getTable')
            ->with('catalog_product_relation')
            ->willReturn('catalog_product_relation');

        $zendDbSelectMock = $this->getMock('Magento\Framework\DB\Select', [], [], '', false);

        $this->productCollectionMock->method('getSelect')->willReturn($zendDbSelectMock);
        $zendDbSelectMock->method('join')->willReturn($zendDbSelectMock);
        $zendDbSelectMock->method('where')->willReturn($zendDbSelectMock);
    }

    public function dataForCreateSwatchProduct()
    {
        $productMock = $this->getMock('\Magento\Catalog\Model\Product', [], [], '', false);

        return [
            [
                $productMock,
                [
                    'image' => '',
                    'small_image' => '',
                    'thumbnail' => '',
                    'swatch_image' => '',
                ]
            ],
            [
                $productMock,
                [
                    'small_image' => 'img1.png',
                    'thumbnail' => 'img1.png',
                ]
            ],
            [
                $productMock,
                []
            ],
            [
                $productMock,
                [
                    'image' => 'img1.png',
                    'small_image' => 'img1.png',
                    'thumbnail' => 'img1.png',
                ]
            ],
        ];
    }

    public function dataForCreateSwatchProductByFallback()
    {
        $productMock = $this->getMock('\Magento\Catalog\Model\Product', [], [], '', false);

        return [
            [
                95,
            ],
            [
                $productMock,
            ],
        ];
    }

    /**
     * @dataProvider dataForGettingSwatchAsArray
     */
    public function testGetSwatchAttributesAsArray($optionsArray, $attributeData, $expected)
    {
        $configurable = $this->getMock(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable',
            [],
            [],
            '',
            false
        );

        $this->productMock
            ->expects($this->atLeastOnce())
            ->method('getTypeInstance')
            ->willReturn($configurable);

        $confAttribute = $this->getMock(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute',
            [],
            [],
            '',
            false
        );

        $configurable
            ->expects($this->atLeastOnce())
            ->method('getConfigurableAttributes')
            ->with($this->productMock)
            ->willReturn([$confAttribute]);

        $confAttribute
            ->expects($this->atLeastOnce())
            ->method('__call')
            ->with('getProductAttribute')
            ->willReturn($this->attributeMock);

        $this->attributeMock->method('setStoreId')->will($this->returnSelf());
        $storeMock = $this->getMock('\Magento\Store\Model\Store', [], [], '', false);
        $storeMock->method('getId')->willReturn(1);
        $this->storeManagerMock->method('getStore')->willReturn($storeMock);

        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(true);
        $this->attributeMock->expects($this->at(1))->method('getData')->with('swatch_input_type')->willReturn('visual');
        $this->attributeMock->expects($this->at(3))->method('getData')->with('')->willReturn($attributeData);

        $sourceMock = $this->getMock('\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource', [], [], '', false);
        $sourceMock->expects($this->any())->method('getAllOptions')->with(false)->willReturn($optionsArray);
        $this->attributeMock->method('getSource')->willReturn($sourceMock);

        $result = $this->swatchHelperObject->getSwatchAttributesAsArray($this->productMock);
        $this->assertEquals($result, $expected);
    }

    public function dataForGettingSwatchAsArray()
    {
        return [
            [
                [
                    ['value' => 45, 'label' => 'green'],
                    ['value' => 46, 'label' => 'yellow'],
                    ['value' => 47, 'label' => 'red'],
                    ['value' => 48, 'label' => 'blue'],
                ],
                [
                    'attribute_id' => 52
                ],
                [
                    52 => [
                        'attribute_id' => 52,
                        'options' => [
                            45 => 'green',
                            46 => 'yellow',
                            47 => 'red',
                            48 => 'blue',
                        ],
                    ]
                ],
            ],
            [
                [
                    ['value' => 45, 'label' => 'green'],
                    ['value' => 46, 'label' => 'yellow'],
                ],
                [
                    'attribute_id' => 324
                ],
                [
                    324 => [
                        'attribute_id' => 324,
                        'options' => [
                            45 => 'green',
                            46 => 'yellow',
                        ],
                    ]
                ],
            ],
        ];
    }

    public function testGetSwatchesByOptionsIdIf1()
    {
        $swatchMock = $this->getMock('\Magento\Swatches\Model\Swatch', [], [], '', false);

        $optionsData = [
            [
                'type' => 1,
                'store_id' => 1,
                'value' => '#324234',
                'option_id' => 35,
                'id' => 423,
            ],
        ];

        $swatchMock->expects($this->at(0))->method('offsetGet')->with('type')->willReturn(1);
        $swatchMock->expects($this->at(1))->method('offsetGet')->with('option_id')->willReturn(35);
        $swatchMock->expects($this->at(2))->method('getData')->with('')->willReturn($optionsData[0]);

        $swatchCollectionMock = $this->objectManager->getCollectionMock(
            '\Magento\Swatches\Model\ResourceModel\Swatch\Collection',
            [
                $swatchMock,
            ]
        );
        $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock);

        $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf());

        $storeMock = $this->getMock('\Magento\Store\Model\Store', [], [], '', false);
        $this->storeManagerMock->method('getStore')->willReturn($storeMock);
        $storeMock->method('getId')->willReturn(1);

        $this->swatchHelperObject->getSwatchesByOptionsId([35]);
    }

    public function testGetSwatchesByOptionsIdIf2()
    {
        $swatchMock = $this->getMock('\Magento\Swatches\Model\Swatch', [], [], '', false);

        $optionsData = [
            [
                'type' => 0,
                'store_id' => 1,
                'value' => 'test',
                'option_id' => 35,
                'id' => 487,
            ],
            [
                'type' => 0,
                'store_id' => 1,
                'value' => 'test2',
                'option_id' => 36,
                'id' => 488,
            ]
        ];

        $swatchMock->expects($this->at(0))->method('offsetGet')->with('type')->willReturn(0);
        $swatchMock->expects($this->at(1))->method('offsetGet')->with('store_id')->willReturn(1);
        $swatchMock->expects($this->at(2))->method('offsetGet')->with('value')->willReturn('test');
        $swatchMock->expects($this->at(3))->method('offsetGet')->with('option_id')->willReturn(35);
        $swatchMock->expects($this->at(4))->method('getData')->with('')->willReturn($optionsData[0]);
        $swatchMock->expects($this->at(5))->method('offsetGet')->with('type')->willReturn(0);
        $swatchMock->expects($this->at(6))->method('offsetGet')->with('store_id')->willReturn(1);
        $swatchMock->expects($this->at(7))->method('offsetGet')->with('value')->willReturn('test2');
        $swatchMock->expects($this->at(8))->method('offsetGet')->with('option_id')->willReturn(36);
        $swatchMock->expects($this->at(9))->method('getData')->with('')->willReturn($optionsData[1]);

        $swatchCollectionMock = $this->objectManager->getCollectionMock(
            '\Magento\Swatches\Model\ResourceModel\Swatch\Collection',
            [
                $swatchMock,
                $swatchMock,
            ]
        );
        $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock);

        $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf());

        $storeMock = $this->getMock('\Magento\Store\Model\Store', [], [], '', false);
        $this->storeManagerMock->method('getStore')->willReturn($storeMock);
        $storeMock->method('getId')->willReturn(1);

        $this->swatchHelperObject->getSwatchesByOptionsId([35]);
    }

    public function testGetSwatchesByOptionsIdIf3()
    {
        $swatchMock = $this->getMock('\Magento\Swatches\Model\Swatch', [], [], '', false);

        $optionsData = [
            'type' => 0,
            'store_id' => 0,
            'value' => 'test_test',
            'option_id' => 35,
            'id' => 423,
        ];

        $swatchMock->expects($this->at(0))->method('offsetGet')->with('type')->willReturn(0);
        $swatchMock->expects($this->at(1))->method('offsetGet')->with('store_id')->willReturn(0);
        $swatchMock->expects($this->at(2))->method('offsetGet')->with('store_id')->willReturn(0);
        $swatchMock->expects($this->at(3))->method('offsetGet')->with('option_id')->willReturn(35);
        $swatchMock->expects($this->at(4))->method('getData')->with('')->willReturn($optionsData);

        $swatchCollectionMock = $this->objectManager->getCollectionMock(
            '\Magento\Swatches\Model\ResourceModel\Swatch\Collection',
            [
                $swatchMock,
            ]
        );
        $this->swatchCollectionFactoryMock->method('create')->willReturn($swatchCollectionMock);

        $swatchCollectionMock->method('addFilterByOptionsIds')->with([35])->will($this->returnSelf());

        $storeMock = $this->getMock('\Magento\Store\Model\Store', [], [], '', false);
        $this->storeManagerMock->method('getStore')->willReturn($storeMock);
        $storeMock->method('getId')->willReturn(1);

        $this->swatchHelperObject->getSwatchesByOptionsId([35]);
    }

    public function testIsProductHasSwatch()
    {
        $this->getSwatchAttributes();
        $result = $this->swatchHelperObject->isProductHasSwatch($this->productMock);
        $this->assertEquals(2, $result);
    }

    /**
     * @dataProvider dataIsVisualSwatch
     */
    public function testIsVisualSwatch($swatchType, $boolResult)
    {
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(true);
        $this->attributeMock
            ->expects($this->once())
            ->method('getData')
            ->with('swatch_input_type')
            ->willReturn($swatchType);
        $result = $this->swatchHelperObject->isVisualSwatch($this->attributeMock);
        if ($boolResult) {
            $this->assertTrue($result);
        } else {
            $this->assertFalse($result);
        }
    }

    public function dataIsVisualSwatch()
    {
        return [
            [
                'visual',
                true,
            ],
            [
                'some_other_type',
                false,
            ],
        ];
    }

    /**
     * @dataProvider dataForIsVisualSwatchType
     */
    public function testIsVisualSwatchFalse($data, $count, $swatchType, $boolResult)
    {
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(false);

        $this->attributeMock->expects($this->exactly(2))->method('getData')->withConsecutive(
            ['additional_data'],
            ['swatch_input_type']
        )->willReturnOnConsecutiveCalls(
            $data,
            $swatchType
        );

        $this->attributeMock
            ->expects($this->exactly($count['setData']))
            ->method('setData');

        $result = $this->swatchHelperObject->isVisualSwatch($this->attributeMock);
        if ($boolResult) {
            $this->assertTrue($result);
        } else {
            $this->assertFalse($result);
        }
    }

    public function dataForIsVisualSwatchType()
    {
        $additionalData = [
            'swatch_input_type' => 'visual',
            'update_product_preview_image' => 1,
            'use_product_image_for_swatch' => 0
        ];
        return [
            [
                serialize($additionalData),
                [
                    'getData' => 1,
                    'setData' => 3,
                ],
                'visual',
                true,
            ],
            [
                null,
                [
                    'getData' => 1,
                    'setData' => 0,
                ],
                'some_other_type',
                false,
            ],
        ];
    }

    /**
     * @dataProvider dataForIsTextSwatchType
     */
    public function testIsTextSwatchFalse($data, $count, $swatchType, $boolResult)
    {
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(false);

        $this->attributeMock->expects($this->exactly(2))->method('getData')->withConsecutive(
            ['additional_data'],
            ['swatch_input_type']
        )->willReturnOnConsecutiveCalls(
            $data,
            $swatchType
        );

        $this->attributeMock
            ->expects($this->exactly($count['setData']))
            ->method('setData');

        $result = $this->swatchHelperObject->isTextSwatch($this->attributeMock);
        if ($boolResult) {
            $this->assertTrue($result);
        } else {
            $this->assertFalse($result);
        }
    }

    public function dataForIsTextSwatchType()
    {
        $additionalData = [
            'swatch_input_type' => 'text',
            'update_product_preview_image' => 1,
            'use_product_image_for_swatch' => 0
        ];
        return [
            [
                serialize($additionalData),
                [
                    'getData' => 1,
                    'setData' => 3,
                ],
                'text',
                true,
            ],
            [
                null,
                [
                    'getData' => 1,
                    'setData' => 0,
                ],
                'some_other_type',
                false,
            ],
        ];
    }

    /**
     * @dataProvider dataIsTextSwatch
     */
    public function testIsTextSwatch($swatchType, $boolResult)
    {
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(true);
        $this->attributeMock
            ->expects($this->once())
            ->method('getData')
            ->with('swatch_input_type')
            ->willReturn($swatchType);
        $result = $this->swatchHelperObject->isTextSwatch($this->attributeMock);
        if ($boolResult) {
            $this->assertTrue($result);
        } else {
            $this->assertFalse($result);
        }
    }

    public function dataIsTextSwatch()
    {
        return [
            [
                'text',
                true,
            ],
            [
                'some_other_type',
                false,
            ],
        ];
    }

    /**
     * @dataProvider dataIsSwatchAttribute
     */
    public function testIsSwatchAttribute($times, $swatchType, $boolResult)
    {
        $this->attributeMock->method('hasData')->with('swatch_input_type')->willReturn(true);
        $this->attributeMock
            ->expects($this->exactly($times))
            ->method('getData')
            ->with('swatch_input_type')
            ->willReturn($swatchType);

        $result = $this->swatchHelperObject->isSwatchAttribute($this->attributeMock);
        if ($boolResult) {
            $this->assertTrue($result);
        } else {
            $this->assertFalse($result);
        }
    }

    public function dataIsSwatchAttribute()
    {
        return [
            [
                1,
                'visual',
                true,
            ],
            [
                2,
                'text',
                true,
            ],
            [
                2,
                'some_other_type',
                false,
            ],
        ];
    }
}


text:
package org.apache.tika.language.translate;

import org.apache.tika.exception.TikaException;

import java.io.IOException;

/**
 * Interface for Translator services.
 * @since Tika 1.6
 */
public interface Translator {
    /**
     * Translate text between given languages.
     * @param text The text to translate.
     * @param sourceLanguage The input text language (for example, "en").
     * @param targetLanguage The desired language to translate to (for example, "fr").
     * @return The translation result. If translation is unavailable, returns the same text back.
     * @throws TikaException When there is an error translating.
     * @throws java.io.IOException
     * @since Tika 1.6
     */
    public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException;

    /**
     * Translate text to the given language
     * This method attempts to auto-detect the source language of the text.
     * @param text The text to translate.
     * @param targetLanguage The desired language to translate to (for example, "hi").
     * @return The translation result. If translation is unavailable, returns the same text back.
     * @throws TikaException When there is an error translating.
     * @throws java.io.IOException
     * @since Tika 1.6
     */
    public String translate(String text, String targetLanguage) throws TikaException, IOException;

    /**
     * @return true if this Translator is probably able to translate right now.
     * @since Tika 1.6
     */
    public boolean isAvailable();
}

redpajama_set_name: RedPajamaGithub


text:
package ol;

import jsinterop.annotations.JsProperty;

import jsinterop.annotations.JsType;
import ol.proj.Projection;

/**
 * Options for creating a {@link ol.View}.
 *
 * @author Tino Desjardins
 */
@JsType(isNative = true)
public interface ViewOptions extends Options {

    @JsProperty
    void setCenter(Coordinate coordinate);

    @JsProperty
    void setProjection(Projection projection);

    @JsProperty
    void setZoom(double zoom);

}


text:
use std::thread;
use std::time::Duration;
use std::collections::VecDeque;

// Discord Dependencies -------------------------------------------------------
use discord::voice::VoiceConnection;
use discord::{Connection, Discord, Error, State};
use discord::model::{
    ChannelId, MessageId, UserId, ServerId,
    Event as DiscordEvent,
    PrivateChannel
};

// Low Level Event Abstraction ------------------------------------------------
#[derive(Debug)]
pub enum Event {
    Reconnected,
    Disconnected,
    Timer,
    Received(Box<DiscordEvent>),
    SendMessageFailure(ChannelId, String),
    DeleteMessageFailure(ChannelId, MessageId)
}

// Low Level Event Queue ------------------------------------------------------
pub struct EventQueue {
    events: VecDeque<Event>,
    receiver: DiscordHandle
}

// Public Interface -----------------------------------------------------------
impl EventQueue {

    pub fn new(token: String) -> EventQueue {
        EventQueue {
            events: VecDeque::new(),
            receiver: DiscordHandle::from_token(
                token.clone()

            ).expect("[EL] Initial connection failed.")
        }

    }

    pub fn events(&mut self) -> Vec<Event> {

        match self.receiver.recv_event() {
            Ok(event) => {
                self.receiver.update(&event);
                self.events.push_back(Event::Received(Box::new(event)));
            },
            Err(err) => {
                if let Error::WebSocket(..) = err {
                    warn!("[EL] [Receiver] WebSocket closed...");
                    match self.receiver.reconnect() {
                        Ok(r) => {
                            warn!("[EL] [Receiver] Reconnected.!");
                            self.events.push_back(Event::Reconnected);
                            self.receiver = r;
                        },
                        Err(_) => {
                            warn!("[EL] [Receiver] Connection failed!");
                            self.events.push_back(Event::Disconnected);
                        }
                    }

                } else if let Error::Closed(..) = err {
                    warn!("[EL] [Receiver] Connection closed.");
                    self.events.push_back(Event::Disconnected);

                } else {
                    self.events.push_back(Event::Timer);
                    thread::sleep(Duration::from_millis(100));
                }
            }

        }

        self.events.drain(0..).collect()

    }

    pub fn connect_server_voice<C: FnOnce(&mut VoiceConnection)>(
        &mut self,
        server_id: ServerId,
        channel_id: ChannelId,
        callback: C
    ) {
        let voice_connection = self.receiver.connection.voice(Some(server_id));
        info!("[EL] Creating voice connection for Channel#{} on Server#{}", channel_id, server_id);
        voice_connection.connect(channel_id);
        callback(voice_connection);
    }

    pub fn with_server_voice<C: FnOnce(&mut VoiceConnection)>(
        &mut self,
        server_id: ServerId,
        callback: C
    ) {
        let voice_connection = self.receiver.connection.voice(Some(server_id));
        callback(voice_connection);
    }

    pub fn disconnect_server_voice(&mut self, server_id: ServerId) {
        info!("[EL] Dropping voice connection for Server#{}", server_id);
        self.receiver.connection.drop_voice(Some(server_id));
    }

}

// Message Interface ----------------------------------------------------------
impl EventQueue {

    pub fn send_message_to_user(&mut self, user_id: &UserId, content: String) {
        if let Some(channel) = self.private_channel_for_user(user_id) {
            self.send_message_to_channel(&channel.id, content);
        }
    }

    pub fn send_message_to_channel(&mut self, channel_id: &ChannelId, content: String) {

        if self.receiver.discord.send_message(*channel_id, content.as_str(), "", false).is_err() {
            warn!("[EL] Failed to sent message.");
            self.events.push_back(Event::SendMessageFailure(*channel_id, content));

        } else {
            info!("[EL] Message sent.");
        }

    }

    pub fn delete_message(&mut self, message_id: MessageId, channel_id: ChannelId) {
        if self.receiver.discord.delete_message(channel_id, message_id).is_err() {
            warn!("[EL] Failed to delete message.");
            self.events.push_back(Event::DeleteMessageFailure(channel_id, message_id));

        } else {
            info!("[EL] Message deleted.");
        }
    }

}

// Internal Interface ---------------------------------------------------------
impl EventQueue {

    fn private_channel_for_user(&self, user_id: &UserId) -> Option<PrivateChannel> {
        self.receiver.discord.create_private_channel(*user_id).ok()
    }

}

// Discord Abstraction --------------------------------------------------------
pub struct DiscordHandle {
    token: String,
    discord: Discord,
    connection: Connection,
    state: State
}

impl DiscordHandle {

    fn from_token(token: String) -> Result<DiscordHandle, String> {

        let discord = try!(Discord::from_bot_token(&token).map_err(|err| {
            err.to_string()
        }));

        match discord.connect() {
            Ok((mut conn, ready)) => {
                conn.set_non_blocking(true);
                Ok(DiscordHandle {
                    token: token,
                    discord: discord,
                    connection: conn,
                    state: State::new(ready)
                })
            },
            Err(err) => Err(err.to_string())
        }

    }

    fn reconnect(&self) -> Result<DiscordHandle, String> {
        DiscordHandle::from_token(self.token.clone())
    }

    fn update(&mut self, event: &DiscordEvent) {
        self.state.update(event);
    }

    fn recv_event(&mut self) -> Result<DiscordEvent, Error> {
        self.connection.recv_event()
    }

}


text:
package com.hazelcast.internal.util.hashslot;

/**
 * Cursor over assigned slots in a {@link HashSlotArray12byteKey}. Initially the cursor's location is
 * before the first slot and the cursor is invalid.
 */
public interface HashSlotCursor12byteKey extends HashSlotCursor {

    /**
     * @return key part 1 of current slot.
     * @throws IllegalStateException if the cursor is invalid.
     */
    long key1();

    /**
     * @return key part 2 of current slot.
     * @throws IllegalStateException if the cursor is invalid.
     */
    int key2();
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Crud extends CI_CONTROLLER
{
	public function __construct()
	{
		parent::__construct();

		//cargamos la base de datos por defecto
		$this->load->database('default');
		//cargamos el helper url y el helper form
		$this->load->helper(array('url','form'));
		//cargamos la librería form_validation
		$this->load->library(array('form_validation'));
		//cargamos el modelo Crud_model
		$this->load->model('Crud_model');

	}

	//cargamos la vista y pasamos el título y los usuarios a
	//través del array data a la misma
	public function index()
	{

		$data = array('titulo' => 'Crud en codeigniter',
					  'users' => $this->Crud_model->get_users());

		$this->load->view('crud',$data);
	}

    public function registro()
    {
        $data = array('titulo' => 'Registro de usuario');

        $this->load->view('register_view',$data);
    }

 	//función para eliminar usuarios
    public function delete_user()
    {

        //comprobamos si es una petición ajax y existe la variable post id
        if($this->input->is_ajax_request() && $this->input->post('id'))
        {

        	$id = $this->input->post('id');

			$this->Crud_model->delete_user($id);

        }

    }

 	//con esta función añadimos y editamos usuarios dependiendo
 	//si llega la variable post id, en ese caso editamos
    public function multi_user()
    {

    	//comprobamos si es una petición ajax
    	if($this->input->server('REQUEST_METHOD') == 'POST')
        {

            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
            $this->form_validation->set_rules('nombre', 'Nombre', 'required|trim|min_length[2]|max_length[150]');

            $this->form_validation->set_message('required','El %s es obligatorio');
            $this->form_validation->set_message('valid_email','El %s no es válido');
            $this->form_validation->set_message('max_length', 'El %s no puede tener más de %s carácteres');
            $this->form_validation->set_message('min_length', 'El %s no puede tener menos de %s carácteres');

            if($this->form_validation->run() == FALSE)
            {

            	//de esta forma devolvemos los errores de formularios
            	//con ajax desde codeigniter, aunque con php es lo mismo
            	$errors = array(
				    'nombre' => form_error('nombre'),
				    'email' => form_error('email'),
				    'respuesta' => 'error'
				);
            	//y lo devolvemos así para parsearlo con JSON.parse
				echo json_encode($errors);

				return FALSE;

            }else{

            	$nombre = $this->input->post('nombre');
	        	$email = $this->input->post('email');

	        	//si estamos editando
            	if($this->input->post('id'))
            	{

            		$id = $this->input->post('id');
            		$this->Crud_model->edit_user($id,$nombre,$email);

            	//si estamos agregando un usuario
            	}else{

            		$this->Crud_model->new_user($nombre,$email);

            	}

	        	//en cualquier caso damos ok porque todo ha salido bien
	        	//habría que hacer la comprobación de la respuesta del modelo

	        	$response = array(
				    'respuesta'	=>	'ok'
				);

				echo json_encode($response);

            }

        }

    }

}


text: ring ..\codegen\parsec.ring cjson.cf ring_cjson.c ring_cjson.rh


text:
"""
JSONField automatically serializes most Python terms to JSON data.
Creates a TEXT field with a default value of "{}".  See test_json.py for
more information.

 from django.db import models
 from django_extensions.db.fields import json

 class LOL(models.Model):
     extra = json.JSONField()
"""

import datetime
from decimal import Decimal

import json
from django.conf import settings
from mongoengine.fields import StringField

class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        elif isinstance(obj, datetime.datetime):
            assert settings.TIME_ZONE == 'UTC'
            return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
        return json.JSONEncoder.default(self, obj)

def dumps(value):
    assert isinstance(value, dict)
    return JSONEncoder().encode(value)

def loads(txt):
    value = json.loads(txt, parse_float=Decimal)
    assert isinstance(value, dict)
    return value

class JSONDict(dict):
    """
    Hack so repr() called by dumpdata will output JSON instead of
    Python formatted data.  This way fixtures will work!
    """

    def __repr__(self):
        return dumps(self)

class JSONField(StringField):
    """
    JSONField is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly. Main object must be a dict object.
    """

    def __init__(self, *args, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = '{}'
        StringField.__init__(self, *args, **kwargs)

    def to_python(self, value):
        """ Convert our string value to JSON after we load it from the DB """
        if not value:
            return {}
        elif isinstance(value, str):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value

    def get_db_prep_save(self, value):
        """ Convert our JSON object to a string before we save """
        if not value:
            return super().get_db_prep_save("")
        else:
            return super().get_db_prep_save(dumps(value))


text:
title: Apache Mesos - HTTP Endpoints - /maintenance/status
layout: documentation
---
<!--- This is an automatically generated file. DO NOT EDIT! --->

### USAGE ###
>        /maintenance/status
>        /master/maintenance/status

### TL;DR; ###
Retrieves the maintenance status of the cluster.

### DESCRIPTION ###
Returns 200 OK when the maintenance status was queried successfully.

Returns 307 TEMPORARY_REDIRECT redirect to the leading master when
current master is not the leader.

Returns 503 SERVICE_UNAVAILABLE if the leading master cannot be
found.

Returns an object with one list of machines per machine mode.
For draining machines, this list includes the frameworks' responses
to inverse offers.
**NOTE**:
Inverse offer responses are cleared if the master fails over.
However, new inverse offers will be sent once the master recovers.

### AUTHENTICATION ###
This endpoint requires authentication iff HTTP authentication is
enabled.


text:
static_assert( std::is_trivially_destructible<date::month_weekday>{}, "");
static_assert(!std::is_default_constructible<date::month_weekday>{}, "");
static_assert( std::is_trivially_copy_constructible<date::month_weekday>{}, "");
static_assert( std::is_trivially_copy_assignable<date::month_weekday>{}, "");
static_assert( std::is_trivially_move_constructible<date::month_weekday>{}, "");
static_assert( std::is_trivially_move_assignable<date::month_weekday>{}, "");

static_assert(std::is_nothrow_constructible<date::month_weekday,
                                                date::month,
                                                date::weekday_indexed>{}, "");

int
main()
{
    using namespace date;

    constexpr month_weekday mwd1 = {feb, sat[4]};
    constexpr month_weekday mwd2 = {mar, mon[1]};
    static_assert(mwd1.ok(), "");
    static_assert(mwd2.ok(), "");
    static_assert(!month_weekday{feb, sat[0]}.ok(), "");
    static_assert(!month_weekday{month{0}, sun[1]}.ok(), "");
    static_assert(mwd1.month() == feb, "");
    static_assert(mwd1.weekday_indexed() == sat[4], "");
    static_assert(mwd2.month() == mar, "");
    static_assert(mwd2.weekday_indexed() == mon[1], "");
    static_assert(mwd1 == mwd1, "");
    static_assert(mwd1 != mwd2, "");
    std::ostringstream os;
    os << mwd1;
    assert(os.str() == "Feb/Sat[4]");
}


text:
	-- Love Frames - A GUI library for LOVE --
	-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------

-- button object
local newobject = loveframes.NewObject("button", "loveframes_object_button", true)

--[[---------------------------------------------------------
	- func: initialize()
	- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()

	self.type = "button"
	self.text = "Button"
	self.width = 80
	self.height = 25
	self.internal = false
	self.down = false
	self.clickable = true
	self.enabled = true
	self.OnClick = nil

end

--[[---------------------------------------------------------
	- func: update(deltatime)
	- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible
	local alwaysupdate = self.alwaysupdate

	if not visible then
		if not alwaysupdate then
			return
		end
	end

	self:CheckHover()

	local hover = self.hover
	local down = self.down
	local downobject = loveframes.downobject
	local parent = self.parent
	local base = loveframes.base
	local update = self.Update

	if not hover then
		self.down = false
		if downobject == self then
			self.hover = true
		end
	else
		if downobject == self then
			self.down = true
		end
	end

	-- move to parent if there is a parent
	if parent ~= base then
		self.x = self.parent.x + self.staticx
		self.y = self.parent.y + self.staticy
	end

	if update then
		update(self, dt)
	end

end

--[[---------------------------------------------------------
	- func: draw()
	- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible

	if not visible then
		return
	end

	local skins = loveframes.skins.available
	local skinindex = loveframes.config["ACTIVESKIN"]
	local defaultskin = loveframes.config["DEFAULTSKIN"]
	local selfskin = self.skin
	local skin = skins[selfskin] or skins[skinindex]
	local drawfunc = skin.DrawButton or skins[defaultskin].DrawButton
	local draw = self.Draw
	local drawcount = loveframes.drawcount

	-- set the object's draw order
	self:SetDrawOrder()

	if draw then
		draw(self)
	else
		drawfunc(self)
	end

end

--[[---------------------------------------------------------
	- func: mousepressed(x, y, button)
	- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible

	if not visible then
		return
	end

	local hover = self.hover

	if hover and button == "l" then
		local baseparent = self:GetBaseParent()
		if baseparent and baseparent.type == "frame" then
			baseparent:MakeTop()
		end
		self.down = true
		loveframes.downobject = self
	end

end

--[[---------------------------------------------------------
	- func: mousereleased(x, y, button)
	- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible

	if not visible then
		return
	end

	local hover = self.hover
	local down = self.down
	local clickable = self.clickable
	local enabled = self.enabled
	local onclick = self.OnClick

	if hover and down and clickable and button == "l" then
		if enabled then
			if onclick then
				onclick(self, x, y)
			end
		end
	end

	self.down = false

end

--[[---------------------------------------------------------
	- func: SetText(text)
	- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)

	self.text = text
	return self

end

--[[---------------------------------------------------------
	- func: GetText()
	- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()

	return self.text

end

--[[---------------------------------------------------------
	- func: SetClickable(bool)
	- desc: sets whether the object can be clicked or not
--]]---------------------------------------------------------
function newobject:SetClickable(bool)

	self.clickable = bool
	return self

end

--[[---------------------------------------------------------
	- func: GetClickable(bool)
	- desc: gets whether the object can be clicked or not
--]]---------------------------------------------------------
function newobject:GetClickable()

	return self.clickable

end

--[[---------------------------------------------------------
	- func: SetClickable(bool)
	- desc: sets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:SetEnabled(bool)

	self.enabled = bool
	return self

end

--[[---------------------------------------------------------
	- func: GetEnabled()
	- desc: gets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:GetEnabled()

	return self.enabled

end

--[[---------------------------------------------------------
	- func: GetDown()
	- desc: gets whether or not the object is currently
	        being pressed
--]]---------------------------------------------------------
function newobject:GetDown()

	return self.down

end


text:
$(function () {
    //dialog init
    $('#dialog').dialog({
        autoOpen: false,
        modal: false,
        width: 600,
        buttons: {
            "Ok": function () {
                $(this).dialog("close");
            }
        }
    });
    return false;
}
);

function test1() {
    alert('test1');
}

//dialog with two buttons
function ShowEidssDialog(title, text, button1Text, button1callback, button2Text) {
    $("#dialog").dialog("option", "title", title);
    //$("#dialog").text(text);
    $("#dialog").html(text);
    $("#dialog").dialog("option", "buttons", [
    {
        text: button1Text
        ,click: function () {
            button1callback();
            $(this).dialog("close");
        }
    }
    ,
    {
        text: button2Text
        ,click: function () {
            $(this).dialog("close");
        }
    }
    ]);
    $('#dialog').dialog('open');
    return false;
}

var msgConfimation = EIDSS.BvMessages['msgConfimation'];
var strOK_Id = EIDSS.BvMessages['strOK_Id'];
var strCancel_Id = EIDSS.BvMessages['strCancel_Id'];

function ShowEidssDialogSavePrompt(button1callback) {
    ShowEidssDialog(msgConfimation, EIDSS.BvMessages['msgSavePrompt'], strOK_Id, button1callback, strCancel_Id);
}

function ShowEidssDialogCancelPrompt(button1callback) {
    ShowEidssDialog(msgConfimation, EIDSS.BvMessages['msgCancelPrompt'], strOK_Id, button1callback, strCancel_Id);
}

function ShowEidssDialogOKPrompt(button1callback) {
    ShowEidssDialog(msgConfimation, EIDSS.BvMessages['msgOKPrompt'], strOK_Id, button1callback, strCancel_Id);
}

function ShowEidssDialogDeletePrompt(button1callback) {
    ShowEidssDialog(msgConfimation, EIDSS.BvMessages['msgDeletePrompt'], strOK_Id, button1callback, strCancel_Id);
}


text:
require 'paneller/widget'

module Paneller
  describe Widget do
    let(:widget_class) { Class.new { include Widget } }
    let(:formatter_module) { Module.new {  } }
    let(:some_content) { rand(36**16).to_s(36) }

    describe '.new' do

      describe 'options' do

        it 'accepts a formatter in its options and extend itself with it' do
          widget = widget_class.new(formatter: formatter_module)

          expect(widget).to be_a formatter_module
        end

        it 'accepts an initial content in its options and sets the content to it' do
          widget = widget_class.new(initial_content: some_content)

          expect(widget.to_s).to eq some_content
        end

        it 'uses default options if none are provided' do
          widget = widget_class.new

          expect(widget.to_s).to eq Widget::DEFAULT_OPTIONS[:initial_content]
          expect(widget).to be_a Widget::DEFAULT_OPTIONS[:formatter]
        end

      end

      it 'receives a unique id' do
        used_ids = []

        1000.times do
          widget = widget_class.new

          expect(used_ids).not_to include widget.id
          used_ids << widget.id
        end
      end

    end

    describe '#poll_content' do

      let(:widget) { widget_class.new }

      it 'throws an error if not overridden' do
        expect { widget.poll_content }.to raise_error(NameError)
      end

    end

    describe '#run' do

      let(:interval) { 0.01 }
      let(:widget) { widget_class.new(update_interval: interval) }

      it 'calls #poll_content and sets the content to what it yields' do

        allow(widget).to receive(:poll_content).and_yield(some_content)

        widget.run

        expect(widget.to_s).to eq some_content
      end

      it 'waits the amount of time specified in options between consecutive polls' do
        iterations = 3
        pauses = iterations - 1

        (1..iterations).inject(allow(widget).to receive(:poll_content)) do |receive|
          receive.and_yield('content')
        end

        start_time = Time.now
        widget.run
        end_time = Time.now

        expect(end_time - start_time).to be_within(0.001).of(pauses * interval)
      end

      it 'notifies observers about changes' do
        observer = double('observer', update: nil)
        some_other_content = "#{some_content} and more"

        allow(widget).to receive(:poll_content).and_yield(some_content).and_yield(some_other_content)

        widget.add_observer(observer)
        widget.run

        expect(observer).to have_received(:update).twice
        expect(observer).to have_received(:update).with(widget.id, some_content)
        expect(observer).to have_received(:update).with(widget.id, some_other_content)
      end

      it 'only notifies observers when the content has changed' do
        observer = double('observer', update: nil)

        allow(widget).to receive(:poll_content).and_yield(some_content).and_yield(some_content)

        widget.add_observer(observer)
        widget.run

        expect(observer).to have_received(:update).once
      end

    end

  end
end


text:
SessionExpirationScript
=======================

Script to alert the user if the session is going to expires

 - Supports IE7
 - Cookie based
 - Supports ajax and multi tabs

How to use:
---

Reference the script
```HTML
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/session-expiration.js"></script>
```

Then initialize the processes:
```JavaScript
sessionExpiration.Init({
    expires: 5, //Time in minutes to session expires
    startWarning: 2, //Time in minutes to start calling the alert before the session expires (in this case, 3 minutes after script loads (5-2))
    sessionExpiring: function (time) {
        $('body').html('Session remaining: ' + time + ' seconds');
    },
    sessionOk: function () {
        $('body').html('');
    },
    sessionTimeout: function () {
        alert("Your session was timed out");
        location.href = 'http://www.contoso.com/login';
    }
});
```

Version
----

1.1

What's new
---
 - 'sessionOk' will be called only when session timeout is refreshed
 - fixed the bug with cookies path

License
----

MIT

rt.bortolin@gmail.com


text:
<?php
namespace Kahlan\Spec\Suite\Filter\Behavior;

use Kahlan\Plugin\Stub;
use Kahlan\Filter\MethodFilters;

describe('Filterable', function() {

	beforeEach(function() {
		$this->mock = Stub::create(['uses' => ['Kahlan\Filter\Behavior\Filterable']]);

		Stub::on($this->mock)->method('filterable', function() {
			return Filter::on($this, 'filterable', func_get_args(), function($chain, $message) {
				return "Hello {$message}";
			});
		});
	});

	describe("methodFilters", function() {

		it("gets the `MethodFilters` instance", function() {

			expect($this->mock->methodFilters())->toBeAnInstanceOf('Kahlan\Filter\MethodFilters');

		});

		it("sets a new `MethodFilters` instance", function() {

			$methodFilters = new MethodFilters();
			expect($this->mock->methodFilters($methodFilters))->toBeAnInstanceOf('Kahlan\Filter\MethodFilters');
			expect($this->mock->methodFilters())->toBe($methodFilters);

		});

	});

});


text:
using EasyNetQ.AutoSubscribe;
using EasyNetQ.Internals;
using FluentAssertions;
using NSubstitute;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace EasyNetQ.Tests.AutoSubscriberTests;

public class When_autosubscribing_with_subscription_configuration_action : IDisposable
{
    private IBus bus;
    private Action<ISubscriptionConfiguration> capturedAction;
    private IPubSub pubSub;

    public When_autosubscribing_with_subscription_configuration_action()
    {
        pubSub = Substitute.For<IPubSub>();
        bus = Substitute.For<IBus>();
        bus.PubSub.Returns(pubSub);

        var autoSubscriber = new AutoSubscriber(bus, "my_app")
        {
            ConfigureSubscriptionConfiguration =
                c => c.WithAutoDelete()
                    .WithExpires(10)
                    .WithPrefetchCount(10)
                    .WithPriority(10)
        };

        pubSub.SubscribeAsync(
                Arg.Is("MyActionTest"),
                Arg.Any<Func<MessageA, CancellationToken, Task>>(),
                Arg.Any<Action<ISubscriptionConfiguration>>()
            )
            .Returns(Task.FromResult(new SubscriptionResult()).ToAwaitableDisposable())
            .AndDoes(a => capturedAction = (Action<ISubscriptionConfiguration>)a.Args()[2]);

        autoSubscriber.Subscribe(new[] { typeof(MyConsumerWithAction) });
    }

    public void Dispose()
    {
        bus.Dispose();
    }

    [Fact]
    public void Should_have_called_subscribe()
    {
        pubSub.Received().SubscribeAsync(
            Arg.Any<string>(),
            Arg.Any<Func<MessageA, CancellationToken, Task>>(),
            Arg.Any<Action<ISubscriptionConfiguration>>()
        );
    }

    [Fact]
    public void Should_have_called_subscribe_with_action_capable_of_configuring_subscription()
    {
        var subscriptionConfiguration = new SubscriptionConfiguration(1);

        capturedAction(subscriptionConfiguration);

        subscriptionConfiguration.AutoDelete.Should().BeTrue();
        subscriptionConfiguration.Expires.Should().Be(10);
        subscriptionConfiguration.PrefetchCount.Should().Be(10);
        subscriptionConfiguration.Priority.Should().Be(10);
    }

    // Discovered by reflection over test assembly, do not remove.
    private class MyConsumerWithAction : IConsume<MessageA>
    {
        [AutoSubscriberConsumer(SubscriptionId = "MyActionTest")]
        public void Consume(MessageA message, CancellationToken cancellationToken)
        {
        }
    }

    private class MessageA
    {
    }
}

// ReSharper restore InconsistentNaming


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/lizhuo/Documents/GitHub/LogisticsPlatform/Client/Logistics/app/src/main/res/values-hdpi/dimens.xml -->
    <eat-comment/>
    <dimen name="am_pm_text_size">20dp</dimen>
    <dimen name="data_text_size_1">22dp</dimen>
    <dimen name="data_text_size_2">25dp</dimen>
</resources>


text:
.<%= params.slugifiedContentName %> { display: inline-block; width: auto; text-align: center; }
.<%= params.slugifiedContentName %> img { display: block; }


text:
namespace Logging.Memory
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Extensions.Logging;

    /// <summary>
    /// In-memory logger
    /// </summary>
    public class MemoryLogger : ILogger
    {
        private static readonly object lockObj = new object();

        private Func<string, LogLevel, bool> filter;

        private readonly Func<LogLevel, string, string, Exception, string> logLineFormatter = null;

        private static readonly Dictionary<LogLevel, LogForLevel> logsDictionary = new Dictionary<LogLevel, LogForLevel>();

        /// <summary>
        /// Max count of stored log lines
        /// </summary>
        public static int MaxLogCount = 200;

        /// <summary>
        /// Logger name
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Logger filter
        /// </summary>
        public Func<string, LogLevel, bool> Filter
        {
            get { return this.filter; }
            set
            {
                this.filter = value ?? throw new ArgumentNullException(nameof(value));
            }
        }

        /// <summary>
        /// Last <see cref="MaxLogCount"/> log lines
        /// </summary>
        public static List<string> LogList
        {
            get
            {
                return LogListWithTime.Select(x=>x.line).ToList();
            }
        }

        /// <summary>
        /// Last <see cref="MaxLogCount"/> log lines with time of add for each line
        /// </summary>
        public static List<(DateTime time,string line)> LogListWithTime
        {
            get
            {
                return logsDictionary
                            .SelectMany(x => x.Value.logList)
                            .OrderByDescending(x => x.time)
                            .Take(MaxLogCount)
                            .Reverse() // keep asc sort like in 1st version
                            .ToList();
            }
        }

        /// <summary>
        /// Return last <see cref="MaxLogCount"/> log lines of specified logLevel with time of add for each line
        /// </summary>
        /// <param name="logLevel">log level for return</param>
        /// <returns>List of log lines with time</returns>
        public static List<(DateTime time, string line)> GetLogWithTime(LogLevel logLevel)
        {
            if (logsDictionary.TryGetValue(logLevel, out var log))
            {
                return log.logList.OrderBy(x => x.time).ToList();
            }
            else
            {
                return Enumerable.Empty<(DateTime time, string line)>().ToList();
            }
        }

        /// <summary>
        /// Return last <see cref="MaxLogCount"/> log lines with specified logLevel
        /// </summary>
        /// <param name="logLevel">log level for return</param>
        /// <returns>List of log lines</returns>
        public static List<string> GetLog(LogLevel logLevel)
        {
            return GetLogWithTime(logLevel).Select(x => x.line).ToList();
        }

        /// <summary>
        /// Return log lines with time of add for each line of logLevel more or equal than <paramref name="minLogLevel"/>
        /// </summary>
        /// <param name="minLogLevel">Min log level</param>
        /// <returns>List of log lines with time</returns>
        public static List<(DateTime time,string line)> GetLogGteWithTime(LogLevel minLogLevel)
        {
            return logsDictionary.Where(x => x.Key >= minLogLevel)
                        .SelectMany(x => x.Value.logList)
                            .OrderBy(x => x.time).ToList();
        }

        /// <summary>
        /// Return log lines with logLevel more or equal than <paramref name="minLogLevel"/>
        /// </summary>
        /// <param name="minLogLevel">Min log level</param>
        /// <returns>List of log lines</returns>
        public static List<string> GetLogGte(LogLevel minLogLevel)
        {
            return GetLogGteWithTime(minLogLevel).Select(x => x.line).ToList();
        }

        /// <summary>
        /// Return log lines with time of add for each line of logLevel less or equal than <paramref name="maxLogLevel"/>
        /// </summary>
        /// <param name="maxLogLevel">Max log level</param>
        /// <returns>List of log lines with time</returns>
        public static List<(DateTime time, string line)> GetLogLteWithTime(LogLevel maxLogLevel)
        {
            return logsDictionary.Where(x => x.Key <= maxLogLevel)
                        .SelectMany(x => x.Value.logList)
                            .OrderBy(x => x.time).ToList();
        }

        /// <summary>
        /// Return log lines with logLevel less or equal than <paramref name="maxLogLevel"/>
        /// </summary>
        /// <param name="maxLogLevel">Max log level</param>
        /// <returns>List of log lines</returns>
        public static List<string> GetLogLte(LogLevel maxLogLevel)
        {
            return GetLogLteWithTime(maxLogLevel).Select(x => x.line).ToList();
        }

        static MemoryLogger()
        {
            foreach (var level in ((LogLevel[])Enum.GetValues(typeof(LogLevel))).Where(x => x != LogLevel.None))
            {
                logsDictionary.Add(level, new LogForLevel(MaxLogCount));
            }
        }

        /// <summary>
        /// default constructor
        /// </summary>
        /// <param name="name">logger name</param>
        /// <param name="filter">filter log entities</param>
        /// <param name="maxLogCount">max count of stored lines of log (for each level)</param>
        /// <param name="logLineFormatter">string formatter for log line</param>
        public MemoryLogger(string name, Func<string, LogLevel, bool> filter,
                                int maxLogCount,
                                Func<LogLevel, string, string, Exception, string> logLineFormatter)
        {
            Name = name;
            this.filter = filter ?? ((category, logLevel) => true);
            MaxLogCount = maxLogCount;
            this.logLineFormatter = logLineFormatter ?? DefaultLogLineFormatter.Formatter;
        }

        #region ILog implementation
        /// <inheritdoc />
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            var message = formatter(state, exception);

            if (logsDictionary.TryGetValue(logLevel, out var currentLog))
            {
                if (!string.IsNullOrEmpty(message))
                {
                    var preparedMessage = this.logLineFormatter(logLevel, Name, message, exception);
                    lock (lockObj)
                    {
                        if (currentLog.logList.Count < MaxLogCount)
                        {
                            currentLog.logList.Add((DateTime.Now, preparedMessage));
                        }
                        else
                        {
                            currentLog.logList[currentLog.currentLogIndex] = (DateTime.Now, preparedMessage);
                        }

                        if (currentLog.currentLogIndex < MaxLogCount - 1)
                        {
                            currentLog.currentLogIndex++;
                        }
                        else
                        {
                            currentLog.currentLogIndex = 0;
                        }
                    }

                }
            }
        }

        /// <inheritdoc />
        public bool IsEnabled(LogLevel logLevel)
        {
            return this.filter(Name, logLevel);
        }

        /// <inheritdoc />
        public IDisposable BeginScope<TState>(TState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            return MemoryLogScope.Push(Name, state);
        }
        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using OpenQA.Selenium;

namespace Selenium.Internal.SeleniumEmulation
{
    /// <summary>
    /// Defines the command for the addLocationStrategy keyword.
    /// </summary>
    internal class AddLocationStrategy : SeleneseCommand
    {
        private ElementFinder finder;

        /// <summary>
        /// Initializes a new instance of the <see cref="AddLocationStrategy"/> class.
        /// </summary>
        /// <param name="elementFinder">An <see cref="ElementFinder"/> object used to locate elements.</param>
        public AddLocationStrategy(ElementFinder elementFinder)
        {
            this.finder = elementFinder;
        }

        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            string strategy = string.Format(CultureInfo.InvariantCulture, @"return (function(locator, inWindow, inDocument) {{ {0} }}).call(null, arguments[0], window, document)", value);

            this.finder.AddStrategy(locator, strategy);

            return null;
        }
    }
}


text:
var rollup = require('rollup');
var fs = require('fs');
var istanbul = require('rollup-plugin-istanbul');
var babel = require("babel-core");
var less = require('semicolon-less')

// used to track the cache for subsequent bundles
var cache;

module.exports = rollup.rollup({
    // The bundle's starting point. This file will be
    // included, along with the minimum necessary code
    // from its dependencies
    entry: 'test/spec.modern.js',
    // If you have a bundle you want to re-use (e.g., when using a watcher to rebuild as files change),
    // you can tell rollup use a previous bundle as its starting point.
    // This is entirely optional!
    cache: cache,

    plugins: [
        // istanbul({
        //   exclude: ['test/**/*.js']
        // })
    ]
}).then(function(bundle) {
    // Generate bundle + sourcemap
    var result = bundle.generate({
        format: 'umd',
        moduleName: 'avalon'
    });
    // Cache our bundle for later use (optional)
    cache = bundle;
    var code = result.code.replace(
            /Object\.defineProperty\(exports,\s*'__esModule',\s*\{\s*value:\s*true\s*\}\);/,
            "exports.__esModule = true").
        //      replace(/'use strict';?/,'')
    replace(/avalon\$1/g, 'avalon')

    result = babel.transform(code, {
        presets: ['avalon'],
        compact: false
    })

    code = result.code.replace(/\}\)\(undefined,/, '})(this,')
    fs.writeFileSync('./dist/avalon.modern.test.js', less(code));

}).catch(function(e) {
    console.log('error', e)
})


text:
package io.spring.initializr.actuate;

import io.spring.initializr.web.AbstractFullStackInitializrIntegrationTests;
import io.spring.initializr.web.AbstractInitializrIntegrationTests.Config;
import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.ActiveProfiles;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for actuator specific features.
 *
 * @author Stephane Nicoll
 */
@ActiveProfiles("test-default")
@SpringBootTest(classes = Config.class, webEnvironment = WebEnvironment.RANDOM_PORT,
		properties = { "management.endpoints.web.exposure.include=info", "management.info.env.enabled=true" })
class ActuatorIntegrationTests extends AbstractFullStackInitializrIntegrationTests {

	@Test
	void infoHasExternalProperties() {
		String body = getRestTemplate().getForObject(createUrl("/actuator/info"), String.class);
		assertThat(body).contains("\"spring-boot\"");
		assertThat(body).contains("\"version\":\"2.4.4\"");
	}

}


text:
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

// components
import NavBar from './NavBar';
import LeftMenu from '../LeftMenu';

// actions
import * as authActions from '../../../modules/auth/actions';

const Header = ({ toggleAuthModal, userId }) => (
	<div>
		<LeftMenu />
		<NavBar
			toggleAuthModal={toggleAuthModal}
			userId={userId}
		/>
	</div>
);

Header.propTypes = {
	toggleAuthModal: PropTypes.func.isRequired,
	userId: PropTypes.string,
};

Header.defaultProps = {
	userId: null
};

const mapStateToProps = state => ({
	userId: state.auth.userId,
});

const mapDispatchToProps = dispatch => ({
	toggleAuthModal: (e) => {
		e.preventDefault();
		dispatch(authActions.toggleAuthModal());
	},
});

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Header);


text:
//
//  OCAProducer+Subclass.h
//  Objective-Chain
//
//  Created by Martin Kiss on 30.12.13.
//  Copyright © 2014 Martin Kiss. All rights reserved.
//

#import "OCAProducer.h"

/*! Interface to be used by subclasses. Before you decide to subclass Producer, you may consider to use Command subclass.
 *  Every Producer must manage its own lifetime, so it should live and produce values until it makes sense. For example, a Timer produces values until the end date. Property produces until its observed object deallocates.
 *  To hook onto another object (a.k.a. owner), use Decomposer class.
 */
@interface OCAProducer ()

#pragma mark Creating Producer

//! Designated initializer. Your custom public initializer can provide a class that you are planning to produce. All produced values are validated to be of this class. May be nil, which means any values pass the validation.
- (instancetype)initWithValueClass:(Class)valueClass;

#pragma mark Managing Connections

//! Your subclass can provide a replacement for added consumer. Pass the original consumer or create Mediator, for example, to transform produced values.
- (id<OCAConsumer>)replacementConsumerForConsumer:(id<OCAConsumer>)consumer;

//! Empty. Called before the consumer is added, but after -replacementConsumerForConsumer: is called.
- (void)willAddConsumer:(id<OCAConsumer> )consumer;

//! If the receiver already finished, it calls -finishConsumingWithError: on the Consumer, otherwise it re-sends the latest produced value.
- (void)didAddConsumer:(id<OCAConsumer> )consumer;

//! Empty.
- (void)willRemoveConsumer:(id<OCAConsumer> )consumer;

//! Empty.
- (void)didRemoveConsumer:(id<OCAConsumer> )consumer;

#pragma mark Lifetime of Producer

//! Core method. Call this from your subclass with values you want to produce. Values are validated and sent to all Consumers. If the Producer already finished, nothing is sent.
- (void)produceValue:(id)value NS_REQUIRES_SUPER;

//! Core method. Call this from your subclass once you plan to send no more values. Marks the Producer as finished, sends the error to consumers and removes them. Usually after finishing, the Producer is no longer needed and may be deallocated. This method is automatically called before deallocation.
- (void)finishProducingWithError:(NSError *)error NS_REQUIRES_SUPER;

//! Readwrite acces to the laste produced value. You usually don't need to do any changes to it.
@property (atomic, readwrite, strong) id lastValue;

//! Called from -prodcuceValue:. Default implementation validated class of the value to the valueClass property. Override if you need other validation.
- (BOOL)validateProducedValue:(id)value;

#pragma mark Describing Producer

- (NSString *)descriptionName;
- (NSDictionary *)debugDescriptionValues;

@end


text:
module Nppes
  module UpdatePack
    class Data < UpdatePack::Base
      def initialize(data_file)
        @file = data_file
      end

      def proceed
        parse(@file) do |row|
          proceed_row(row)
        end
      end

      def proceed_row(row, required_fields = RequiredFields)
        @fields = split_row(row)

        npi = Nppes::NpIdentifier.where(npi: @fields[0]).first_or_initialize

        required_fields.fields.each_pair { |k, v| npi.send("#{k}=", prepare_value(@fields, v)) }

        # for submodels
        required_fields.relations.each_pair do |k, v|
          v.each do |entity|
            relation = npi.send(k).new
            entity.each_pair {|name, num| relation.send("#{name}=", prepare_value(@fields, num))}
            unless relation.valid?
              npi.send(k).delete(relation)
              break
            end
          end
        end

        npi.save if npi.valid?
      end

      protected
        def prepare_value(fields, variants)
          if variants.is_a? String
            variants
          elsif variants.is_a? Array
            variant = variants.detect {|v| fields[v].present? }
            variant ? fields[variant] : ''
          else
            fields[variants]
          end
        end
    end
  end
end


text:
       {{yorum[index].book}} -  {{yorum[index].comment_time}}

       {{yorum[index].comment}}


text:
from fabric.context_managers import settings, hide
import fabric.state
from libcloud.compute.types import Provider
import libcloud.security
import platform
import logging
import ssh

LOG_LEVEL = logging.INFO
FORMAT = "%(levelname)-10s %(name)s %(message)s"
logging.basicConfig(format=FORMAT, level=LOG_LEVEL)

ssh_logger = logging.getLogger('ssh.transport')
ssh_logger.setLevel(logging.WARN)

# don't verify ssl certs (doesn't work on os x)
if platform.mac_ver():
    libcloud.security.VERIFY_SSL_CERT = False

# to hide 'running', this must be at the global level
#   https://github.com/fabric/fabric/issues/424
fabric.state.output['running'] = False

AVAILABLE_CLOUD_PROVIDERS = (
    'ec2',
    'ec2_us_east',
    'ec2_us_west',
    'rackspace',
)
AVAILABLE_CLOUD_REGIONS = {
    'ec2': {
        'us-east-1': Provider.EC2_US_EAST,
        'us-west-1': Provider.EC2_US_WEST,
        'us-west-2': Provider.EC2_US_WEST_OREGON,
        'eu-west-1': Provider.EC2_EU_WEST,
    },
    'rackspace': {
        'dfw': Provider.RACKSPACE,
        'uk': Provider.RACKSPACE_UK,
    },
    'vcloud': {
        'default': Provider.VCLOUD,
    }
}
def default_settings():
    """
    Returns a default settings object for tasks

    :rtype: `fabric.context_managers.settings`

    """
    defaults = settings(
        hide('running',),
    )
    return defaults


text:
""" Test end to end flow with:
        Notification service with
        Threshold in-built rule plugin
        notify-python35 delivery channel plugin
"""

import os
import time
import subprocess
import http.client
import json
from threading import Event
import urllib.parse

import pytest

__author__ = "Ashish Jabble"
__copyright__ = "Copyright (c) 2019 Dianomic Systems"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"

SERVICE = "notification"
SERVICE_NAME = "NotificationServer #1"
NOTIFY_PLUGIN = "python35"
NOTIFY_INBUILT_RULES = ["Threshold"]

def _configure_and_start_service(service_branch, foglamp_url, remove_directories):
    try:
        subprocess.run(["$FOGLAMP_ROOT/tests/system/python/scripts/install_c_service {} {}"
                       .format(service_branch, SERVICE)], shell=True, check=True, stdout=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        assert False, "{} installation failed".format(SERVICE)
    finally:
        remove_directories("/tmp/foglamp-service-{}".format(SERVICE))

    # Start service
    conn = http.client.HTTPConnection(foglamp_url)
    data = {"name": SERVICE_NAME,
            "type": "notification",
            "enabled": "true"
            }
    conn.request("POST", '/foglamp/service', json.dumps(data))
    r = conn.getresponse()
    assert 200 == r.status
    r = r.read().decode()
    jdoc = json.loads(r)
    assert 2 == len(jdoc)
    assert SERVICE_NAME == jdoc['name']

def _install_notify_plugin(notify_branch, plugin_name, remove_directories):
    try:
        subprocess.run(["$FOGLAMP_ROOT/tests/system/python/scripts/install_c_plugin {} notify {}".format(
            notify_branch, plugin_name)], shell=True, check=True, stdout=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        assert False, "{} installation failed".format(plugin_name)
    finally:
        remove_directories("/tmp/foglamp-notify-{}".format(plugin_name))

def _get_result(foglamp_url, path):
    conn = http.client.HTTPConnection(foglamp_url)
    conn.request("GET", path)
    r = conn.getresponse()
    assert 200 == r.status
    r = r.read().decode()
    jdoc = json.loads(r)
    return jdoc

def _verify_service(foglamp_url, status):
    jdoc = _get_result(foglamp_url, '/foglamp/service')
    srvc = [s for s in jdoc['services'] if s['name'] == SERVICE_NAME]
    assert 1 == len(srvc)
    svc = srvc[0]
    assert SERVICE.capitalize() == svc['type']
    assert status == svc['status']

def _verify_audit_log_entry(foglamp_url, path, name, severity='INFORMATION', count=1):
    jdoc = _get_result(foglamp_url, path)
    assert len(jdoc['audit'])
    assert count == jdoc['totalCount']
    audit_detail = jdoc['audit'][0]
    assert severity == audit_detail['severity']
    assert name == audit_detail['details']['name']

def _add_notification_instance(foglamp_url, payload):
    conn = http.client.HTTPConnection(foglamp_url)
    conn.request("POST", '/foglamp/notification', json.dumps(payload))
    r = conn.getresponse()
    assert 200 == r.status
    r = r.read().decode()
    jdoc = json.loads(r)
    assert "Notification {} created successfully".format(payload['name']) == jdoc['result']

def pause_for_x_seconds(x=1):
    wait_e = Event()
    wait_e.clear()
    wait_e.wait(timeout=x)

class TestNotificationService:
    def test_service(self, reset_and_start_foglamp, service_branch, foglamp_url, wait_time, retries, remove_directories):
        _configure_and_start_service(service_branch, foglamp_url, remove_directories)

        retry_count = 0
        # only 2 services is being up by default i.e core and storage
        default_registry_count = 2
        service_registry = default_registry_count
        while service_registry != 3 and retry_count < retries:
            svc = _get_result(foglamp_url, '/foglamp/service')
            service_registry = svc['services']
            retry_count += 1

            pause_for_x_seconds(x=wait_time * 2)

        if len(service_registry) == default_registry_count:
            assert False, "Failed to start the {} service".format(SERVICE)

        _verify_service(foglamp_url, status='running')
        _verify_audit_log_entry(foglamp_url, '/foglamp/audit?source=NTFST', name=SERVICE_NAME)

    def test_get_default_notification_plugins(self, foglamp_url, remove_directories):
        remove_directories(os.environ['FOGLAMP_ROOT'] + '/plugins/notificationDelivery')
        remove_directories(os.environ['FOGLAMP_ROOT'] + '/plugins/notificationRule')
        remove_directories(os.environ['FOGLAMP_ROOT'] + 'cmake_build/C/plugins/notificationDelivery')
        remove_directories(os.environ['FOGLAMP_ROOT'] + 'cmake_build/C/plugins/notificationRule')
        jdoc = _get_result(foglamp_url, '/foglamp/notification/plugin')
        assert [] == jdoc['delivery']
        assert 1 == len(jdoc['rules'])
        assert NOTIFY_INBUILT_RULES[0] == jdoc['rules'][0]['name']

class TestNotificationCRUD:

    @pytest.mark.parametrize("data", [
        {"name": "Test 1", "description": "Test 1 notification", "rule": NOTIFY_INBUILT_RULES[0],
         "channel": NOTIFY_PLUGIN, "enabled": "false", "notification_type": "retriggered"},
        {"name": "Test2", "description": "Test 2 notification", "rule": NOTIFY_INBUILT_RULES[0],
         "channel": NOTIFY_PLUGIN, "enabled": "false", "notification_type": "toggled"},
        {"name": "Test #3", "description": "Test 3 notification", "rule": NOTIFY_INBUILT_RULES[0],
         "channel": NOTIFY_PLUGIN, "enabled": "false", "notification_type": "one shot"}
    ])
    def test_create_notification_instances_with_default_rule_and_channel_python35(self, foglamp_url, notify_branch,
                                                                                data,
                                                                                remove_directories):
        if data['name'] == 'Test 1':
            _install_notify_plugin(notify_branch, NOTIFY_PLUGIN, remove_directories)
        _add_notification_instance(foglamp_url, data)

    def test_inbuilt_rule_plugin_and_notify_python35_delivery(self, foglamp_url):
        jdoc = _get_result(foglamp_url, '/foglamp/notification/plugin')
        assert 1 == len(jdoc['delivery'])
        assert NOTIFY_PLUGIN == jdoc['delivery'][0]['name']
        assert 1 == len(jdoc['rules'])
        assert NOTIFY_INBUILT_RULES[0] == jdoc['rules'][0]['name']

    def test_get_notifications_and_audit_entry(self, foglamp_url):
        jdoc = _get_result(foglamp_url, '/foglamp/notification')
        assert 3 == len(jdoc['notifications'])

        # Test 1, Test2 and Test #3
        jdoc = _get_result(foglamp_url, '/foglamp/audit?source=NTFAD')
        assert 3 == jdoc['totalCount']

    def test_update_notification(self, foglamp_url, name="Test 1"):
        conn = http.client.HTTPConnection(foglamp_url)
        data = {"notification_type": "toggled"}
        conn.request("PUT", '/foglamp/notification/{}'.format(urllib.parse.quote(name))
                     , json.dumps(data))
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        assert "Notification {} updated successfully".format(name) == jdoc["result"]

        # Verify updated notification info
        jdoc = _get_result(foglamp_url, '/foglamp/notification/{}'.format(urllib.parse.quote(name)))
        assert "toggled" == jdoc['notification']['notificationType']

    def test_delete_notification(self, foglamp_url, name="Test #3"):
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("DELETE", '/foglamp/notification/{}'.format(urllib.parse.quote(name)))
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        jdoc = json.loads(r)
        assert "Notification {} deleted successfully.".format(name) == jdoc["result"]

        # Verify only two notifications should exist NOT 3
        jdoc = _get_result(foglamp_url, '/foglamp/notification')
        notifications = jdoc['notifications']
        assert 2 == len(notifications)
        assert "Test 1" == notifications[0]['name']
        assert "Test2" == notifications[1]['name']

        jdoc = _get_result(foglamp_url, '/foglamp/audit?source=NTFDL')
        assert 1 == jdoc['totalCount']

class TestSentAndReceiveNotification:
    FOGBENCH_TEMPLATE = "fogbench-template.json"
    SENSOR_VALUE = 20
    SOUTH_PLUGIN_NAME = "coap"
    ASSET_NAME = "{}".format(SOUTH_PLUGIN_NAME)

    @pytest.fixture
    def start_south(self, add_south, remove_data_file, remove_directories, south_branch, foglamp_url):
        """ This fixture clone a south repo and starts south instance
            add_south: Fixture that starts any south service with given configuration
            remove_data_file: Fixture that remove data file created during the tests
            remove_directories: Fixture that remove directories created during the tests """

        fogbench_template_path = self.prepare_template_reading_from_fogbench()

        add_south(self.SOUTH_PLUGIN_NAME, south_branch, foglamp_url, service_name=self.SOUTH_PLUGIN_NAME)

        yield self.start_south

        # Cleanup code that runs after the test is over
        remove_data_file(fogbench_template_path)
        remove_directories("/tmp/foglamp-south-{}".format(self.SOUTH_PLUGIN_NAME))

    def prepare_template_reading_from_fogbench(self):
        """ Define the template file for fogbench readings """

        fogbench_template_path = os.path.join(
            os.path.expandvars('${FOGLAMP_ROOT}'), 'data/{}'.format(self.FOGBENCH_TEMPLATE))
        with open(fogbench_template_path, "w") as f:
            f.write(
                '[{"name": "%s", "sensor_values": '
                '[{"name": "sensor", "type": "number", "min": %d, "max": %d, "precision": 0}]}]' % (
                    self.ASSET_NAME, self.SENSOR_VALUE, self.SENSOR_VALUE))

        return fogbench_template_path

    def ingest_readings_from_fogbench(self, foglamp_url, wait_time):
        pause_for_x_seconds(x=wait_time*3)
        conn = http.client.HTTPConnection(foglamp_url)
        subprocess.run(["cd $FOGLAMP_ROOT/extras/python; python3 -m fogbench -t ../../data/{}; cd -"
                       .format(self.FOGBENCH_TEMPLATE)], shell=True, check=True, stdout=subprocess.DEVNULL)

        pause_for_x_seconds(x=wait_time)

        conn.request("GET", '/foglamp/asset')
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        val = json.loads(r)
        assert 1 == len(val)
        assert self.ASSET_NAME == val[0]["assetCode"]
        assert 1 == val[0]["count"]

        conn.request("GET", '/foglamp/asset/{}'.format(self.ASSET_NAME))
        r = conn.getresponse()
        assert 200 == r.status
        r = r.read().decode()
        val = json.loads(r)
        assert 1 == len(val)
        assert {'sensor': self.SENSOR_VALUE} == val[0]["reading"]

    def configure_rule_with_single_item_eval_type(self, foglamp_url, cat_name):
        conn = http.client.HTTPConnection(foglamp_url)
        data = {"asset": self.ASSET_NAME,
                "datapoint": "sensor",
                "evaluation_data": "Single Item",
                "condition": ">",
                "trigger_value": str(self.SENSOR_VALUE - 10),
                }
        conn.request("PUT", '/foglamp/category/rule{}'.format(cat_name), json.dumps(data))
        r = conn.getresponse()
        assert 200 == r.status

    def enable_notification(self, foglamp_url, cat_name, is_enabled=True):
        _enabled = "true" if is_enabled else "false"
        data = {"value": _enabled}
        conn = http.client.HTTPConnection(foglamp_url)
        conn.request("PUT", '/foglamp/category/{}/enable'.format(cat_name), json.dumps(data))
        r = conn.getresponse()
        assert 200 == r.status

    def test_sent_and_receive_notification(self, foglamp_url, start_south, wait_time):
        data = {"name": "Test4",
                "description": "Test4_Notification",
                "rule": NOTIFY_INBUILT_RULES[0],
                "channel": NOTIFY_PLUGIN,
                "enabled": True,
                "notification_type": "one shot"
                }
        name = data['name']
        _add_notification_instance(foglamp_url, data)
        self.configure_rule_with_single_item_eval_type(foglamp_url, name)

        # upload script NotifyPython35::configure() -> lowercase(categoryName) + _script_ + method_name + ".py"
        cat_name = "delivery{}".format(name)
        script_path = '$FOGLAMP_ROOT/tests/system/python/data/notify35.py'
        url = 'http://' + foglamp_url + '/foglamp/category/' + cat_name + '/script/upload'
        upload_script = 'curl -F "script=@{}" {}'.format(script_path, url)
        subprocess.run(upload_script, shell=True, check=True, stdout=subprocess.DEVNULL)

        # enable notification delivery (it was getting disabled, as no script file was available)
        self.enable_notification(foglamp_url, "delivery" + name)

        self.ingest_readings_from_fogbench(foglamp_url, wait_time)
        time.sleep(wait_time)

        _verify_audit_log_entry(foglamp_url, '/foglamp/audit?source=NTFSN', name=name)

class TestStartStopNotificationService:
    def test_shutdown_service_with_schedule_disable(self, foglamp_url, disable_schedule, wait_time):
        disable_schedule(foglamp_url, SERVICE_NAME)
        _verify_service(foglamp_url, status='shutdown')
        pause_for_x_seconds(x=wait_time)
        # After shutdown there should be 1 entry for NTFSD (shutdown)
        _verify_audit_log_entry(foglamp_url, '/foglamp/audit?source=NTFSD', name=SERVICE_NAME, count=1)

    def test_restart_notification_service(self, foglamp_url, enable_schedule, wait_time):
        enable_schedule(foglamp_url, SERVICE_NAME)
        pause_for_x_seconds(x=wait_time)
        _verify_service(foglamp_url, status='running')
        # After restart there should be 2 entries for NTFST (start)
        _verify_audit_log_entry(foglamp_url, '/foglamp/audit?source=NTFST', name=SERVICE_NAME, count=2)