text:
<?php

/**
 * Theme helper
 *
 * @category    Mage
 * @package     Mage_XmlConnect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_XmlConnect_Helper_Theme extends Mage_Adminhtml_Helper_Data
{
    /**
     * Color Themes Cache
     *
     * @param array|null
     */
    protected $_themeArray = null;

    /**
     * Return for Color Themes Fields array.
     *
     * @return array
     */
    public function getThemeAjaxParameters()
    {
        $themesArray = array (
            'conf_native_navigationBar_tintColor'
                => 'conf[native][navigationBar][tintColor]',
            'conf_native_body_primaryColor'
                => 'conf[native][body][primaryColor]',
            'conf_native_body_secondaryColor'
                => 'conf[native][body][secondaryColor]',
            'conf_native_categoryItem_backgroundColor'
                => 'conf[native][categoryItem][backgroundColor]',
            'conf_native_categoryItem_tintColor'
                => 'conf[native][categoryItem][tintColor]',

            'conf_extra_fontColors_header'
                => 'conf[extra][fontColors][header]',
            'conf_extra_fontColors_primary'
                => 'conf[extra][fontColors][primary]',
            'conf_extra_fontColors_secondary'
                => 'conf[extra][fontColors][secondary]',
            'conf_extra_fontColors_price'
                => 'conf[extra][fontColors][price]',

            'conf_native_body_backgroundColor'
                => 'conf[native][body][backgroundColor]',
            'conf_native_body_scrollBackgroundColor'
                => 'conf[native][body][scrollBackgroundColor]',
            'conf_native_itemActions_relatedProductBackgroundColor'
                => 'conf[native][itemActions][relatedProductBackgroundColor]'
        );
        return $themesArray;
    }

    /**
     * Returns JSON ready Themes array
     *
     * @param bool $flushCache load defaults
     * @return array
     */
    public function getAllThemesArray($flushCache = false)
    {
        $result = array();
        $themes = $this->getAllThemes($flushCache);
        foreach ($themes as $theme) {
            $result[$theme->getName()] = $theme->getFormData();
        }
        return $result;
    }

    /**
     * Get dropdown select image for theme
     *
     * @param string $themeId
     * @return string Image url
     */
    public function getThemeImageUrl($themeId)
    {
        $themeImage = array_key_exists($themeId, $this->getDefaultThemes()) ? $themeId : 'user_custom';
        return Mage::helper('xmlconnect/image')->getSkinImagesUrl('swatch_' . $themeImage . '.gif');
    }

    /**
     * Get themes dropdown selector html
     *
     * @param string $themeId
     * @return string
     */
    public function getThemesSelector($themeId = '')
    {
        if (Mage::registry('current_app') !== null) {
            $themeId = Mage::registry('current_app')->getData('conf/extra/theme');
        }

        if (!$themeId) {
            $themeId = $this->getDefaultThemeName();
        }

        $currentTheme = $this->getThemeByName($themeId);
        if ($currentTheme === null) {
            $themeId = $this->getDefaultThemeName();
            $currentTheme = $this->getThemeByName($themeId);
        }

        if (!($currentTheme instanceof Mage_XmlConnect_Model_Theme)) {
            Mage::throwException(
                Mage::helper('xmlconnect')->__('Can\'t load selected theme. Please check your media folder permissions.')
            );
        }

        $themeList = '';
        foreach ($this->getAllThemes(true) as $theme) {
            $themeList .= '
getName() . '">';
            $themeList .= 'getName() . '" style="cursor:pointer;">' . $theme->getLabel();
            $themeList .= '';
            $themeList .= 'getThemeImageUrl($theme->getName()) . '"/>';
            $themeList .= '
';
        }

        $themesDdl = <<<EOT

                {$currentTheme->getLabel()}

                        getThemeImageUrl($themeId)}"/>

                {$themeList}

EOT;
        return $themesDdl;
    }

    /**
     * Reads directory media/xmlconnect/themes/*
     *
     * @param bool $flushCache Reads default color Themes
     * @return array contains Mage_XmlConnect_Model_Theme
     */
    public function getAllThemes($flushCache = false)
    {
        if (!$this->_themeArray || $flushCache) {
            try {
                $saveLibxmlErrors   = libxml_use_internal_errors(true);
                $this->_themeArray  = array();
                $themeDir = $this->getMediaThemePath();

                $ioFile = new Varien_Io_File();
                $ioFile->checkAndCreateFolder($themeDir);
                $ioFile->open(array('path' => $themeDir));
                $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES);
                if (!count($fileList) || !$this->_checkDefaultThemes($fileList)) {
                    $this->resetTheme();
                    $this->getAllThemes(true);
                }
                foreach ($fileList as $file) {
                    $src = $themeDir . DS . $file['text'];
                    if (is_readable($src)) {
                        $theme = Mage::getModel('xmlconnect/theme', $src);
                        $this->_themeArray[$theme->getName()] = $theme;
                    }
                }
                asort($this->_themeArray);
                libxml_use_internal_errors($saveLibxmlErrors);
            } catch (Exception $e) {
                Mage::logException($e);
            }
        }
        return $this->_themeArray;
    }

    /**
     * Check are default themes files present in media folder or not
     *
     * @param array $fileList
     * @return bool
     */
    protected function _checkDefaultThemes($fileList)
    {
        $cacheKey = 'MAGENTO_MOBILE_DEFAULT_THEMES_CACHE_KEY';
        $cache = Mage::app()->loadCache($cacheKey);
        if (Mage::app()->useCache('config') && $cache) {
            $defaultFiles = unserialize($cache);
        } else {
            $ioFile = new Varien_Io_File();
            $ioFile->open(array('path' => $this->_getDefaultThemePath()));
            $fileDefaultList = $ioFile->ls(Varien_Io_File::GREP_FILES);
            $defaultFiles = array();
            foreach ($fileDefaultList as $defaultFileData) {
                if ('xml' != $defaultFileData['filetype']) {
                    continue;
                }
                $defaultFiles[] = $defaultFileData['text'];
            }
            if (Mage::app()->useCache('config')) {
                Mage::app()->saveCache(serialize($defaultFiles), $cacheKey, array('config'));
            }
        }

        if (empty($defaultFiles)) {
            Mage::throwException($this->__('Default themes are missed.'));
        }
        $matches = 0;
        foreach ($fileList as $fileData) {
            if (in_array($fileData['text'], $defaultFiles)) {
                ++$matches;
            }
        }
        return $matches == count($defaultFiles);
    }

    /**
     * Reads default theme directory
     *
     * @throws Mage_Core_Exception
     * @return array contains Mage_XmlConnect_Model_Theme
     */
    public function getDefaultThemes()
    {
        $saveLibxmlErrors   = libxml_use_internal_errors(true);
        $defaultThemeArray  = array();
        $themeDir = $this->_getDefaultThemePath();
        $ioFile = new Varien_Io_File();
        $ioFile->open(array('path' => $themeDir));
        try {
            $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES);
            foreach ($fileList as $file) {
                $src = $themeDir . DS . $file['text'];
                if (is_readable($src)) {
                    $theme = Mage::getModel('xmlconnect/theme', $src);
                    $defaultThemeArray[$theme->getName()] = $theme;
                }
            }
            libxml_use_internal_errors($saveLibxmlErrors);
        } catch (Exception $e) {
            Mage::logException($e);
        }
        if (!count($defaultThemeArray)) {
            Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t load default themes.'));
        }
        return $defaultThemeArray;
    }

    /**
     * Create new custom theme
     *
     * @param  $themeName string
     * @param  $data array
     * @return Mage_XmlConnect_Model_Theme
     */
    public function createNewTheme($themeName, $data)
    {
        /** @var $defaultTheme Mage_XmlConnect_Model_Theme */
        $defaultTheme = $this->getThemeByName($this->getDefaultThemeName());
        return $defaultTheme->createNewTheme($themeName, $data);
    }

    /**
     * Get default theme path: /xmlconnect/etc/themes/*
     *
     * @return string
     */
    protected function _getDefaultThemePath()
    {
        return Mage::getModuleDir('etc', 'Mage_XmlConnect') . DS . 'themes';
    }

    /**
     * Get media theme path: media/xmlconnect/themes/*
     *
     * @return string
     */
    public function getMediaThemePath()
    {
        return Mage::getBaseDir('media') . DS . 'xmlconnect' . DS . 'themes';
    }

    /**
     * Reset themes color changes
     * Copy /xmlconnect/etc/themes/* to media/xmlconnect/themes/*
     *
     * @throws Mage_Core_Exception
     * @param null $theme
     * @return null
     */
    public function resetTheme($theme = null)
    {
        $themeDir = $this->getMediaThemePath();
        $defaultThemeDir = $this->_getDefaultThemePath();

        $ioFile = new Varien_Io_File();
        $ioFile->open(array('path' => $defaultThemeDir));
        $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES);
        foreach ($fileList as $file) {
            $f = $file['text'];
            $src = $defaultThemeDir . DS . $f;
            $dst = $themeDir . DS .$f;

            if ($theme && ($theme . '.xml') != $f) {
                continue;
            }

            if (!$ioFile->cp($src, $dst)) {
                Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $src, $dst));
            } else {
                $ioFile->chmod($dst, 0755);
            }
        }
    }

    /**
     * Get theme object by name
     *
     * @param string $name
     * @return Mage_XmlConnect_Model_Theme|null
     */
    public function getThemeByName($name)
    {
        $themes = $this->getAllThemes();
        $theme = isset($themes[$name]) ? $themes[$name] : null;
        return $theme;
    }

    /**
     * Return predefined custom theme name
     *
     * @return string
     */
    public function getCustomThemeName()
    {
        return 'custom';
    }

    /**
     * Return predefined default theme name
     *
     * @return string
     */
    public function getDefaultThemeName()
    {
        return 'default';
    }

    /**
     * Get current theme name
     *
     * @return string
     */
    public function getThemeId()
    {
        $themeId = Mage::helper('xmlconnect')->getApplication()->getData('conf/extra/theme');

        if ($this->getThemeByName($themeId) === null) {
            $themeId = null;
        }

        if (empty($themeId)) {
            $themeId = $this->getDefaultThemeName();
        }
        return $themeId;
    }

    /**
     * Get theme label by theme name
     *
     * @param array $themes
     * @param bool $themeId
     * @return string
     */
    public function getThemeLabel(array $themes, $themeId = false)
    {
        $themeLabel = '';
        $themeId    = $themeId ? $themeId : $this->getThemeId();

        foreach ($themes as $theme) {
            if ($theme->getName() == $themeId) {
                $themeLabel = $theme->getLabel();
                break;
            }
        }
        return $themeLabel;
    }

    /**
     * Delete theme by id
     *
     * @param  $themeId
     * @return bool
     */
    public function deleteTheme($themeId)
    {
        $result = false;
        $ioFile = new Varien_Io_File();
        $ioFile->cd($this->getMediaThemePath());
        $themeFile = basename($themeId . '.xml');
        if ($ioFile->fileExists($themeFile)) {
            $result = $ioFile->rm($themeFile);
        }
        return $result;
    }
}


text:
<?php

namespace Swarming\SubscribePro\Test\Unit\Model\Quote;

use Magento\Quote\Model\Quote;
use Magento\Vault\Api\Data\PaymentTokenInterface;
use Magento\Vault\Api\PaymentTokenManagementInterface;
use SubscribePro\Service\Customer\CustomerInterface as PlatformCustomerInterface;
use Swarming\SubscribePro\Model\Quote\SubscriptionCreator;
use Swarming\SubscribePro\Helper\QuoteItem as QuoteItemHelper;
use Swarming\SubscribePro\Helper\OrderItem as OrderItemHelper;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderPaymentInterface;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use Magento\Quote\Model\Quote\Address as QuoteAddress;
use Swarming\SubscribePro\Platform\Manager\Customer as CustomerManager;
use Swarming\SubscribePro\Model\Quote\QuoteItem\SubscriptionCreator as QuoteItemSubscriptionCreator;

class SubscriptionCreatorTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var \Swarming\SubscribePro\Model\Quote\SubscriptionCreator
     */
    protected $subscriptionCreator;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Model\Quote\QuoteItem\SubscriptionCreator
     */
    protected $quoteItemSubscriptionCreatorMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Platform\Manager\Customer
     */
    protected $platformCustomerManagerMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Vault\Api\PaymentTokenManagementInterface
     */
    protected $tokenManagementMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Helper\QuoteItem
     */
    protected $quoteItemHelperMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|\Swarming\SubscribePro\Helper\OrderItem
     */
    protected $orderItemHelperMock;

    protected function setUp(): void
    {
        $this->platformCustomerManagerMock = $this->getMockBuilder(CustomerManager::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->tokenManagementMock = $this->getMockBuilder(PaymentTokenManagementInterface::class)->getMock();

        $this->quoteItemHelperMock = $this->getMockBuilder(QuoteItemHelper::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->orderItemHelperMock = $this->getMockBuilder(OrderItemHelper::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->quoteItemSubscriptionCreatorMock = $this->getMockBuilder(QuoteItemSubscriptionCreator::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->subscriptionCreator = new SubscriptionCreator(
            $this->platformCustomerManagerMock,
            $this->tokenManagementMock,
            $this->quoteItemHelperMock,
            $this->orderItemHelperMock,
            $this->quoteItemSubscriptionCreatorMock
        );
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage The vault is not found.
     */
    public function testExecuteIfVaultNotFound()
    {
        $paymentEntityId = 321;

        $paymentMock = $this->createPaymentMock();
        $paymentMock->expects($this->once())
            ->method('getEntityId')
            ->willReturn($paymentEntityId);

        $this->tokenManagementMock->expects($this->once())
            ->method('getByPaymentId')
            ->with($paymentEntityId)
            ->willReturn(null);

        $orderMock = $this->createOrderMock();
        $orderMock->expects($this->once())
            ->method('getPayment')
            ->willReturn($paymentMock);

        $this->platformCustomerManagerMock->expects($this->never())
            ->method('getCustomerById');

        $quoteMock = $this->createQuoteMock();
        $quoteMock->expects($this->never())->method('getAllShippingAddresses');
        $quoteMock->expects($this->never())->method('getBillingAddress');
        $quoteMock->expects($this->never())->method('getAllVisibleItems');
        $quoteMock->expects($this->never())->method('getCustomerId');

        $this->subscriptionCreator->createSubscriptions($quoteMock, $orderMock);
    }

    /**
     * @expectedException \Exception
     * @expectedExceptionMessage The vault is not found.
     */
    public function testExecuteIfVaultNotActive()
    {
        $paymentEntityId = 321;

        $vaultMock = $this->createVaultMock();
        $vaultMock->expects($this->once())
            ->method('getIsActive')
            ->willReturn(false);

        $paymentMock = $this->createPaymentMock();
        $paymentMock->expects($this->once())
            ->method('getEntityId')
            ->willReturn($paymentEntityId);

        $this->tokenManagementMock->expects($this->once())
            ->method('getByPaymentId')
            ->with($paymentEntityId)
            ->willReturn($vaultMock);

        $orderMock = $this->createOrderMock();
        $orderMock->expects($this->once())
            ->method('getPayment')
            ->willReturn($paymentMock);

        $this->platformCustomerManagerMock->expects($this->never())
            ->method('getCustomerById');

        $quoteMock = $this->createQuoteMock();
        $quoteMock->expects($this->never())->method('getAllShippingAddresses');
        $quoteMock->expects($this->never())->method('getBillingAddress');
        $quoteMock->expects($this->never())->method('getAllVisibleItems');
        $quoteMock->expects($this->never())->method('getCustomerId');

        $this->subscriptionCreator->createSubscriptions($quoteMock, $orderMock);
    }

    /**
     * @param bool $isVirtual
     * @param bool $isSubscriptionEnabled
     * @param bool $isItemFulfilsSubscription
     * @dataProvider createSubscriptionsIfNotSubscriptionItemDataProvider
     */
    public function testCreateSubscriptionsIfNoSubscriptionShippingItems(
        $isVirtual,
        $isSubscriptionEnabled,
        $isItemFulfilsSubscription
    ) {
        $customerId = 233;
        $paymentEntityId = 1235;
        $paymentProfileId = 1232;
        $result = [
            SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [],
            SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 0
        ];

        $vaultMock = $this->createVaultMock();
        $vaultMock->expects($this->once())
            ->method('getIsActive')
            ->willReturn(true);
        $vaultMock->expects($this->atLeastOnce())
            ->method('getGatewayToken')
            ->willReturn($paymentProfileId);

        $paymentMock = $this->createPaymentMock();
        $paymentMock->expects($this->once())
            ->method('getEntityId')
            ->willReturn($paymentEntityId);

        $this->tokenManagementMock->expects($this->once())
            ->method('getByPaymentId')
            ->with($paymentEntityId)
            ->willReturn($vaultMock);

        $orderMock = $this->createOrderMock();
        $orderMock->expects($this->once())
            ->method('getPayment')
            ->willReturn($paymentMock);

        $platformCustomerMock = $this->createPlatformCustomerMock();

        $quoteItemMock = $this->createQuoteItemMock();
        $quoteItemMock->expects($this->atLeastOnce())
            ->method('getIsVirtual')
            ->willReturn($isVirtual);

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$quoteItemMock]);

        $quoteMock = $this->createQuoteMock();
        $quoteMock->expects($this->once())->method('getAllShippingAddresses')->willReturn([$addressMock]);
        $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$quoteItemMock]);
        $quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId);

        $this->platformCustomerManagerMock->expects($this->once())
            ->method('getCustomerById')
            ->with($customerId)
            ->willReturn($platformCustomerMock);

        $this->quoteItemHelperMock->expects($this->any())
            ->method('isSubscriptionEnabled')
            ->with($quoteItemMock)
            ->willReturn($isSubscriptionEnabled);

        $this->quoteItemHelperMock->expects($this->any())
            ->method('isItemFulfilsSubscription')
            ->with($quoteItemMock)
            ->willReturn($isItemFulfilsSubscription);

        $this->quoteItemSubscriptionCreatorMock->expects($this->never())->method('create');

        $this->assertEquals(
            $result,
            $this->subscriptionCreator->createSubscriptions($quoteMock, $orderMock)
        );
    }

    /**
     * @return array
     */
    public function createSubscriptionsIfNotSubscriptionItemDataProvider()
    {
        return [
            'Virtual product' => [
                'isVirtual' => true,
                'isSubscriptionEnabled' => false,
                'isItemFulfilsSubscription' => false
            ],
            'Subscription not enabled' => [
                'isVirtual' => false,
                'isSubscriptionEnabled' => false,
                'isItemFulfilsSubscription' => false
            ],
            'Quote item fulfils subscription' => [
                'isVirtual' => false,
                'isSubscriptionEnabled' => true,
                'isItemFulfilsSubscription' => true
            ],
        ];
    }

    /**
     * @param int $paymentEntityId
     * @param int $paymentProfileId
     * @param int $customerId
     * @param int $platformCustomerId
     * @param \Magento\Quote\Model\Quote\Item[] $quoteItems
     * @param array $subscriptionIds
     * @param array $result
     * @dataProvider createSubscriptionsWithoutVirtualItemsDataProvider
     */
    public function testCreateSubscriptionsWithoutVirtualItems(
        $paymentEntityId,
        $paymentProfileId,
        $customerId,
        $platformCustomerId,
        $quoteItems,
        $subscriptionIds,
        $result
    ) {
        $vaultMock = $this->createVaultMock();
        $vaultMock->expects($this->once())
            ->method('getIsActive')
            ->willReturn(true);
        $vaultMock->expects($this->atLeastOnce())
            ->method('getGatewayToken')
            ->willReturn($paymentProfileId);

        $paymentMock = $this->createPaymentMock();
        $paymentMock->expects($this->once())
            ->method('getEntityId')
            ->willReturn($paymentEntityId);

        $this->tokenManagementMock->expects($this->once())
            ->method('getByPaymentId')
            ->with($paymentEntityId)
            ->willReturn($vaultMock);

        $orderMock = $this->createOrderMock();
        $orderMock->expects($this->once())
            ->method('getPayment')
            ->willReturn($paymentMock);

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())->method('getAllVisibleItems')->willReturn($quoteItems);

        $platformCustomerMock = $this->createPlatformCustomerMock();
        $platformCustomerMock->expects($this->any())->method('getId')->willReturn($platformCustomerId);

        $quoteMock = $this->createQuoteMock();
        $quoteMock->expects($this->once())->method('getAllShippingAddresses')->willReturn([$addressMock]);
        $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([]);
        $quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId);

        $subscriptionMap = [];
        foreach ($quoteItems as $key => $quoteItem) {
            $subscriptionMap[$key] = [
                $quoteItem,
                $platformCustomerId,
                $paymentProfileId,
                $addressMock,
                $subscriptionIds[$key]
            ];
        }

        $this->platformCustomerManagerMock->expects($this->once())
            ->method('getCustomerById')
            ->with($customerId)
            ->willReturn($platformCustomerMock);

        $this->quoteItemHelperMock->expects($this->exactly(count($quoteItems)))
            ->method('isSubscriptionEnabled')
            ->willReturnMap(array_map(function ($quoteItem) {
                return [$quoteItem, true];
            }, $quoteItems));

        $this->quoteItemHelperMock->expects($this->exactly(count($quoteItems)))
            ->method('isItemFulfilsSubscription')
            ->willReturnMap(array_map(function ($quoteItem) {
                return [$quoteItem, false];
            }, $quoteItems));

        $this->quoteItemSubscriptionCreatorMock->expects($this->exactly(count($quoteItems)))
            ->method('create')
            ->willReturnMap($subscriptionMap);

        $this->assertEquals(
            $result,
            $this->subscriptionCreator->createSubscriptions($quoteMock, $orderMock)
        );
    }

    /**
     * @return array
     */
    public function createSubscriptionsWithoutVirtualItemsDataProvider()
    {
        return [
            'Empty quote' => [
                'paymentEntityId' => 123,
                'paymentProfileId' => 123123123,
                'customerId' => 22323,
                'platformCustomerId' => 4124124,
                'quoteItems' => [],
                'subscriptionIds' => [],
                'result' => [
                    SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [],
                    SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 0
                ]
            ],
            'All quote items valid' => [
                'paymentEntityId' => 231,
                'paymentProfileId' => 53432,
                'customerId' => 8878,
                'platformCustomerId' => 231,
                'quoteItems' => [$this->createQuoteItemMock(), $this->createQuoteItemMock()],
                'subscriptionIds' => [12, 34],
                'result' => [
                    SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [12, 34],
                    SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 0
                ]
            ],
            'With not created subscriptions' => [
                'paymentEntityId' => 321,
                'paymentProfileId' => 213,
                'customerId' => 1098678,
                'platformCustomerId' => 5435,
                'quoteItems' => [
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock()
                ],
                'subscriptionIds' => [null, 34, 56],
                'result' => [
                    SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [34, 56],
                    SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 1
                ]
            ],
        ];
    }

    /**
     * @param int $paymentEntityId
     * @param int $paymentProfileId
     * @param int $customerId
     * @param int $platformCustomerId
     * @param \Magento\Quote\Model\Quote\Item[] $quoteItems
     * @param array $subscriptionIds
     * @param int $virtualSubscriptionId
     * @param array $result
     * @dataProvider createSubscriptionsWithVirtualItemsDataProvider
     */
    public function testCreateSubscriptionsWithVirtualItems(
        $paymentEntityId,
        $paymentProfileId,
        $customerId,
        $platformCustomerId,
        $quoteItems,
        $subscriptionIds,
        $virtualSubscriptionId,
        $result
    ) {
        $vaultMock = $this->createVaultMock();
        $vaultMock->expects($this->once())
            ->method('getIsActive')
            ->willReturn(true);
        $vaultMock->expects($this->atLeastOnce())
            ->method('getGatewayToken')
            ->willReturn($paymentProfileId);

        $paymentMock = $this->createPaymentMock();
        $paymentMock->expects($this->once())
            ->method('getEntityId')
            ->willReturn($paymentEntityId);

        $this->tokenManagementMock->expects($this->once())
            ->method('getByPaymentId')
            ->with($paymentEntityId)
            ->willReturn($vaultMock);

        $orderMock = $this->createOrderMock();
        $orderMock->expects($this->once())
            ->method('getPayment')
            ->willReturn($paymentMock);

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())->method('getAllVisibleItems')->willReturn($quoteItems);

        $platformCustomerMock = $this->createPlatformCustomerMock();
        $platformCustomerMock->expects($this->any())->method('getId')->willReturn($platformCustomerId);

        $virtualQuoteItemMock = $this->createQuoteItemMock();
        $virtualQuoteItemMock->expects($this->once())->method('getIsVirtual')->willReturn(true);

        $quoteMock = $this->createQuoteMock();
        $quoteMock->expects($this->once())->method('getAllShippingAddresses')->willReturn([$addressMock]);
        $quoteMock->expects($this->once())->method('getAllVisibleItems')->willReturn([$virtualQuoteItemMock]);
        $quoteMock->expects($this->once())->method('getCustomerId')->willReturn($customerId);

        $subscriptionMap = [];
        foreach ($quoteItems as $key => $quoteItem) {
            $subscriptionMap[$key] = [
                $quoteItem,
                $platformCustomerId,
                $paymentProfileId,
                $addressMock,
                $subscriptionIds[$key]
            ];
        }
        $subscriptionMap[] = [
            $virtualQuoteItemMock,
            $platformCustomerId,
            $paymentProfileId,
            null,
            $virtualSubscriptionId
        ];

        $isSubscriptionEnabledMap = array_map(function ($quoteItem) {
            return [$quoteItem, true];
        }, $quoteItems);
        $isSubscriptionEnabledMap[] = [$virtualQuoteItemMock, true];

        $isItemFulfilsSubscriptionMap = array_map(function ($quoteItem) {
            return [$quoteItem, false];
        }, $quoteItems);
        $isItemFulfilsSubscriptionMap[] = [$virtualQuoteItemMock, false];

        $this->platformCustomerManagerMock->expects($this->once())
            ->method('getCustomerById')
            ->with($customerId)
            ->willReturn($platformCustomerMock);

        $this->quoteItemHelperMock->expects($this->exactly(count($isSubscriptionEnabledMap)))
            ->method('isSubscriptionEnabled')
            ->willReturnMap($isSubscriptionEnabledMap);

        $this->quoteItemHelperMock->expects($this->exactly(count($isItemFulfilsSubscriptionMap)))
            ->method('isItemFulfilsSubscription')
            ->willReturnMap($isItemFulfilsSubscriptionMap);

        $this->quoteItemSubscriptionCreatorMock->expects($this->exactly(count($subscriptionMap)))
            ->method('create')
            ->willReturnMap($subscriptionMap);

        $this->assertEquals(
            $result,
            $this->subscriptionCreator->createSubscriptions($quoteMock, $orderMock)
        );
    }

    /**
     * @return array
     */
    public function createSubscriptionsWithVirtualItemsDataProvider()
    {
        return [
            'Fail to create subscription from virtual product' => [
                'paymentEntityId' => 123,
                'paymentProfileId' => 65435,
                'customerId' => 543,
                'platformCustomerId' => 5346,
                'quoteItems' => [
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock()
                ],
                'subscriptionIds' => [123, null, 78],
                'virtualSubscriptionId' => null,
                'result' => [
                    SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [123, 78],
                    SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 2
                ]
            ],
            'Subscription created for virtual product' => [
                'paymentEntityId' => 231,
                'paymentProfileId' => 65435,
                'customerId' => 543,
                'platformCustomerId' => 5346,
                'quoteItems' => [
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock(),
                    $this->createQuoteItemMock()
                ],
                'subscriptionIds' => [123, null, 78],
                'virtualSubscriptionId' => 431,
                'result' => [
                    SubscriptionCreator::CREATED_SUBSCRIPTION_IDS => [123, 78, 431],
                    SubscriptionCreator::FAILED_SUBSCRIPTION_COUNT => 1
                ]
            ],
        ];
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\OrderInterface
     */
    private function createOrderMock()
    {
        return $this->getMockBuilder(OrderInterface::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Sales\Api\Data\OrderPaymentInterface
     */
    private function createPaymentMock()
    {
        return $this->getMockBuilder(OrderPaymentInterface::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Vault\Api\Data\PaymentTokenInterface
     */
    private function createVaultMock()
    {
        return $this->getMockBuilder(PaymentTokenInterface::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Item
     */
    private function createQuoteItemMock()
    {
        return $this->getMockBuilder(QuoteItem::class)
            ->disableOriginalConstructor()
            ->setMethods(['getIsVirtual', '__wakeup'])
            ->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote
     */
    private function createQuoteMock()
    {
        return $this->getMockBuilder(Quote::class)
            ->disableOriginalConstructor()
            ->setMethods(
                [
                    'getCustomerId',
                    'getAllShippingAddresses',
                    'getBillingAddress',
                    'getAllVisibleItems',
                    '__wakeup'
                ]
            )
            ->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\SubscribePro\Service\Customer\CustomerInterface
     */
    private function createPlatformCustomerMock()
    {
        return $this->getMockBuilder(PlatformCustomerInterface::class)->getMock();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Magento\Quote\Model\Quote\Address
     */
    private function createAddressMock()
    {
        return $this->getMockBuilder(QuoteAddress::class)
            ->disableOriginalConstructor()
            ->getMock();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.geolocate.webservices.svcv2;

import jakarta.jws.WebMethod;
import jakarta.jws.WebParam;
import jakarta.jws.WebResult;
import jakarta.jws.WebService;
import jakarta.jws.soap.SOAPBinding;
import jakarta.xml.bind.annotation.XmlSeeAlso;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 3.0.2
 * Generated source version: 3.0
 *
 */
@WebService(name = "geolocatesvcHttpPost", targetNamespace = "http://geo-locate.org/webservices/")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface GeolocatesvcHttpPost {

    /**
     * Georeferences a locality description. returns a 'Georef_Result_Set' given Country, State, County, LocalityString and boolean georeferencing options.
Use this one if you are unsure of which to use.
Language key refers to an integer representing different languages libraries. Will default to basic english (languagekey=0) if invalid key is provided.
*GLOBAL*
     *
     * @param country
     * @param doPoly
     * @param displacePoly
     * @param county
     * @param localityString
     * @param doUncert
     * @param polyAsLinkID
     * @param restrictToLowestAdm
     * @param state
     * @param findWaterbody
     * @param languageKey
     * @param hwyX
     * @return
     *     returns org.geolocate.webservices.svcv2.GeorefResultSet
     */
    @WebMethod(operationName = "Georef2")
    @WebResult(name = "Georef_Result_Set", targetNamespace = "http://geo-locate.org/webservices/", partName = "Body")
    public GeorefResultSet georef2(
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "Country")
        String country,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "State")
        String state,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "County")
        String county,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LocalityString")
        String localityString,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "HwyX")
        String hwyX,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "FindWaterbody")
        String findWaterbody,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "RestrictToLowestAdm")
        String restrictToLowestAdm,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doUncert")
        String doUncert,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doPoly")
        String doPoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "displacePoly")
        String displacePoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "polyAsLinkID")
        String polyAsLinkID,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LanguageKey")
        String languageKey);

    /**
     * Georeferences a locality description. returns a 'Georef_Result_Set' given vLocality, vGeorgraphy and boolean georeferencing options.  VLocality and VGeogrpahy are fields specific to BioGeomancer.
Language key refers to an integer representing different languages libraries. Will default to basic english (0) if invalid key is provided
*North American Localities Only*
     *
     * @param vGeography
     * @param doPoly
     * @param displacePoly
     * @param vLocality
     * @param doUncert
     * @param polyAsLinkID
     * @param restrictToLowestAdm
     * @param findWaterbody
     * @param languageKey
     * @param hwyX
     * @return
     *     returns org.geolocate.webservices.svcv2.GeorefResultSet
     */
    @WebMethod(operationName = "Georef3")
    @WebResult(name = "Georef_Result_Set", targetNamespace = "http://geo-locate.org/webservices/", partName = "Body")
    public GeorefResultSet georef3(
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "vLocality")
        String vLocality,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "vGeography")
        String vGeography,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "HwyX")
        String hwyX,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "FindWaterbody")
        String findWaterbody,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "RestrictToLowestAdm")
        String restrictToLowestAdm,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doUncert")
        String doUncert,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doPoly")
        String doPoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "displacePoly")
        String displacePoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "polyAsLinkID")
        String polyAsLinkID,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LanguageKey")
        String languageKey);

    /**
     * Snaps given point to nearest water body found from given locality description terms.
*U.S. localities only, county required*
     *
     * @param wgs84Latitude
     * @param country
     * @param wgs84Longitude
     * @param county
     * @param localityString
     * @param state
     * @return
     *     returns org.geolocate.webservices.svcv2.GeographicPoint
     */
    @WebMethod(operationName = "SnapPointToNearestFoundWaterBody2")
    @WebResult(name = "GeographicPoint", targetNamespace = "http://geo-locate.org/webservices/", partName = "Body")
    public GeographicPoint snapPointToNearestFoundWaterBody2(
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "Country")
        String country,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "State")
        String state,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "County")
        String county,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LocalityString")
        String localityString,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "WGS84Latitude")
        String wgs84Latitude,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "WGS84Longitude")
        String wgs84Longitude);

    /**
     * Returns an uncertainty polygon given the unique id used to generate it.
     *
     * @param polyGenerationKey
     * @return
     *     returns java.lang.String
     */
    @WebMethod(operationName = "CalcUncertaintyPoly")
    @WebResult(name = "string", targetNamespace = "http://geo-locate.org/webservices/", partName = "Body")
    public String calcUncertaintyPoly(
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "PolyGenerationKey")
        String polyGenerationKey);

    /**
     * Georeferences a locality description. returns a 'Georef_Result_Set' given Country, State, County, LocalityString and boolean georeferencing options.  Also adds results from Biogeomancer to the mix. May take a long time to get results back from BG.
Language key refers to an integer representing different languages libraries. Will default to basic english (languagekey=0) if invalid key is provided.
*GLOBAL*
     *
     * @param country
     * @param doPoly
     * @param displacePoly
     * @param county
     * @param localityString
     * @param doUncert
     * @param polyAsLinkID
     * @param restrictToLowestAdm
     * @param state
     * @param findWaterbody
     * @param languageKey
     * @param hwyX
     * @return
     *     returns org.geolocate.webservices.svcv2.GeorefResultSet
     */
    @WebMethod(operationName = "Georef2plusBG")
    @WebResult(name = "Georef_Result_Set", targetNamespace = "http://geo-locate.org/webservices/", partName = "Body")
    public GeorefResultSet georef2PlusBG(
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "Country")
        String country,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "State")
        String state,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "County")
        String county,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LocalityString")
        String localityString,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "HwyX")
        String hwyX,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "FindWaterbody")
        String findWaterbody,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "RestrictToLowestAdm")
        String restrictToLowestAdm,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doUncert")
        String doUncert,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "doPoly")
        String doPoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "displacePoly")
        String displacePoly,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "polyAsLinkID")
        String polyAsLinkID,
        @WebParam(name = "string", targetNamespace = "http://www.w3.org/2001/XMLSchema", partName = "LanguageKey")
        String languageKey);

}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Net
{
  public partial class HttpListenerException : System.ComponentModel.Win32Exception
  {
    #region Methods and constructors
    protected HttpListenerException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
    {
      Contract.Requires(serializationInfo != null);
    }

    public HttpListenerException()
    {
    }

    public HttpListenerException(int errorCode)
    {
    }

    public HttpListenerException(int errorCode, string message)
    {
    }
    #endregion

    #region Properties and indexers
    public override int ErrorCode
    {
      get
      {
        return default(int);
      }
    }
    #endregion
  }
}


text:
var req = new sql.Request(conn);

req.input('name', sql.VarChar, 'Fred');

var sqlStr = 'SELECT * FROM myTable WHERE name = @name';
req.query(sqlStr, function(err, rs) {

});


text:
using System.Collections;
using Archetype.Models;
using Archetype.Serializer.Test.Base;
using Archetype.Serializer.Test.Helpers;
using Newtonsoft.Json;
using NUnit.Framework;

namespace Archetype.Serializer.Test
{
    [TestFixture]
    public class SerializationBasicModelTests : TestBase
    {
        private ModelHelper _modelHelper;
        private const int _serializationTestsId = 1074;

        [TestFixtureSetUp]
        public void SetUp()
        {
            _modelHelper = new ModelHelper();
        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            _modelHelper = null;
        }

        [TestCase("SimpleModel")]
        [TestCase("SimpleModelList")]
        [TestCase("NestedModel")]
        [TestCase("NestedModelList")]
        public void Model_Serializes_ToArchetypeJson(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias);
            var json = model.ToArchetypeJson(Formatting.Indented);

            Assert.IsTrue(Serializer.Helpers.IsArchetypeJson(json));
        }

        [TestCase("SimpleModel")]
        [TestCase("SimpleModelList")]
        [TestCase("NestedModel")]
        [TestCase("NestedModelList")]
        public void Model_Serializes_And_Deserializes_ToArchetype(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias);
            var json = model.ToArchetypeJson();

            Assert.IsInstanceOf<ArchetypeModel>(JsonConvert.DeserializeObject<ArchetypeModel>(json));
        }

        [TestCase("SimpleModel")]
        [TestCase("NestedModel")]
        public void Model_Serializes_And_Deserializes(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias);
            var json = model.ToArchetypeJson();
            var actual = GetModelFromJson(modelAlias, json);

            AssertAreEqual(model, actual);
        }

        [TestCase("SimpleModelList")]
        [TestCase("NestedModelList")]
        public void ModelList_Serializes_And_Deserializes(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias) as IList;
            var json = model.ToArchetypeJson();
            var actual = GetModelFromJson(modelAlias, json) as IList;

            for (var i = 0; i < actual.Count; i++)
            {
                AssertAreEqual(model[i], actual[i]);
            }
        }

        [TestCase("SimpleModel")]
        [TestCase("NestedModel")]
        public void Model_SaveAndPublish_ReturnsCorrectModel(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias);
            var json = model.ToArchetypeJson();
            var propAlias = ToPropertyAlias(modelAlias);

            var result = ConsoleHelper.Instance.ConsoleCommands.SaveAndPublishArchetypeJson(propAlias,
                json, _serializationTestsId);

            Assert.AreEqual(true, result);

            var resultJson = ConsoleHelper.Instance.ConsoleCommands.GetArchetypeJsonFor(propAlias, _serializationTestsId);

            var resultModel = GetModelFromJson(modelAlias, resultJson);
            AssertAreEqual(model, resultModel);
        }

        [TestCase("SimpleModelList")]
        [TestCase("NestedModelList")]
        public void ModelList_SaveAndPublish_ReturnsCorrectModel(string modelAlias)
        {
            var model = _modelHelper.GetModel(modelAlias) as IList;
            var json = model.ToArchetypeJson();
            var propAlias = ToPropertyAlias(modelAlias);

            var result = ConsoleHelper.Instance.ConsoleCommands.SaveAndPublishArchetypeJson(propAlias,
                json, _serializationTestsId);

            Assert.AreEqual(true, result);

            var resultJson = ConsoleHelper.Instance.ConsoleCommands.GetArchetypeJsonFor(propAlias, _serializationTestsId);

            var resultModel = GetModelFromJson(modelAlias, resultJson) as IList;

            for (var i = 0; i < resultModel.Count; i++)
            {
                AssertAreEqual(model[i], resultModel[i]);
            }
        }
    }
}


text:
package main

import (
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	Test()
	args := SRVargs{service: "xmpp-server", proto: "tcp", name: "google.com"}
	resp, err := GetAddressFromSRV(args)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)

	}

	fmt.Printf("resp.cname : %s \n", resp.cname)
	fmt.Printf("resp.address : %s \n", resp.address)
}

type SRVargs struct {
	service, proto, name string
}

type SRVresp struct {
	cname, address string
}

func GetAddressFromSRV(args SRVargs) (resp SRVresp, err error) {

	// lookup SRV records
	cname, addresses, err := net.LookupSRV(args.service, args.proto, args.name)
	if err != nil {
		return resp, err
	}

	fmt.Printf("cname : %s \n", cname)
	resp.cname = cname

	// return first records
	ap := fmt.Sprintf("http://%s:%d", strings.TrimRight(addresses[0].Target, "."), addresses[0].Port)
	fmt.Println(ap)
	resp.address = ap

	return resp, nil

}

func Test() {

	// lookup SRV records
	cname, addresses, err := net.LookupSRV("xmpp-server", "tcp", "google.com")
	//	cname, addresses, err := net.LookupSRV("", "", "_xmpp-server._tcp.google.com")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("cname : %s \n", cname)
	ap := fmt.Sprintf("http://%s:%d", strings.TrimRight(addresses[0].Target, "."), addresses[0].Port)
	fmt.Println(ap)
}


text:
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Gallio.Common;

namespace Gallio.Framework.Data.Generation
{
    /// <summary>
    /// Generator of sequential <see cref="double"/> values.
    /// </summary>
    public class SequentialDoubleGenerator : SequentialGenerator<double>
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public SequentialDoubleGenerator()
        {
        }

        /// <inheritdoc />
        protected override IEnumerable<double> GetStartStepCountSequence()
        {
            CheckProperty(Start.Value, "Start");
            CheckProperty(Step.Value, "Step");
            CheckProperty(Count.Value, "Count");

            if (Count.Value < 0)
                throw new GenerationException("The 'Count' property must be greater than or equal to zero.");

            double d = Start.Value;

            for (int i = 0; i < Count; i++, d += Step.Value)
            {
                if (DoFilter(d))
                {
                    yield return d;
                }
            }
        }

        /// <inheritdoc />
        protected override IEnumerable<double> GetStartEndCountSequence()
        {
            CheckProperty(Start.Value, "Start");
            CheckProperty(End.Value, "End");
            CheckProperty(Count.Value, "Count");

            if (Count.Value < 0)
                throw new GenerationException("The 'Count' property must be greater than or equal to zero.");

            double d = Start.Value;
            double step = Count.Value <= 1 ? 1 : (End.Value - Start.Value) / (Count.Value - 1);

            for (int i = 0; i < Count; i++, d += step)
            {
                if (DoFilter(d))
                {
                    yield return d;
                }
            }
        }

        /// <inheritdoc />
        protected override IEnumerable<double> GetStartEndStepSequence()
        {
            CheckProperty(Start.Value, "Start");
            CheckProperty(End.Value, "End");
            CheckProperty(Step.Value, "Step");

            if (Step.Value == 0)
                throw new GenerationException("The 'Step' property can not be equal to zero.");

            if (End.Value != Start.Value && Math.Sign(End.Value - Start.Value) != Math.Sign(Step.Value))
                throw new GenerationException("The sequence direction specified by the 'Start' and 'End' properties " +
                    "must be consistent with the sign of the 'Step' property.");

            Func<double, bool> stopCriterion;

            if (Math.Sign(Step.Value) >= 0)
                stopCriterion = d => (d <= End.Value);
            else
                stopCriterion = d => (d >= End.Value);

            for (double d = Start.Value; stopCriterion(d); d += Step.Value)
            {
                if (DoFilter(d))
                {
                    yield return d;
                }
            }
        }

        /// <summary>
        /// Gets the default step.
        /// </summary>
        protected override double DefaultStep
        {
            get
            {
                return 1;
            }
        }
    }
}


text:
<?php
// src/eveg/AppBundle/Controller/SyntaxonRestController.php

namespace eveg\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use FOS\RestBundle\Controller\FOSRestController;
use JMS\Serializer\SerializationContext;
use FOS\RestBundle\Controller\Annotations\Get;

// routes are automaticly generated by FOSRestBundle using the name of a function
// ex : public function getTestAction will set up an 'api_get_test' route

class SyntaxonTbRestController extends FOSRestController
{
	/**
	 * GET Route annotation.
	 * @Get("/tb/syntaxon/{id}")
	 */
	public function getSyntaxonAction($id, Request $request)
	{

		// Get host name
		$hostName = $request->getHost();
		// Check if host is TB or if you're logged in as super-admin
		//if(($hostName !== $this->container->getParameter('eveg')['tb_host']) and (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN'))) Throw new AccessDeniedHttpException();

		// New view
		$view = $this->view();
		$view->setSerializationContext(SerializationContext::create()->setGroups(array('API')));

		// Grabbing SyntaxonCore repository
		$em = $this->getDoctrine()->getManager();
		$scRepo = $em->getRepository('evegAppBundle:SyntaxonCore');

		// Find syntaxon
		$syntaxon = $scRepo->findById($id);

		// Check if unique result
		//...

		// Return
		$view->setData($syntaxon);
		return $view;

	}
}


text:
from __future__ import absolute_import, division, print_function
from builtins import *
# pylint: enable=wildcard-import,redefined-builtin,unused-wildcard-import

from functools import reduce

def drop_duplicates(mapping, how='both'):
    # Determine which columns to consider for duplicates.
    if how == 'none':
        return mapping
    if how == 'otm':
        columns = [mapping.columns[0]]
    elif how == 'mto':
        columns = [mapping.columns[1]]
    elif how == 'both':
        columns = [mapping.columns[0], mapping.columns[1]]
    else:
        raise ValueError(('Unknown value for how ({}). Possible values are '
                          '\'none\', \'otm\' (one-to-many), \'mto\' '
                          '(many-to-one) or \'both\'').format(how))

    # Apply column masks.
    masks = [_duplicate_mask(mapping, c) for c in columns]
    mask = reduce(lambda m1, m2: m1 | m2, masks)
    masked_mapping = mapping.ix[~mask]

    return masked_mapping

def _duplicate_mask(frame, column):
    duplicate_rows = frame.duplicated(subset=column)
    duplicate_values = set(frame.ix[duplicate_rows][column])
    return frame[column].isin(duplicate_values)


text:
package io.tilt.minka.spectator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.Validate;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Facility to create Wells, which are ZNodes that can -only- be updated,
 * and hooked to a Listener for its events
 *
 * @author Cristian Gonzalez
 * @since Ene 16, 2016
 *
 */
public class Wells extends NodeCacheable  {

    private static final Logger logger = LoggerFactory.getLogger(Wells.class);
    public static final String WELL_PREFIX = "/well:";

    public Wells() {
        super();
    }

    public Wells(Spectator spec) {
        super(spec);
    }

    public Wells(final String zookeeperHostPort) {
        super(zookeeperHostPort, null);
    }

    public Wells(final String zookeeperHostPort, String logId) {
        super(zookeeperHostPort, logId);
    }

    /**
     * Run a consumer when the Well gets updated with new content
     *
     * @param wellName     a unique name within the ensemble for the updates to arrive
     * @param consumer     a message consumer to be called on new updates
     * @param <T> 		   the type
     * @return             whether or not the subscription succeed
     */
    public <T> boolean runOnUpdate(
            final String wellName,
            final Consumer<MessageMetadata> consumer) {

        boolean added = false;
        if (!(added = checkExistance(wellName, consumer))) {
            final WellListener event = new WellListener(wellName, consumer);
            added = createCache(WELL_PREFIX, wellName, consumer, event);
        }
        return added;
    }

    /**
     * If you plan to dinamically consume from a lot of Wells, you should release them when no longer care.
     * Otherwise non closed subscription resources will only be released at shutdown
     * (subject to proper termination)
     * @param wellName	the name of the refreshing well
     */
    public void closeWell(final String wellName) {
        Set<UserInstanceObject> set = getUserMap().get(wellName);
        if (set != null) {
            Iterator<UserInstanceObject> it = set.iterator();
            while (it.hasNext()) {
                UserInstanceObject uio = it.next();
                if (uio.getTree() != null) {
                    uio.getTree().close();
                    it.remove();
                }
            }
        }
    }

    /**
     * Update a well with a message to be received by all Consumers
     *
     * @param wellName     the well name where the object is send to update
     * @param message       the payload of the message to send
     * @return              whether the message was successfully sent or not
     */
    public boolean updateWell(final String wellName, final Object message) {
        Validate.notNull(wellName, "name of the queue to post to is required !");
        Validate.notNull(message, "message to post is required !");

        return updatePath(WELL_PREFIX, wellName, message);
    }

    protected class WellListener implements TreeCacheListener {

        public final String name;
        private final Consumer<MessageMetadata> userListener;

        public WellListener(String name, Consumer<MessageMetadata> userListener) {
            super();
            this.name = name;
            this.userListener = userListener;
        }

        @Override
        public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
            if (event.getType() == TreeCacheEvent.Type.NODE_ADDED || event.getType() == TreeCacheEvent.Type.NODE_UPDATED) {
                readOneMessage(event.getData(), client);
            } else if (event.getType() == TreeCacheEvent.Type.CONNECTION_LOST) {
                // TODO nothing i think
            }
        }

        protected void readOneMessage(final ChildData data, final CuratorFramework client) {
            final String parentPath = Wells.WELL_PREFIX + name;
            try {
                final List<MessageMetadata> datas = new ArrayList<>();
                bytesToMessage(data.getStat(), datas, data.getPath(), data.getData());
                if (logger.isDebugEnabled() && datas!=null) {
                    logger.debug("{}: ({}) New update on queue: {} now version: {}", getClass().getSimpleName(),
                            getLogId(), name, datas.size(), data.getStat().getVersion());
                }

                for (final MessageMetadata meta: datas) {
                    userListener.accept(meta);
                }
            } catch (IllegalStateException ise) {
                // no problem machine is going down
                logger.warn("{}: ({}) Node going down while consuming topic messages ({})",
                        getClass().getSimpleName(), getLogId(), ise.getMessage());
            } catch (Exception e) {
                logger.error("{}: ({}) Unexpected error while reading queue: {}", getClass().getSimpleName(), getLogId(),
                        parentPath, e);
            }
        }

        private void bytesToMessage(final Stat childStat, final List<MessageMetadata> datas,
                final String childNode, final byte[] in) {
            try {
                Object o = SerializationUtils.deserialize(in);
                if (o!=null) {
                    datas.add((MessageMetadata)o);
                }
            } catch (Exception e) {
                logger.warn("{}: ({}) Deserializing error while reading on queue: {} for "
                        + "new message: {}, size: {}, created: {}", getClass().getSimpleName(), getLogId(), name,
                        childNode, childStat.getDataLength(), childStat.getCtime());
            }
        }
    }

}


text:
package io.openwire.codec.v7;

import io.openwire.codec.BaseDataStreamMarshaller;
import io.openwire.codec.BooleanStream;
import io.openwire.codec.OpenWireFormat;
import io.openwire.commands.DataStructure;
import io.openwire.commands.JournalQueueAck;
import io.openwire.commands.MessageAck;
import io.openwire.commands.OpenWireDestination;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public class JournalQueueAckMarshaller extends BaseDataStreamMarshaller {

    /**
     * Return the type of Data Structure we marshal
     *
     * @return short representation of the type data structure
     */
    @Override
    public byte getDataStructureType() {
        return JournalQueueAck.DATA_STRUCTURE_TYPE;
    }

    /**
     * @return a new object instance
     */
    @Override
    public DataStructure createObject() {
        return new JournalQueueAck();
    }

    /**
     * Un-marshal an object instance from the data input stream
     *
     * @param o
     *        the object to un-marshal
     * @param dataIn
     *        the data input stream to build the object from
     * @throws IOException
     */
    @Override
    public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
        super.tightUnmarshal(wireFormat, o, dataIn, bs);

        JournalQueueAck info = (JournalQueueAck) o;
        info.setDestination((OpenWireDestination) tightUnmarsalNestedObject(wireFormat, dataIn, bs));
        info.setMessageAck((MessageAck) tightUnmarsalNestedObject(wireFormat, dataIn, bs));
    }

    /**
     * Write the booleans that this object uses to a BooleanStream
     */
    @Override
    public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
        JournalQueueAck info = (JournalQueueAck) o;

        int rc = super.tightMarshal1(wireFormat, o, bs);
        rc += tightMarshalNestedObject1(wireFormat, info.getDestination(), bs);
        rc += tightMarshalNestedObject1(wireFormat, info.getMessageAck(), bs);

        return rc + 0;
    }

    /**
     * Write a object instance to data output stream
     *
     * @param o
     *        the instance to be marshaled
     * @param dataOut
     *        the output stream
     * @throws IOException
     *         thrown if an error occurs
     */
    @Override
    public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
        super.tightMarshal2(wireFormat, o, dataOut, bs);

        JournalQueueAck info = (JournalQueueAck) o;
        tightMarshalNestedObject2(wireFormat, info.getDestination(), dataOut, bs);
        tightMarshalNestedObject2(wireFormat, info.getMessageAck(), dataOut, bs);
    }

    /**
     * Un-marshal an object instance from the data input stream
     *
     * @param o
     *        the object to un-marshal
     * @param dataIn
     *        the data input stream to build the object from
     * @throws IOException
     */
    @Override
    public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
        super.looseUnmarshal(wireFormat, o, dataIn);

        JournalQueueAck info = (JournalQueueAck) o;
        info.setDestination((OpenWireDestination) looseUnmarsalNestedObject(wireFormat, dataIn));
        info.setMessageAck((MessageAck) looseUnmarsalNestedObject(wireFormat, dataIn));
    }

    /**
     * Write the booleans that this object uses to a BooleanStream
     */
    @Override
    public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
        JournalQueueAck info = (JournalQueueAck) o;

        super.looseMarshal(wireFormat, o, dataOut);
        looseMarshalNestedObject(wireFormat, info.getDestination(), dataOut);
        looseMarshalNestedObject(wireFormat, info.getMessageAck(), dataOut);
    }
}


text:
package com.dhiana.arpostits.model;

import java.util.ArrayList;
import java.util.List;

public class Item {

    private Integer id;
    private Integer marker;
    private Integer progress;
    private String title;
    private Boolean ready;
    private Boolean blocked;
    private List<Task> tasks = new ArrayList<Task>();

    public static final int GREEN = 0;
    public static final int YELLOW = 1;
    public static final int RED = 2;

    public Integer getId() {
        return id;
    }

    public Integer getMarker() {
        return marker;
    }

    public void setMarker(Integer marker) {
        this.marker = marker;
    }

    public Integer getProgress() {
        return progress;
    }

    public void setProgress(Integer progress) {
        this.progress = progress;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Boolean getReady() {
        return ready;
    }

    public void setReady(Boolean ready) {
        this.ready = ready;
    }

    public Boolean getBlocked() {
        return blocked;
    }

    public void setBlocked(Boolean blocked) {
        this.blocked = blocked;
    }

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }

    public int getColor() {
        if (blocked) {
            return RED;
        } else if (ready) {
            return GREEN;
        }
        return YELLOW;
    }

}


text:
package io.aos.endpoint.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServer {

    public static void serve(int port) throws IOException {
        System.out.println("Listening for connections on port " + port);
        ServerSocketChannel serverChannel;
        Selector selector;

        serverChannel = ServerSocketChannel.open();
        ServerSocket ss = serverChannel.socket();
        InetSocketAddress address = new InetSocketAddress(port);
        ss.bind(address);
        serverChannel.configureBlocking(false);
        selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        final ByteBuffer msg = ByteBuffer.wrap("Hi!\r\n".getBytes());

        while (true) {

            try {
                selector.select();
            }
            catch (IOException ex) {
                ex.printStackTrace();
                // handle in a proper way
                break;
            }

            Set readyKeys = selector.selectedKeys();
            Iterator iterator = readyKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = (SelectionKey) iterator.next();
                iterator.remove();
                try {
                    if (key.isAcceptable()) {
                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        SocketChannel client = server.accept();
                        System.out.println("Accepted connection from " + client);
                        client.configureBlocking(false);
                        client.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, msg.duplicate());
                    }
                    if (key.isWritable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        while (buffer.hasRemaining()) {
                            if (client.write(buffer) == 0) {
                                break;
                            }
                        }
                        client.close();
                    }
                }
                catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    }
                    catch (IOException cex) {
                    }
                }
            }
        }
    }
}


text:
package org.shanbo.feluca.distribute.launch;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.concurrent.Future;

import org.shanbo.feluca.paddle.GlobalConfig;
import org.shanbo.feluca.util.concurrent.ConcurrentExecutor;

import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Function;
import com.google.common.collect.Lists;

public class LoopingRunner {
	List<GlobalConfig> configs;
	public LoopingRunner(JSONArray configs){
		this.configs = Lists.newArrayList();
		for(int i = 0 ; i < configs.size(); i++){
			this.configs.add(GlobalConfig.parseJSON(configs.getJSONObject(i).toJSONString()));
		}
	}

	public void runTasks(Class<? extends LoopingBase> jobClass) throws Exception{

		System.out.println("(" + configs.size() + ")tasks : " + Lists.transform(configs, new Function<GlobalConfig, String>() {
			public String apply(GlobalConfig input) {
				return input.getWorkerName();
			}
		}));
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
		List<Future<?>> futures = Lists.newArrayList();
		Constructor<? extends LoopingBase> constructor = jobClass.getConstructor(GlobalConfig.class);
		for(int i = 0 ; i < configs.size() ; i++){
			Runnable r =  constructor.newInstance(configs.get(i));
			futures.add(ConcurrentExecutor.submit(r));
		}
		for( int i = 0; i < futures.size() ; i++){
			futures.get(i).get();
		}
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<");
	}

}


text:
package com.coderwjq.shop.module.player.video_list;

import com.coderwjq.shop.base.ILoadingView;

import java.util.List;

/**
 * Created by coderwjq on 2017/9/1 18:17.
 */

public class VideoListContract {
    public interface IVideoListView extends ILoadingView {
        void addVideoList(List<VideoListBean.DataBean> data);

        void addVideoMovieInfo(VideoMovieInfoBean.DataBean videoMovieInfoBeanData);

        void addTotalCount(int total);

        void addVideoMoreList(List<VideoListBean.DataBean> videoMoreData);

        void showLoadMoreError(String message);
    }

    public interface IVideoListPresenter {
        void getMovieList(int movieId, int offset);

        void getVideoMovieInfo(int movieId);

        void getMoreVideoList(int movieId, int offset);
    }
}


text:
namespace password_manager {

extern const base::FilePath::CharType kAffiliationDatabaseFileName[];
extern const base::FilePath::CharType kLoginDataForProfileFileName[];
extern const base::FilePath::CharType kLoginDataForAccountFileName[];

// URL to the password manager account dashboard.
extern const char kPasswordManagerAccountDashboardURL[];

// URL to the help center article about Smart Lock;
// TODO(crbug.com/862269): remove when "Smart Lock" is completely gone.
extern const char kPasswordManagerHelpCenterSmartLock[];

}  // namespace password_manager

#endif  // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_MANAGER_CONSTANTS_H_


text:
#ifndef AAPT_JAVA_MANIFESTCLASSGENERATOR_H
#define AAPT_JAVA_MANIFESTCLASSGENERATOR_H

#include "Diagnostics.h"
#include "java/ClassDefinition.h"
#include "util/StringPiece.h"
#include "xml/XmlDom.h"

#include <iostream>

namespace aapt {

std::unique_ptr<ClassDefinition> generateManifestClass(IDiagnostics* diag, xml::XmlResource* res);

} // namespace aapt

#endif /* AAPT_JAVA_MANIFESTCLASSGENERATOR_H */


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { EditUserPage } from './edit-user';

@NgModule({
  declarations: [
    EditUserPage,
  ],
  imports: [
    IonicPageModule.forChild(EditUserPage),
  ],
  exports: [
    EditUserPage
  ]
})
export class EditUserPageModule {}


text:
title: Balance
youtube_id: W7DQzHVreRI
date: 2015-03-14
tags: [Stress, Update]
---
> "The major work of the world is not done by geniuses. It is done by ordinary people, with balance in their lives, who have learned to work in an extraordinary manner."

~Gordon B. Hinckley

> "Be moderate in order to taste the joys of life in abundance."

~Epicurus

> "Even nectar is poison if taken to excess."

~Hindu Proverb

> "My God, give me neither poverty nor riches; but whatsoever it may be Thy will to give, give me with it a heart which knows humbly to acquiesce in what is Thy will."

~Gotthold


text:
from celery import Celery
from celery.schedules import crontab

import settings
from command import Command

celery = Celery("task_capture",
    backend=settings.REDIS_BACKEND, broker=settings.REDIS_BROKER, include=["task_capture"])

def range_host(com, flag_type):
    for key, value in settings.ORACLE_ACCOUNT.items():
        host = key.split(":")[0]
        port = key.split(":")[1]
        sid = value[0]
        username = value[1]
        password = value[2]
        date = com.get_last_date()
        com.run_capture(host,
            port, sid, username, password, date, flag_type)

celery.conf.update(
    CELERY_ROUTES = {
        "task_capture.capture_obj": {"queue": "sqlreview_obj"},
        "task_capture.capture_other": {"queue": "sqlreview_other"}
        # "sql.c_sql_stru.capture_sql": {"queue": "sqlreview_sql"}
    },
    CELERY_TIMEZONE = 'Asia/Shanghai',
    CELERYBEAT_SCHEDULE = {
        "sql_capture_obj": {
            "task": "task_capture.capture_obj",
            # 每个月的2号,16号的22点执行任务
            # "schedule": crontab(minute=0, hour='22', day_of_month='2,16'),
            # 每天的晚上11点开始执行任务
            "schedule": crontab(minute=settings.CAPTURE_OBJ_MINUTE, hour=settings.CAPTURE_OBJ_HOUR),
            # 每隔10秒钟执行任务
            # "schedule": timedelta(seconds=10),
            "options": {"queue": "sqlreview_obj"}
        },
        "sql_capture_other": {
             "task": "task_capture.capture_other",
            # 每个月的2号,16号的22点执行任务
            # "schedule": crontab(minute=0, hour='22', day_of_month='2,16'),
            # 每天的晚上17点开始执行任务
            "schedule": crontab(minute=settings.CAPTURE_OTHER_MINUTE, hour=settings.CAPTURE_OTHER_HOUR),
            # 每隔10秒钟执行任务
            # "schedule": timedelta(seconds=10),
            "options": {"queue": "sqlreview_other"}
        }
    }
)

@celery.task
def capture_obj():
    com = Command()
    range_host(com, "OBJ")

@celery.task
def capture_other():
    com = Command()
    range_host(com, "OTHER")


text:
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;

/**
 * Created by william on 11/27/2015.
 */
public class TestResolver {

    @Test
    public void testResolve() {

        int size = 6;
        int nums[] = new int[]{-4, 3, -9, 0, 4, 1};

        double[] outputs = Solution.Resolver.resolve(size, nums);

        Assert.assertThat(outputs[0], Matchers.closeTo(0.500000, 10e-4));
        Assert.assertThat(outputs[1], Matchers.closeTo(0.333333, 10e-4));
        Assert.assertThat(outputs[2], Matchers.closeTo(0.166667, 10e-4));
    }
}


text:
'use strict'
const shri = require('npm-shri-stub');

const subtract = shri.subtract(2, 1);
console.log(subtract);


text:
using UnityEngine;
using UnityEngine.Playables;

namespace Cinemachine.Timeline
{
    public sealed class CinemachineMixer : PlayableBehaviour
    {
        // The brain that this track controls
        private CinemachineBrain mBrain;
        private int mBrainOverrideId = -1;

        public override void OnGraphStop(Playable playable)
        {
            if (mBrain != null)
                mBrain.ReleaseCameraOverride(mBrainOverrideId); // clean up
            mBrainOverrideId = -1;
        }

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            base.ProcessFrame(playable, info, playerData);

            // Get the brain that this track controls.
            // Older versions of timeline sent the gameObject by mistake.
            GameObject go = playerData as GameObject;
            if (go == null)
                mBrain = (CinemachineBrain)playerData;
            else
                mBrain = go.GetComponent<CinemachineBrain>();
            if (mBrain == null)
                return;

            // Find which clips are active.  We can process a maximum of 2.
            // In the case that the weights don't add up to 1, the outgoing weight
            // will be calculated as the inverse of the incoming weight.
            int activeInputs = 0;
            ICinemachineCamera camA = null;
            ICinemachineCamera camB = null;
            float camWeight = 1f;
            for (int i = 0; i < playable.GetInputCount(); ++i)
            {
                CinemachineShotPlayable cam
                    = ((ScriptPlayable<CinemachineShotPlayable>)playable.GetInput(i)).GetBehaviour();
                float weight = playable.GetInputWeight(i);
                if (cam != null && cam.VirtualCamera != null
                    && playable.GetPlayState() == PlayState.Playing
                    && weight > 0.0001f)
                {
                    if (activeInputs == 1)
                        camB = camA;
                    camWeight = weight;
                    camA = cam.VirtualCamera;
                    ++activeInputs;
                    if (activeInputs == 2)
                        break;
                }
            }

            // Override the Cinemachine brain with our results.
            // This is a simulation, so we need a fixed delta time.
            float deltaTime = Time.fixedDeltaTime;
            if (info.evaluationType != FrameData.EvaluationType.Playback)
                deltaTime = 0;
            mBrainOverrideId = mBrain.SetCameraOverride(
                    mBrainOverrideId, camB, camA, camWeight, deltaTime);
        }
    }
}


text:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/iam/admin/v1/iam.proto

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_MOCKS_MOCK_IAM_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_MOCKS_MOCK_IAM_CONNECTION_H

#include "google/cloud/iam/iam_connection.h"
#include <gmock/gmock.h>

namespace google {
namespace cloud {
namespace iam_mocks {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/**
 * A class to mock `IAMConnection`.
 *
 * Application developers may want to test their code with simulated responses,
 * including errors, from an object of type `IAMClient`. To do so,
 * construct an object of type `IAMClient` with an instance of this
 * class. Then use the Google Test framework functions to program the behavior
 * of this mock.
 *
 * @see [This example][bq-mock] for how to test your application with
 * GoogleTest. While the example showcases types from the BigQuery library, the
 * underlying principles apply for any pair of `*Client` and `*Connection`.
 *
 * [bq-mock]: @googleapis_dev_link{bigquery,bigquery-read-mock.html}
 */
class MockIAMConnection : public iam::IAMConnection {
 public:
  MOCK_METHOD(Options, options, (), (override));

  MOCK_METHOD(StreamRange<google::iam::admin::v1::ServiceAccount>,
              ListServiceAccounts,
              (google::iam::admin::v1::ListServiceAccountsRequest request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::ServiceAccount>,
              GetServiceAccount,
              (google::iam::admin::v1::GetServiceAccountRequest const& request),
              (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ServiceAccount>, CreateServiceAccount,
      (google::iam::admin::v1::CreateServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ServiceAccount>, PatchServiceAccount,
      (google::iam::admin::v1::PatchServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DeleteServiceAccount,
      (google::iam::admin::v1::DeleteServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::UndeleteServiceAccountResponse>,
      UndeleteServiceAccount,
      (google::iam::admin::v1::UndeleteServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      Status, EnableServiceAccount,
      (google::iam::admin::v1::EnableServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DisableServiceAccount,
      (google::iam::admin::v1::DisableServiceAccountRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ListServiceAccountKeysResponse>,
      ListServiceAccountKeys,
      (google::iam::admin::v1::ListServiceAccountKeysRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ServiceAccountKey>, GetServiceAccountKey,
      (google::iam::admin::v1::GetServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ServiceAccountKey>,
      CreateServiceAccountKey,
      (google::iam::admin::v1::CreateServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::ServiceAccountKey>,
      UploadServiceAccountKey,
      (google::iam::admin::v1::UploadServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DeleteServiceAccountKey,
      (google::iam::admin::v1::DeleteServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(
      Status, DisableServiceAccountKey,
      (google::iam::admin::v1::DisableServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(
      Status, EnableServiceAccountKey,
      (google::iam::admin::v1::EnableServiceAccountKeyRequest const& request),
      (override));

  MOCK_METHOD(StatusOr<google::iam::v1::Policy>, GetIamPolicy,
              (google::iam::v1::GetIamPolicyRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::v1::Policy>, SetIamPolicy,
              (google::iam::v1::SetIamPolicyRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::v1::TestIamPermissionsResponse>,
              TestIamPermissions,
              (google::iam::v1::TestIamPermissionsRequest const& request),
              (override));

  MOCK_METHOD(StreamRange<google::iam::admin::v1::Role>, QueryGrantableRoles,
              (google::iam::admin::v1::QueryGrantableRolesRequest request),
              (override));

  MOCK_METHOD(StreamRange<google::iam::admin::v1::Role>, ListRoles,
              (google::iam::admin::v1::ListRolesRequest request), (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::Role>, GetRole,
              (google::iam::admin::v1::GetRoleRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::Role>, CreateRole,
              (google::iam::admin::v1::CreateRoleRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::Role>, UpdateRole,
              (google::iam::admin::v1::UpdateRoleRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::Role>, DeleteRole,
              (google::iam::admin::v1::DeleteRoleRequest const& request),
              (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::Role>, UndeleteRole,
              (google::iam::admin::v1::UndeleteRoleRequest const& request),
              (override));

  MOCK_METHOD(StreamRange<google::iam::admin::v1::Permission>,
              QueryTestablePermissions,
              (google::iam::admin::v1::QueryTestablePermissionsRequest request),
              (override));

  MOCK_METHOD(
      StatusOr<google::iam::admin::v1::QueryAuditableServicesResponse>,
      QueryAuditableServices,
      (google::iam::admin::v1::QueryAuditableServicesRequest const& request),
      (override));

  MOCK_METHOD(StatusOr<google::iam::admin::v1::LintPolicyResponse>, LintPolicy,
              (google::iam::admin::v1::LintPolicyRequest const& request),
              (override));
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace iam_mocks
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_MOCKS_MOCK_IAM_CONNECTION_H


text:
// coding: utf-8
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------

#ifndef XPCC_ALLOCATOR__DYNAMIC_HPP
#define XPCC_ALLOCATOR__DYNAMIC_HPP

#include "allocator_base.hpp"

namespace xpcc
{
	namespace allocator
	{
		/**
		 * \brief	Dynamic memory allocator
		 *
		 * Wrapper for the underlying memory management. No additional
		 * management is done.
		 *
		 * \ingroup	allocator
		 * \author	Fabian Greif
		 */
		template <typename T>
		class Dynamic : public AllocatorBase<T>
		{
		public:
			template <typename U>
			struct rebind
			{
				typedef Dynamic<U> other;
			};

		public:
			Dynamic() :
				AllocatorBase<T>()
			{
			}

			Dynamic(const Dynamic& other) :
				AllocatorBase<T>(other)
			{
			}

			template <typename U>
			Dynamic(const Dynamic<U>&) :
				AllocatorBase<T>()
			{
			}

			T*
			allocate(size_t n)
			{
				// allocate the memory without calling the constructor
				// of the associated data-type.
				return static_cast<T*>(::operator new(n * sizeof(T)));
			}

			void
			deallocate(T* p)
			{
				// it is important to use this form here, otherwise the
				// destructor of p will be called which is unwanted here.
				// The destructor can be called with the destroy()-method.
				::operator delete(p);
			}
		};
	}
}

#endif // XPCC_ALLOCATOR__DYNAMIC_HPP


text:
import click
from .ffmpeg import FFmpeg

def parse_bandwidth(bandwidth):
    """Converts the bandwidth string (e.g. 5M) to a float representing megabits."""
    if bandwidth[-1].lower() == "m":
        return int(bandwidth[:-1])
    elif bandwidth[-1].lower() == "k":
        return int(bandwidth[:-1]) / 1024

def parse_filesize(filesize):
    """Turn the filesize input string (e.g. 5M) into an integer representing bytes."""
    if filesize.lower() == "4ch":
        return 3134464
    elif filesize[-1].lower() == "g":
        exponent = 3
    elif filesize[-1].lower() == "m":
        exponent = 2
    elif filesize[-1].lower() == "k":
        exponent = 1
    elif filesize[-1].lower() == "b":
        exponent = 0
    else:
        click.echo("Invalid filesize.")
        exit(1)
    return int(filesize[:-1]) * pow(1024, exponent)

@click.command()
@click.option("--bandwidth", "-b", help="Manually set the used bandwidth, e.g. 5M.")
@click.option("--crop/--no-crop", default=False, help="Crop the output video frame.")
@click.option("--crop-width", type=int, help="Width of the cropped area in pixels.")
@click.option("--crop-height", type=int, help="Height of the cropped area in pixels.")
@click.option("--crop-x", type=int, help="Staring X coordinate for the crop.")
@click.option("--crop-y", type=int, help="Staring Y coordinate for the crop.")
@click.option("--duration", help="Duration for the output video, e.g. 30.000")
@click.option("--end", "-e", help="End time for the encode, e.g. 01:12:34.555.")
@click.option("--h264", is_flag=True, help="Use h.264 encoding instead of VP8.")
@click.option("--iterations", type=int, help="Maximum iterations for target filesize.")
@click.option("--output", "-o", help="Output filename")
@click.option(
    "--resolution", nargs=2, type=int, help="Output video width and height in pixels."
)
@click.option("--sound/--no-sound", default=False, help="Output video with sound.")
@click.option("--start", "-s", help="Start time for the encode, e.g. 01:09.100.")
@click.option("--subs/--no-subs", default=False, help="Output video with subtitles.")
@click.option("--target-size", "-t", help="Target filesize for the encode.")
@click.option("--title", help="Add a title to file metadata.")
@click.option("--verbose", is_flag=True, help="Turn on ffmpeg output.")
@click.argument(
    "file", required=True, nargs=1, type=click.Path(exists=True, resolve_path=True)
)
def cli(
    bandwidth,
    crop,
    crop_width,
    crop_height,
    crop_x,
    crop_y,
    duration,
    end,
    h264,
    iterations,
    output,
    resolution,
    sound,
    start,
    subs,
    target_size,
    title,
    verbose,
    file,
):
    """Command-line wrapper for ffmpeg designed to ease converting video files
    to WebM files.
    """
    conversion = FFmpeg(file)
    conversion.start = start
    conversion.end = end
    conversion.h264 = h264
    conversion.iterations = iterations
    conversion.output = output

    if crop:
        from .cropper import VideoCropper

        cropper = VideoCropper(conversion)
        cropper.mainloop()
    if all(x is not None for x in (crop_width, crop_height, crop_x, crop_y)):
        conversion.coordinates = (
            crop_x,
            crop_y,
            crop_x + crop_width,
            crop_y + crop_height,
        )
    if duration:
        conversion.duration = duration
    if bandwidth:
        conversion.bandwidth = parse_bandwidth(bandwidth)
    if target_size:
        conversion.target_filesize = parse_filesize(target_size)

    conversion.quiet = not verbose
    conversion.resolution = resolution
    conversion.sound = sound
    conversion.subtitles = subs
    conversion.title = title
    conversion.encode()

if __name__ == "__main__":
    cli()


text:
package openid

import (
	"bytes"
	"log"
	"os"
	"testing"
)

// searchHTMLMetaXRDS Test

type searchHTMLMetaXRDSTest struct {
	in  []byte
	out string
}

var searchHTMLMetaXRDSTests = []searchHTMLMetaXRDSTest{
	searchHTMLMetaXRDSTest{[]byte("<meta http-equiv='X-XRDS-Location' content='location'></meta>"), "location"},
	searchHTMLMetaXRDSTest{[]byte("<meta http-equiv='X-XRDS-Location' content='location'>"), "location"},
	searchHTMLMetaXRDSTest{[]byte("<meta http-equiv=\"x-xrds-location\" content=\"location\">"), "location"},
	//searchHTMLMetaXRDSTest{[]byte("<meta>location</meta>"), "location"},
}

func TestSearchHTMLMetaXRDS(t *testing.T) {
	for _, l := range searchHTMLMetaXRDSTests {
		content, err := searchHTMLMetaXRDS(bytes.NewBuffer(l.in))
		if err != nil {
			t.Errorf("searchHTMLMetaXRDS error: %s", err.Error())
		}
		if !bytes.Equal([]byte(content), []byte(l.out)) {
			t.Errorf("searchHTMLMetaXRDS(%s) = %s want %s.", l.in, content, l.out)
		}
	}
}

// Yadis Test

type YadisTest struct {
	url string
}

var YadisTests = []YadisTest{
	YadisTest{"https://www.google.com/accounts/o8/id"},
	//YadisTest{"http://orange.fr/"},
	//YadisTest{"http://www.yahoo.com/"},
}

// Test whether the Yadis function returns no errors and a non nil reader
// Doesn't test the content received
func TestYadis(t *testing.T) {
	logger := log.New(os.Stdout, "TestYadis ", log.Ltime|log.Lmicroseconds|log.Lshortfile)
	for _, yt := range YadisTests {
		q := Query{Logger: logger}
		reader, err := q.yadisGet(yt.url)
		if err != nil {
			t.Errorf("Yadis(%s) returned a error: %s", yt.url, err.Error())
			continue
		}
		if reader == nil {
			t.Errorf("Yadis(%s) returned a nil reader", yt.url)
		}
	}
}