text:
<?php

class Ess_M2ePro_Block_Adminhtml_Ebay_Listing_View_Settings_Grid
    extends Ess_M2ePro_Block_Adminhtml_Ebay_Listing_Settings_Grid_Abstract
{
    /** @var Mage_Eav_Model_Entity_Attribute_Abstract */
    protected $_motorsAttribute = null;

    protected $_productsMotorsData = array();

    //########################################

    public function __construct()
    {
        parent::__construct();

        // Initialization block
        // ---------------------------------------
        $this->setId('ebayListingViewSettingsGrid'.$this->getListing()->getId());
        // ---------------------------------------

        if ($this->isMotorsAvailable()) {
            $attributeCode = Mage::helper('M2ePro/Component_Ebay_Motors')
                ->getAttribute($this->getMotorsType());

            $this->_motorsAttribute = Mage::getModel('catalog/product')->getResource()
                                          ->getAttribute($attributeCode);
        }
    }

    //########################################

    public function getMotorsType()
    {
        if (!$this->isMotorsAvailable()) {
            return null;
        }

        if ($this->isMotorEpidsAvailable()) {
            return Mage::helper('M2ePro/Component_Ebay_Motors')->getEpidsTypeByMarketplace(
                $this->getListing()->getMarketplaceId()
            );
        }

        return Ess_M2ePro_Helper_Component_Ebay_Motors::TYPE_KTYPE;
    }

    //########################################

    public function getMainButtonsHtml()
    {
        $data = array(
            'current_view_mode' => $this->getParentBlock()->getViewMode()
        );
        $viewModeSwitcherBlock = $this->getLayout()->createBlock('M2ePro/adminhtml_ebay_listing_view_modeSwitcher');
        $viewModeSwitcherBlock->addData($data);

        return $viewModeSwitcherBlock->toHtml() . parent::getMainButtonsHtml();
    }

    //########################################

    public function getAdvancedFilterButtonHtml()
    {
        if (!Mage::helper('M2ePro/View_Ebay')->isAdvancedMode()) {
            return '';
        }

        return parent::getAdvancedFilterButtonHtml();
    }

    //########################################

    protected function isShowRuleBlock()
    {
        if (Mage::helper('M2ePro/View_Ebay')->isSimpleMode()) {
            return false;
        }

        return parent::isShowRuleBlock();
    }

    //########################################

    protected function getGridHandlerJs()
    {
        return 'EbayListingSettingsGridHandler';
    }

    //########################################

    protected function _prepareCollection()
    {
        // ---------------------------------------
        // Get collection
        // ---------------------------------------
        /** @var $collection Ess_M2ePro_Model_Resource_Magento_Product_Collection */
        $collection = Mage::getConfig()->getModelInstance(
            'Ess_M2ePro_Model_Resource_Magento_Product_Collection',
            Mage::getModel('catalog/product')->getResource()
        );

        $collection->setListingProductModeOn();
        $collection->setListing($this->getListing());
        $collection->setStoreId($this->getListing()->getStoreId());

        if ($this->isFilterOrSortByPriceIsUsed(null, 'ebay_online_current_price')) {
            $collection->setIsNeedToUseIndexerParent(true);
        }

        $collection->addAttributeToSelect('sku');
        $collection->addAttributeToSelect('name');

        // Join listing product tables
        // ---------------------------------------
        $collection->joinTable(
            array('lp' => 'M2ePro/Listing_Product'),
            'product_id=entity_id',
            array(
                'id' => 'id',
                'ebay_status' => 'status',
                'additional_data' => 'additional_data'
            ),
            '{{table}}.listing_id='.(int)$this->getListing()->getId()
        );
        $collection->joinTable(
            array('elp' => 'M2ePro/Ebay_Listing_Product'),
            'listing_product_id=id',
            array(
                'listing_product_id' => 'listing_product_id',

                'template_category_id'  => 'template_category_id',
                'template_other_category_id'  => 'template_other_category_id',

                'template_payment_mode'  => 'template_payment_mode',
                'template_shipping_mode' => 'template_shipping_mode',
                'template_return_mode'   => 'template_return_mode',

                'template_description_mode'     => 'template_description_mode',
                'template_selling_format_mode'  => 'template_selling_format_mode',
                'template_synchronization_mode' => 'template_synchronization_mode',

                'end_date'              => 'end_date',
                'start_date'            => 'start_date',
                'online_title'          => 'online_title',
                'online_sku'            => 'online_sku',
                'available_qty'         => new Zend_Db_Expr('(online_qty - online_qty_sold)'),
                'ebay_item_id'          => 'ebay_item_id',
                'online_main_category'  => 'online_main_category',
                'online_qty_sold'       => 'online_qty_sold',
                'online_start_price'    => 'online_start_price',
                'online_current_price'  => 'online_current_price',
                'online_reserve_price'  => 'online_reserve_price',
                'online_buyitnow_price' => 'online_buyitnow_price',
            )
        );
        $collection->joinTable(
            array('ei' => 'M2ePro/Ebay_Item'),
            'id=ebay_item_id',
            array(
                'item_id' => 'item_id',
            ),
            NULL,
            'left'
        );
        $collection->joinTable(
            array('etc' => 'M2ePro/Ebay_Template_Category'),
            'id=template_category_id',
            array(
                'category_main_mode'      => 'category_main_mode',
                'category_main_id'        => 'category_main_id',
                'category_main_path'      => 'category_main_path',
                'category_main_attribute' => 'category_main_attribute',
            ),
            NULL,
            'left'
        );
        $collection->joinTable(
            array('etoc' => 'M2ePro/Ebay_Template_OtherCategory'),
            'id=template_other_category_id',
            array(
                'category_secondary_mode'      => 'category_secondary_mode',
                'category_secondary_id'        => 'category_secondary_id',
                'category_secondary_path'      => 'category_secondary_path',
                'category_secondary_attribute' => 'category_secondary_attribute',

                'store_category_main_mode'      => 'store_category_main_mode',
                'store_category_main_id'        => 'store_category_main_id',
                'store_category_main_path'      => 'store_category_main_path',
                'store_category_main_attribute' => 'store_category_main_attribute',

                'store_category_secondary_mode'      => 'store_category_secondary_mode',
                'store_category_secondary_id'        => 'store_category_secondary_id',
                'store_category_secondary_path'      => 'store_category_secondary_path',
                'store_category_secondary_attribute' => 'store_category_secondary_attribute',
            ),
            NULL,
            'left'
        );

        if ($this->_motorsAttribute) {
            $collection->joinTable(
                array(
                    'eea' => Mage::helper('M2ePro/Module_Database_Structure')
                        ->getTableNameWithPrefix('eav_entity_attribute')
                ),
                'attribute_set_id=attribute_set_id',
                array(
                    'is_motors_attribute_in_product_attribute_set' => 'entity_attribute_id',
                ),
                '{{table}}.attribute_id = ' . $this->_motorsAttribute->getAttributeId(),
                'left'
            );
        }

        if ($collection->isNeedUseIndexerParent()) {
            $collection->joinIndexerParent();
        }

        $this->setCollection($collection);
        $result = parent::_prepareCollection();

        if ($this->isMotorsAvailable() && $this->_motorsAttribute) {
            $this->prepareExistingMotorsData();
        }

        return $result;
    }

    protected function _prepareColumns()
    {
        $this->addColumns();

        $this->addColumnAfter(
            'name', array(
            'header'    => Mage::helper('M2ePro')->__('Product Title / Product SKU / eBay Category'),
            'align'     => 'left',
            'type'      => 'text',
            'index'     => 'name',
            'filter'    => 'M2ePro/adminhtml_ebay_listing_view_settings_grid_column_filter_titleSkuCategory',
            'frame_callback' => array($this, 'callbackColumnTitle'),
            'filter_condition_callback' => array($this, 'callbackFilterTitle')
            ), 'product_id'
        );

        if ($this->isMotorsAvailable() && $this->_motorsAttribute) {
            $this->addColumnAfter(
                'parts_motors_attribute_value', array(
                'header'    => Mage::helper('M2ePro')->__('Compatibility'),
                'align'     => 'left',
                'width'     => '100px',
                'type'      => 'options',
                'index'     => $this->_motorsAttribute->getAttributeCode(),
                'sortable'  => false,
                'options'   => array(
                    1 => Mage::helper('M2ePro')->__('Filled'),
                    0 => Mage::helper('M2ePro')->__('Empty')
                ),
                'frame_callback' => array($this, 'callbackColumnMotorsAttribute'),
                'filter_condition_callback' => array($this, 'callbackFilterMotorsAttribute'),
                ), 'name'
            );
        }

        return parent::_prepareColumns();
    }

    //########################################

    protected function _prepareMassactionGroup()
    {
        $this->getMassactionBlock()->setGroups(
            array(
            'edit_settings'            => Mage::helper('M2ePro')->__('Edit General Settings'),
            'edit_categories_settings' => Mage::helper('M2ePro')->__('Edit Categories Settings'),
            'other'                    => Mage::helper('M2ePro')->__('Other')
            )
        );

        return $this;
    }

    protected function _prepareMassactionItems()
    {
        $this->getMassactionBlock()->addItem(
            'editCategorySettings', array(
            'label'    => Mage::helper('M2ePro')->__('All Categories'),
            'url'      => '',
            ), 'edit_categories_settings'
        );

        $this->getMassactionBlock()->addItem(
            'editPrimaryCategorySettings', array(
                'label'    => Mage::helper('M2ePro')->__('Primary Categories'),
                'url'      => '',
            ), 'edit_categories_settings'
        );

        if ($this->getListing()->getAccount()->getChildObject()->getEbayStoreCategories()) {
            $this->getMassactionBlock()->addItem(
                'editStorePrimaryCategorySettings', array(
                'label'    => Mage::helper('M2ePro')->__('Store Primary Categories'),
                'url'      => '',
                ), 'edit_categories_settings'
            );
        }

        parent::_prepareMassactionItems();

        if ($this->isMotorsAvailable() && $this->_motorsAttribute) {
            $this->getMassactionBlock()->addItem(
                'editMotors', array(
                'label' => Mage::helper('M2ePro')->__('Add Compatible Vehicles'),
                'url'   => ''
                ), 'other'
            );
        }

        $this->getMassactionBlock()->addItem(
            'moving', array(
            'label'    => Mage::helper('M2ePro')->__('Move Item(s) to Another Listing'),
            'url'      => '',
            'confirm'  => Mage::helper('M2ePro')->__('Are you sure?')
            ), 'other'
        );

        if (Mage::helper('M2ePro/View_Ebay')->isAdvancedMode()) {
            $this->getMassactionBlock()->addItem(
                'transferring', array(
                'label'    => Mage::helper('M2ePro')->__('Sell on Another eBay Site'),
                'url'      => '',
                ), 'other'
            );
        }

        return $this;
    }

    //########################################

    public function callbackColumnTitle($value, $row, $column, $isExport)
    {
        $helper = Mage::helper('M2ePro');

        $value = parent::callbackColumnTitle($value, $row, $column, $isExport);

        /** @var Ess_M2ePro_Model_Listing_Product $listingProduct */
        $listingProduct = Mage::helper('M2ePro/Component_Ebay')
            ->getObject('Listing_Product', $row->getData('listing_product_id'));

        if ($listingProduct->getChildObject()->isVariationsReady()) {
            $additionalData = (array)Mage::helper('M2ePro')->jsonDecode($row->getData('additional_data'));

            $productAttributes = isset($additionalData['variations_sets'])
                ? array_keys($additionalData['variations_sets']) : array();

            $value .= '
';
            $value .= implode(', ', $productAttributes);
            $value .= '
';
        }

        $value .= '

';

        if ($row->getData('category_main_mode') == Ess_M2ePro_Model_Ebay_Template_Category::CATEGORY_MODE_NONE) {
            $value .= $this->getCategoryInfoHtml(
                $helper->__('eBay Primary Category'),
                ''.$helper->__('Not Set').''
            );
        } else {
            $value .= $this->getEbayCategoryInfoHtml($row, 'category_main', $helper->__('eBay Primary Category'));
        }

        $value .= $this->getEbayCategoryInfoHtml($row, 'category_secondary', $helper->__('eBay Secondary Category'));

        $value .= $this->getStoreCategoryInfoHtml(
            $row, 'category_main',
            $helper->__('eBay Store Primary Category')
        );
        $value .= $this->getStoreCategoryInfoHtml(
            $row, 'category_secondary',
            $helper->__('eBay Store Secondary Category')
        );
        $value .= '
';

        return $value;
    }

    public function callbackColumnMotorsAttribute($value, $row, $column, $isExport)
    {
        if (!$this->_motorsAttribute) {
            return Mage::helper('M2ePro')->__('N/A');
        }

        if (!$row->getData('is_motors_attribute_in_product_attribute_set')) {
            return Mage::helper('M2ePro')->__('N/A');
        }

        $attributeCode = $this->_motorsAttribute->getAttributeCode();
        $attributeValue = $row->getData($attributeCode);

        if (empty($attributeValue)) {
            return Mage::helper('M2ePro')->__('N/A');
        }

        $motorsData = $this->_productsMotorsData[$row->getData('listing_product_id')];

        $countOfItems = count($motorsData['items']);
        $countOfFilters = count($motorsData['filters']);
        $countOfGroups = count($motorsData['groups']);

        $showAll = false;

        if ($countOfItems + $countOfFilters + $countOfGroups === 0) {
            $showAll = true;
        }

        if (Mage::helper('M2ePro/Component_Ebay_Motors')->isTypeBasedOnEpids($this->getMotorsType())){
            $motorsTypeTitle = 'ePIDs';
        } else {
            $motorsTypeTitle = 'kTypes';
        }

        $html = '
';
        $label = Mage::helper('M2ePro')->__('Show');
        $labelFilters = Mage::helper('M2ePro')->__('Filters');
        $labelGroups = Mage::helper('M2ePro')->__('Groups');

        if ($showAll || $countOfItems > 0) {
            $html .= <<<HTML
{$motorsTypeTitle}:
{$countOfItems}

HTML;

            if ($countOfItems) {
                $html .= <<<HTML
[getData('id')},
        EbayListingSettingsGridHandlerObj
    );">{$label}]

HTML;
            }
        }

        if ($showAll || $countOfFilters > 0) {
            $html .= <<<HTML
{$labelFilters}:
{$countOfFilters}

HTML;

            if ($countOfFilters) {
                $html .= <<<HTML
[getData('id')},
        EbayListingSettingsGridHandlerObj
    );">{$label}]

HTML;
            }
        }

        if ($showAll || $countOfGroups > 0) {
            $html .= <<<HTML
{$labelGroups}:
{$countOfGroups}

HTML;

            if ($countOfGroups) {
                $html .= <<<HTML
[getData('id')},
        EbayListingSettingsGridHandlerObj
    );">{$label}]
HTML;
            }
        }

        $html .= '
';

        return $html;
    }

    //########################################

    public function callbackFilterTitle($collection, $column)
    {
        $inputValue = $column->getFilter()->getValue('input');
        if ($inputValue !== null) {
            $fieldsToFilter = array(
                array('attribute'=>'sku','like'=>'%'.$inputValue.'%'),
                array('attribute'=>'name','like'=>'%'.$inputValue.'%'),
                array('attribute'=>'category_main_path','like'=>'%'.$inputValue.'%'),
                array('attribute'=>'category_secondary_path','like'=>'%'.$inputValue.'%'),
                array('attribute'=>'store_category_main_path','like'=>'%'.$inputValue.'%'),
                array('attribute'=>'store_category_secondary_path','like'=>'%'.$inputValue.'%'),
            );

            if (is_numeric($inputValue)) {
                $fieldsToFilter[] = array('attribute'=>'category_main_id','eq'=>$inputValue);
                $fieldsToFilter[] = array('attribute'=>'category_secondary_id','eq'=>$inputValue);
                $fieldsToFilter[] = array('attribute'=>'store_category_main_id','eq'=>$inputValue);
                $fieldsToFilter[] = array('attribute'=>'store_category_secondary_id','eq'=>$inputValue);
            }

            $collection->addFieldToFilter($fieldsToFilter);
        }

        $selectValue = $column->getFilter()->getValue('select');
        if ($selectValue !== null) {
            $collection->addFieldToFilter('template_category_id', array(($selectValue ? 'notnull' : 'null') => true));
        }
    }

    public function callbackFilterMotorsAttribute(Varien_Data_Collection_Db $collection, $column)
    {
        $value = $column->getFilter()->getValue();

        if ($value === null) {
            return;
        }

        if (!$this->_motorsAttribute) {
            return;
        }

        if ($value == 1) {
            $attributeCode = $this->_motorsAttribute->getAttributeCode();
            $collection->joinAttribute(
                $attributeCode, 'catalog_product/'.$attributeCode, 'entity_id', NULL, 'left',
                $this->getListing()->getStoreId()
            );

            $collection->addFieldToFilter($attributeCode, array('notnull'=>true));
            $collection->addFieldToFilter($attributeCode, array('neq'=>''));
            $collection->addFieldToFilter(
                'is_motors_attribute_in_product_attribute_set', array('notnull'=>true)
            );
        } else {
            $attributeId = $this->_motorsAttribute->getId();
            $storeId = $this->getListing()->getStoreId();

            $joinCondition = 'eaa.entity_id = e.entity_id and eaa.attribute_id = '.$attributeId;
            if (!$this->_motorsAttribute->isScopeGlobal()) {
                $joinCondition .= ' and eaa.store_id = '.$storeId;
            }

            $collection->getSelect()->joinLeft(
                array(
                    'eaa' => Mage::helper('M2ePro/Module_Database_Structure')
                        ->getTableNameWithPrefix('catalog_product_entity_text')
                ),
                $joinCondition,
                array('value')
            );

            $collection->getSelect()->where('eaa.value IS NULL');
            $collection->getSelect()->orWhere('eaa.value = \'\'');
            $collection->getSelect()->orWhere('eea.entity_attribute_id IS NULL');
        }
    }

    //########################################

    public function getGridUrl()
    {
        return $this->getUrl('*/adminhtml_ebay_listing/viewGrid', array('_current'=>true));
    }

    public function getRowUrl($row)
    {
        return false;
    }

    //########################################

    protected function getEbayCategoryInfoHtml($row, $modeNick, $modeTitle)
    {
        $helper = Mage::helper('M2ePro');
        $mode = $row->getData($modeNick.'_mode');

        if ($mode === null || $mode == Ess_M2ePro_Model_Ebay_Template_Category::CATEGORY_MODE_NONE) {
            return '';
        }

        if ($mode == Ess_M2ePro_Model_Ebay_Template_Category::CATEGORY_MODE_ATTRIBUTE) {
            $category = $helper->__('Magento Attribute'). ' > ';
            $category.= $helper->escapeHtml(
                Mage::helper('M2ePro/Magento_Attribute')->getAttributeLabel(
                    $row->getData($modeNick.'_attribute'),
                    $this->getListing()->getStoreId()
                )
            );
        } else {
            $category = $helper->escapeHtml($row->getData($modeNick.'_path')).' ('.$row->getData($modeNick.'_id').')';
        }

        return $this->getCategoryInfoHtml($modeTitle, $category);
    }

    protected function getStoreCategoryInfoHtml($row, $modeNick, $modeTitle)
    {
        $helper = Mage::helper('M2ePro');
        $mode = $row->getData('store_'.$modeNick.'_mode');

        if ($mode == Ess_M2ePro_Model_Ebay_Template_Category::CATEGORY_MODE_NONE) {
            return '';
        }

        if ($mode == Ess_M2ePro_Model_Ebay_Template_Category::CATEGORY_MODE_ATTRIBUTE) {
            $category = $helper->__('Magento Attribute'). ' > ';
            $category .= $helper->escapeHtml(
                Mage::helper('M2ePro/Magento_Attribute')->getAttributeLabel(
                    $row->getData('store_'.$modeNick.'_attribute'),
                    $this->getListing()->getStoreId()
                )
            );
        } else {
            $category = $helper->escapeHtml($row->getData('store_'.$modeNick.'_path')).
                        ' ('.$row->getData('store_'.$modeNick.'_id').')';
        }

        return $this->getCategoryInfoHtml($modeTitle, $category);
    }

    protected function getCategoryInfoHtml($modeTitle, $category)
    {
        return <<<HTML

        {$modeTitle}:

{$category}

HTML;
    }

    //########################################

    protected function getColumnActionsItems()
    {
        $helper = Mage::helper('M2ePro');

        $actions = array(
            'editCategories' => array(
                'caption' => $helper->__('All Categories'),
                'group'   => 'edit_categories_settings',
                'field'   => 'id',
                'onclick_action' => 'EbayListingSettingsGridHandlerObj.actions[\'editCategorySettingsAction\']'
            ),

            'editPrimaryCategories' => array(
                'caption' => $helper->__('Primary Category'),
                'group'   => 'edit_categories_settings',
                'field'   => 'id',
                'onclick_action' => 'EbayListingSettingsGridHandlerObj.actions[\'editPrimaryCategorySettingsAction\']'
            ),
        );

        if ($this->getListing()->getAccount()->getChildObject()->getEbayStoreCategories()) {
            $actions['editStorePrimaryCategories'] =  array(
                'caption' => $helper->__('Store Primary Category'),
                'group'   => 'edit_categories_settings',
                'field'   => 'id',
                'onclick_action' => 'EbayListingSettingsGridHandlerObj.'
                                    .'actions[\'editStorePrimaryCategorySettingsAction\']'
            );
        }

        if ($this->isMotorsAvailable() && $this->_motorsAttribute) {
            $actions['addCompatibleVehicles'] =  array(
                'caption' => $helper->__('Add Compatible Vehicles'),
                'group'   => 'other',
                'field'   => 'id',
                'onclick_action' => 'EbayListingSettingsGridHandlerObj.actions[\'editMotorsAction\']'
            );
        }

        return array_merge(parent::getColumnActionsItems(), $actions);
    }

    //########################################

    protected function _toHtml()
    {
        /** @var $helper Ess_M2ePro_Helper_Data */
        $helper = Mage::helper('M2ePro');

        // ---------------------------------------
        $urls = $helper->getControllerActions('adminhtml_ebay_listing', array('_current' => true));

        $path = 'adminhtml_ebay_listing/getCategoryChooserHtml';
        $urls[$path] = $this->getUrl(
            '*/' . $path, array(
            'listing_id' => $this->getListing()->getId()
            )
        );

        $path = 'adminhtml_ebay_listing/getCategorySpecificHtml';
        $urls[$path] = $this->getUrl(
            '*/' . $path, array(
            'listing_id' => $this->getListing()->getId()
            )
        );

        $path = 'adminhtml_ebay_listing/saveCategoryTemplate';
        $urls[$path] = $this->getUrl(
            '*/' . $path, array(
            'listing_id' => $this->getListing()->getId()
            )
        );

        $path = 'adminhtml_ebay_listing/runTransferring';
        $urls[$path] = $this->getUrl(
            '*/' . $path, array(
            'listing_id' => $this->getListing()->getId()
            )
        );

        $path = 'adminhtml_ebay_log/listing';
        $urls[$path] = $this->getUrl(
            '*/adminhtml_ebay_log/listing', array(
            'id' => $this->getListing()->getId()
            )
        );

        $path = 'adminhtml_ebay_listing/getEstimatedFees';
        $urls[$path] = $this->getUrl(
            '*/' . $path, array(
                'listing_id' => $this->getListing()->getId()
            )
        );

        $urls['adminhtml_ebay_listing/getTransferringUrl'] = $this->getUrl('*/adminhtml_ebay_listing/view');

        $urls = array_merge(
            $urls,
            $helper->getControllerActions('adminhtml_ebay_motor')
        );

        $urls = Mage::helper('M2ePro')->jsonEncode($urls);
        // ---------------------------------------

        if (Mage::helper('M2ePro/Component_Ebay_Motors')->isTypeBasedOnEpids($this->getMotorsType())){
            $motorsTypeTitle = 'ePID';
        } else {
            $motorsTypeTitle = 'kType';
        }

        //------------------------------
        $translations = Mage::helper('M2ePro')->jsonEncode(
            array(
            'eBay Categories' => $helper->__('eBay Categories'),
            'of Product' => Mage::helper('M2ePro')->__('of Product'),
            'Specifics' => $helper->__('Specifics'),
            'Compatibility Attribute ePIDs' => $helper->__('Compatibility Attribute ePIDs'),
            'Payment for Translation Service' => $helper->__('Payment for Translation Service'),
            'Payment for Translation Service. Help' => $helper->__('Payment for Translation Service'),
            'Specify a sum to be credited to an Account.' =>
                $helper->__(
                    'Specify a sum to be credited to an Account.'
                           .' If you are planning to order more Items for Translation in future,'
                           .' you can credit the sum greater than the one needed for current Translation.'
                           .' Click here to find out more.',
                    Mage::helper('M2ePro/Module_Support')->getDocumentationUrl(
                        NULL, NULL,
                        'x/BQAJAQ#SellonanothereBaySite-Account'
                    )
                ),
            'Amount to Pay.' => $helper->__('Amount to Pay'),
            'Insert amount to be credited to an Account' => $helper->__('Insert amount to be credited to an Account.'),
            'Confirm' => $helper->__('Confirm'),
            'Add Compatible Vehicles' => $helper->__('Add Compatible Vehicles'),
            'Save Filter' => $helper->__('Save Filter'),
            'Save as Group' => $helper->__('Save as Group'),
            'Set Note' => $helper->__('Set Note'),
            'View Items' => $helper->__('Selected %items_title%s', $motorsTypeTitle),
            'View Filters' => $helper->__('Selected Filters'),
            'View Groups' => $helper->__('Selected Groups'),
            'Selected Items' => $helper->__('Selected %items_title%s', $motorsTypeTitle),
            'Selected Filters' => $helper->__('Selected Filters'),
            'Selected Groups' => $helper->__('Selected Groups'),
            'Motor Item' => $motorsTypeTitle,
            'Note' => $helper->__('Note'),
            'Filter' => $helper->__('Filter'),
            'Group' => $helper->__('Group'),
            'kType' => $helper->__('kType'),
            'ePID' => $helper->__('ePID'),
            'Type' => $helper->__('Type'),
            'Year From' => $helper->__('Year From'),
            'Year To' => $helper->__('Year To'),
            'Body Style' => $helper->__('Body Style')
            )
        );
        // ---------------------------------------

        // ---------------------------------------
        $constants = $helper->getClassConstantAsJson('Ess_M2ePro_Helper_Component_Ebay_Category');
        // ---------------------------------------

        $component = Ess_M2ePro_Helper_Component_Ebay::NICK;

        $temp = Mage::helper('M2ePro/Data_Session')->getValue('products_ids_for_list', true);
        $productsIdsForList = empty($temp) ? '' : $temp;

        $gridId = $component . 'ListingViewGrid' . $this->getListing()->getId();
        $ignoreListings = Mage::helper('M2ePro')->jsonEncode(array($this->getListing()->getId()));

        $logViewUrl = $this->getUrl(
            '*/adminhtml_ebay_log/listing', array(
                'id' => $this->getListing()->getId(),
                'back' => $helper->makeBackUrlParam(
                    '*/adminhtml_ebay_listing/view', array('id' => $this->getListing()->getId())
                )
            )
        );
        $getErrorsSummary = $this->getUrl('*/adminhtml_listing/getErrorsSummary');

        $taskCompletedMessage = $helper->escapeJs($helper->__('Task completed. Please wait ...'));
        $taskCompletedSuccessMessage = $helper->escapeJs(
            $helper->__('"%task_title%" Task was successfully submitted to be processed.')
        );
        $taskRealtimeCompletedSuccessMessage = $helper->escapeJs(
            $helper->__('"%task_title%" Task was completed successfully.')
        );

        // M2ePro_TRANSLATIONS
        // %task_title%" Task was completed with warnings. View Log for the details.
        $tempString = '"%task_title%" Task was completed with warnings.'
                     .' View Log for the details.';
        $taskCompletedWarningMessage = $helper->escapeJs($helper->__($tempString));

        // M2ePro_TRANSLATIONS
        // "%task_title%" Task was completed with errors. View Log for the details.
        $tempString = '"%task_title%" Task was completed with errors. '
                     .' View Log for the details.';
        $taskCompletedErrorMessage = $helper->escapeJs($helper->__($tempString));

        $sendingDataToEbayMessage = $helper->escapeJs($helper->__('Sending %product_title% Product(s) data on eBay.'));
        $viewAllProductLogMessage = $helper->escapeJs($helper->__('View All Product Log.'));

        $listingLockedMessage = $helper->escapeJs(
            $helper->__('The Listing was locked by another process. Please try again later.')
        );
        $listingEmptyMessage = $helper->escapeJs(
            $helper->__('Listing is empty.')
        );

        $selectItemsMessage = $helper->escapeJs($helper->__('Please select Items.'));
        $selectActionMessage = $helper->escapeJs($helper->__('Please select Action.'));

        $successWord = $helper->escapeJs($helper->__('Success'));
        $noticeWord = $helper->escapeJs($helper->__('Notice'));
        $warningWord = $helper->escapeJs($helper->__('Warning'));
        $errorWord = $helper->escapeJs($helper->__('Error'));
        $closeWord = $helper->escapeJs($helper->__('Close'));

        $prepareData = $this->getUrl('*/adminhtml_listing_moving/prepareMoveToListing');
        $getMoveToListingGridHtml = $this->getUrl('*/adminhtml_listing_moving/moveToListingGrid');
        $moveToListing = $this->getUrl('*/adminhtml_listing_moving/moveToListing');

        $popupTitle = $helper->escapeJs($helper->__('Moving eBay Items'));

        $motorsType = '';
        if ($this->isMotorsAvailable()) {
            $motorsType = $this->getMotorsType();
        }

        $html = <<getRequest()->getParam('auto_actions')) {
            $html .= <<isMotorEpidsAvailable() || $this->isMotorKtypesAvailable();
    }

    protected function isMotorEpidsAvailable()
    {
        return $this->getListing()->getChildObject()->isPartsCompatibilityModeEpids();
    }

    protected function isMotorKtypesAvailable()
    {
        return $this->getListing()->getChildObject()->isPartsCompatibilityModeKtypes();
    }

    //########################################

    /**
     * @inheritdoc
     **/
    protected function getListing()
    {
        if ($this->_listing === null) {
            $this->_listing = Mage::helper('M2ePro/Component_Ebay')->getCachedObject(
                'Listing', $this->getRequest()->getParam('id')
            );
        }

        return $this->_listing;
    }

    //########################################

    protected function prepareExistingMotorsData()
    {
        $this->injectMotorAttributeData();

        $this->_productsMotorsData = array();
        $motorsHelper              = Mage::helper('M2ePro/Component_Ebay_Motors');

        $items   = array();
        $filters = array();
        $groups  = array();

        foreach ($this->getCollection()->getItems() as $product) {
            if (!$product->getData('is_motors_attribute_in_product_attribute_set')) {
                continue;
            }

            $productId = $product->getData('listing_product_id');

            $attributeCode = $this->_motorsAttribute->getAttributeCode();
            $attributeValue = $product->getData($attributeCode);

            $this->_productsMotorsData[$productId] = $motorsHelper->parseAttributeValue($attributeValue);

            $items   = array_merge($items, array_keys($this->_productsMotorsData[$productId]['items']));
            $filters = array_merge($filters, $this->_productsMotorsData[$productId]['filters']);
            $groups  = array_merge($groups, $this->_productsMotorsData[$productId]['groups']);
        }

        //-------------------------------
        $typeIdentifier = $motorsHelper->getIdentifierKey($this->getMotorsType());

        $select = Mage::getResourceModel('core/config')->getReadConnection()
            ->select()
            ->from(
                $motorsHelper->getDictionaryTable($this->getMotorsType()),
                array($typeIdentifier)
            )
            ->where('`'.$typeIdentifier.'` IN (?)', $items);

        if ($motorsHelper->isTypeBasedOnEpids($this->getMotorsType())) {
            $select->where('scope = ?', $motorsHelper->getEpidsScopeByType($this->getMotorsType()));
        }

        $existedItems = $select->query()->fetchAll(PDO::FETCH_COLUMN);
        //-------------------------------

        //-------------------------------
        $filtersTable = Mage::helper('M2ePro/Module_Database_Structure')
            ->getTableNameWithPrefix('m2epro_ebay_motor_filter');
        $select = Mage::getResourceModel('core/config')->getReadConnection()
            ->select()
            ->from(
                $filtersTable,
                array('id')
            )
            ->where('`id` IN (?)', $filters);

        $existedFilters = $select->query()->fetchAll(PDO::FETCH_COLUMN);
        //-------------------------------

        //-------------------------------
        $groupsTable = Mage::helper('M2ePro/Module_Database_Structure')
            ->getTableNameWithPrefix('m2epro_ebay_motor_group');
        $select = Mage::getResourceModel('core/config')->getReadConnection()
            ->select()
            ->from(
                $groupsTable,
                array('id')
            )
            ->where('`id` IN (?)', $groups);

        $existedGroups = $select->query()->fetchAll(PDO::FETCH_COLUMN);
        //-------------------------------

        foreach ($this->_productsMotorsData as $productId => $productMotorsData) {
            foreach (array_diff(array_keys($productMotorsData['items']), $existedItems) as $key) {
                unset($this->_productsMotorsData[$productId]['items'][$key]);
            }

            $invalidFilters = array_diff(
                $productMotorsData['filters'],
                array_intersect($productMotorsData['filters'], $existedFilters)
            );
            foreach ($invalidFilters as $key => $filterId) {
                unset($this->_productsMotorsData[$productId]['filters'][$key]);
            }

            $invalidGroups = array_diff(
                $productMotorsData['groups'],
                array_intersect($productMotorsData['groups'], $existedGroups)
            );
            foreach ($invalidGroups as $key => $groupId) {
                unset($this->_productsMotorsData[$productId]['groups'][$key]);
            }
        }

        return $this;
    }

    protected function injectMotorAttributeData()
    {
        $productsIds = array();
        foreach ($this->getCollection()->getItems() as $product) {
            if (!$product->getData('is_motors_attribute_in_product_attribute_set')) {
                continue;
            }

            $productsIds[] = $product->getEntityId();
        }

        $attributeData = array();
        $queryStmt = Mage::getResourceModel('core/config')->getReadConnection()
            ->select()
            ->from(
                Mage::helper('M2ePro/Module_Database_Structure')->getTableNameWithPrefix('catalog_product_entity_text'),
                array(
                    'entity_id', 'value'
                )
            )
            ->where('attribute_id = ?', $this->_motorsAttribute->getId())
            ->where('entity_id IN (?)', $productsIds)
            ->where(
                'store_id IN (?)', array(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID,
                $this->getListing()->getStoreId())
            )
            ->order('store_id ASC')
            ->query();

        while ($row = $queryStmt->fetch()) {
            $attributeData[$row['entity_id']] = $row['value'];
        }

        $attributeCode = $this->_motorsAttribute->getAttributeCode();
        foreach ($this->getCollection()->getItems() as $product) {
            if (isset($attributeData[$product->getEntityId()])) {
                $product->setData($attributeCode, $attributeData[$product->getEntityId()]);
            }
        }
    }

    //########################################
}


text:
import { Task } from '../task';

import { Server } from 'karma';

function karmaFactory(opts) {
    let name = opts.name || 'karma';
    Task.checkRequiredParams(name, opts, ['config']);

    let configFile = process.cwd() + '/' + opts.config;

    return Task.addGulpTask(name, () => {
        return new Promise((done) => {
            // server.start({configFile}, resolve)
            new Server(configFile, [done]).start();
        });
    });
}

export  { karmaFactory as karma };

redpajama_set_name: RedPajamaGithub


text:
using System;

#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
#endif

using LoginScreen.Views;

namespace LoginScreen.ViewControllers
{
	class RegistrationViewController : BaseViewController
	{
		readonly ICredentialsProvider credentialsProvider;
		readonly ILoginScreenMessages messages;
		Action completionHandler;

		public RegistrationViewController (ICredentialsProvider credentialsProvider, ILoginScreenMessages messages)
			: base (messages.RegistrationFormTitle)
		{
			this.credentialsProvider = credentialsProvider;
			this.messages = messages;
		}

		public void SetCompletionHandler (Action completionHandler)
		{
			this.completionHandler = completionHandler;
		}

		protected override BaseFormView CreateFormView ()
		{
			var form = new RegistrationFormView
			{
				Title = messages.RegistrationFormTitle,
				EmailFieldPlaceHolder = messages.EmailFieldPlaceHolder,
				UserNameFieldPlaceHolder = messages.UserNameFieldPlaceHolder,
				PasswordFieldPlaceHolder = messages.PasswordFieldPlaceHolder,
				PasswordConfirmationFieldPlaceHolder = messages.PasswordConfirmationFieldPlaceHolder,
				RegisterButtonTitle = messages.RegisterButtonTitle
			};

			form.RegisterClick += RegisterClick;

			return form;
		}

		void RegisterClick (object sender, EventArgs e)
		{
			View.EndEditing (true);

			var form = sender as RegistrationFormView;
			if (form != null) {
				bool valid = true;

				if (String.IsNullOrEmpty (form.Email)) {
					form.ShowBubbleForEmail (messages.ErrorMessageEmailRequired);
					valid = false;
				} else if (!IsEmailValid (form.Email)) {
					form.ShowBubbleForEmail (messages.ErrorMessageEmailInvalid);
					valid = false;
				}
				if (String.IsNullOrEmpty (form.UserName)) {
					form.ShowBubbleForUserName (messages.ErrorMessageUserNameRequired);
					valid = false;
				}
				if (String.IsNullOrEmpty (form.Password)) {
					form.ShowBubbleForPassword (messages.ErrorMessagePasswordRequired);
					valid = false;
				} else if (!form.Password.Equals (form.PasswordConfirmation, StringComparison.Ordinal)) {
					form.ShowBubbleForPasswordConfirmation (messages.ErrorMessagePasswordDoesNotMatch);
					valid = false;
				}

				if (valid) {
					StartActivityAnimation (messages.RegistrationWaitingMessage);
					credentialsProvider.Register (form.Email, form.UserName, form.Password, Registered, x => Failed (form, x));
				}
			}
		}

		void Registered ()
		{
			InvokeOnMainThread (() => {
				if (credentialsProvider.NeedLoginAfterRegistration) {
					StopActivityAnimation ();
					#if __UNIFIED__
					NavigationController.PopViewController (true);
					#else
					NavigationController.PopViewControllerAnimated (true);
					#endif
				} else {
					StopActivityAnimation ();
					#if __UNIFIED__
					NavigationController.PopViewController (false);
					#else
					NavigationController.PopViewControllerAnimated (false);
					#endif
					completionHandler.Invoke ();
				}
			});
		}

		void Failed (RegistrationFormView form, LoginScreenFaultDetails details)
		{
			InvokeOnMainThread (() => {
				StopActivityAnimation ();
				if (!String.IsNullOrEmpty (details.EmailErrorMessage)) {
					form.ShowBubbleForEmail (details.EmailErrorMessage);
				}
				if (!String.IsNullOrEmpty (details.UserNameErrorMessage)) {
					form.ShowBubbleForUserName (details.UserNameErrorMessage);
				}
				if (!String.IsNullOrEmpty (details.PasswordErrorMessage)) {
					form.ShowBubbleForPassword (details.PasswordErrorMessage);
				}
				if (!String.IsNullOrEmpty (details.CommonErrorMessage)) {
					ShowAlert (messages.RegistrationCommonErrorTitle, details.CommonErrorMessage, messages.AlertCancelButtonTitle);
				}
			});
		}
	}
}


text:
/**
 * @file
 *   This file implements the OpenThread platform abstraction for the alarm.
 *
 */

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>

#include "openthread-system.h"
#include <openthread/config.h>
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/diag.h>
#include "common/logging.hpp"

#include "platform-efr32.h"
#include "utils/code_utils.h"

#include "em_core.h"
#include "rail.h"
#include "sl_sleeptimer.h"

#define XTAL_ACCURACY 200

static sl_sleeptimer_timer_handle_t sl_handle;
static uint32_t                     sAlarm     = 0;
static bool                         sIsRunning = false;

static void AlarmCallback(sl_sleeptimer_timer_handle_t *aHandle, void *aData)
{
    otSysEventSignalPending();
}

void efr32AlarmInit(void)
{
    memset(&sl_handle, 0, sizeof sl_handle);
}

uint32_t otPlatAlarmMilliGetNow(void)
{
    uint64_t    ticks;
    uint64_t    now;
    sl_status_t status;

    ticks  = sl_sleeptimer_get_tick_count64();
    status = sl_sleeptimer_tick64_to_ms(ticks, &now);
    assert(status == SL_STATUS_OK);
    return (uint32_t)now;
}

uint32_t otPlatTimeGetXtalAccuracy(void)
{
    return XTAL_ACCURACY;
}

void otPlatAlarmMilliStartAt(otInstance *aInstance, uint32_t aT0, uint32_t aDt)
{
    OT_UNUSED_VARIABLE(aInstance);
    sl_status_t status;
    int32_t     remaining;
    uint32_t    ticks;

    sl_sleeptimer_stop_timer(&sl_handle);

    sAlarm     = aT0 + aDt;
    remaining  = (int32_t)(sAlarm - otPlatAlarmMilliGetNow());
    sIsRunning = true;

    if (remaining <= 0)
    {
        otSysEventSignalPending();
    }
    else
    {
        status = sl_sleeptimer_ms32_to_tick(remaining, &ticks);
        assert(status == SL_STATUS_OK);

        status = sl_sleeptimer_start_timer(&sl_handle, ticks, AlarmCallback, NULL, 0,
                                           SL_SLEEPTIMER_NO_HIGH_PRECISION_HF_CLOCKS_REQUIRED_FLAG);
        assert(status == SL_STATUS_OK);
    }
}

void otPlatAlarmMilliStop(otInstance *aInstance)
{
    OT_UNUSED_VARIABLE(aInstance);

    sl_sleeptimer_stop_timer(&sl_handle);
    sIsRunning = false;
}

void efr32AlarmProcess(otInstance *aInstance)
{
    int32_t remaining;

    if (sIsRunning)
    {
        remaining = (int32_t)(sAlarm - otPlatAlarmMilliGetNow());

        if (remaining <= 0)
        {
            sIsRunning = false;

#if OPENTHREAD_CONFIG_DIAG_ENABLE
            if (otPlatDiagModeGet())
            {
                otPlatDiagAlarmFired(aInstance);
            }
            else
#endif
            {
                otPlatAlarmMilliFired(aInstance);
            }
        }
    }
}


text:
import type { UIPlugin } from '@uppy/core'
import type { Provider } from '@uppy/companion-client'

interface ProviderViewOptions {
    provider: Provider
    viewType?: 'list' | 'grid'
    showTitles?: boolean
    showFilter?: boolean
    showBreadcrumbs?: boolean
}

interface OnFirstRenderer {
    onFirstRender: () => any
}

declare class ProviderView {
  constructor (plugin: UIPlugin & OnFirstRenderer, opts: ProviderViewOptions)
  // @todo add other provider view methods
}

export default ProviderView


text:
#import "FacebookPhotoDetailViewController.h"
#import "UIKit+KGOAdditions.h"
#import "Foundation+KGOAdditions.h"
#import "KGOSocialMediaController+FacebookAPI.h"
#import "KGOAppDelegate.h"
#import "CoreDataManager.h"
#import "FacebookModel.h"
#import "FacebookModule.h"

@interface FacebookPhotoDetailViewController (Private)

- (void)requestImage:(FacebookPhoto *)photo;
- (void)handlePreviewTap:(UIRotationGestureRecognizer *)gestureRecognizer;
- (void)fadeControlsAppropriately;
- (void)fadeInControls;
- (void)fadeOutControls;

@end

@implementation FacebookPhotoDetailViewController

@synthesize connection;
@synthesize currentURL;

/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization
 }
 return self;
 }
 */
- (void)dealloc
{
    [currentURL release];
    [connection release];

    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark -

- (void)displayPost {
    DLog(@"%@", self.photo);

    UIImage *image = nil;
    if (self.photo.data) {
        image = [UIImage imageWithData:self.photo.data];
    } else if(self.photo.thumbData) {
        image = [UIImage imageWithData:self.photo.thumbData];
        [self requestImage:self.photo];
    }

    UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
    [self.mediaView setPreviewView:imageView];
    [self.mediaView setPreviewSize:image.size];
}

- (void)setPhoto:(FacebookPhoto *)photo {
    self.post = photo;
}

- (FacebookPhoto *)photo {
    return (FacebookPhoto *)self.post;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Photo";
}

- (void)viewDidUnload
{
    self.photo = nil;
    self.currentURL = nil;
    self.connection.delegate = nil;
    self.connection = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark - Table view methods

- (NSString *)postTitle {
    return  self.photo.title;
}

- (void)requestImage:(FacebookPhoto *)photo {

    if ([self.connection isConnected]) {
        [self.connection cancel];
    }

    if (!self.connection) {
        self.connection = [[[ConnectionWrapper alloc] initWithDelegate:self] autorelease];
    }
    self.currentURL = [NSURL URLWithString:photo.src];
    if ([self.connection requestDataFromURL:self.currentURL allowCachedResponse:YES]) {
        [KGO_SHARED_APP_DELEGATE() showNetworkActivityIndicator];
    }
}

// ConnectionWrapper delegate
- (void)connection:(ConnectionWrapper *)wrapper handleData:(NSData *)data {
    // TODO: If memory usage becomes a concern, convert images to PNG using UIImagePNGRepresentation(). PNGs use considerably less RAM.
    if (connection.theURL == self.currentURL) {
        UIImage *image = [UIImage imageWithData:data];
        if(image) {
            self.photo.data = data;
            [[CoreDataManager sharedManager] saveData];
            UIImageView *imageView = (UIImageView *)self.mediaView.previewView;
            imageView.image = [UIImage imageWithData:data];
        }
    }

    self.connection = nil;
    [KGO_SHARED_APP_DELEGATE() hideNetworkActivityIndicator];
}

- (void)connection:(ConnectionWrapper *)wrapper handleConnectionFailureWithError:(NSError *)error {
    self.connection = nil;
    [KGO_SHARED_APP_DELEGATE() hideNetworkActivityIndicator];
}

#pragma mark FacebookMediaDetailViewController
- (NSString *)identifierForBookmark {
    return self.photo.identifier;
}

- (NSString *)mediaTypeForBookmark {
    return @"photo";
}

- (NSString *)mediaTypeHumanReadableName{
    return @"photo";
}

- (NSString *)closeButtonName {
    return @"Photos";
}

- (BOOL)hideToolbarsInLandscape {
    return YES;
}
@end


text:
package github.nisrulz.logger;

import android.util.Log;

public class Logger {

  private final String TAG;
  private final int priority;

  public static Logger withTag(String tag) {
    return new Logger(tag);
  }

  private Logger(String TAG) {
    this.TAG = TAG;
    this.priority = Log.DEBUG; // This could be ERROR / INFO / VERBOSE
  }

  public Logger log(String message) {
    if (BuildConfig.DEBUG) {
      Log.println(priority, TAG, message);
    }
    return this;
  }

  public void withCause(Exception cause) {
    if (BuildConfig.DEBUG) {
      Log.println(priority, TAG, Log.getStackTraceString(cause));
    }
  }
}


text:
from django.db import models, migrations

def migrate_profiles(apps, schema_editor):
    from ...core.conf import settings

    User = apps.get_model(settings.AUTH_USER_MODEL)
    UserProfile = apps.get_model('spirit_user', 'UserProfile')

    users = User.objects.filter(st=None)

    # Avoid using bulk_create coz there are things setted on save
    for user in users:
        st = UserProfile()
        st.user = user
        st.is_verified = True
        st.save()

class Migration(migrations.Migration):

    dependencies = [
        ('spirit_user', '0003_auto_20150728_0448'),
    ]

    operations = [
        migrations.RunPython(migrate_profiles),
    ]


text:
package org.foxbpm.engine.impl.bpmn.deployer;

import java.io.ByteArrayInputStream;
import java.util.List;

import org.foxbpm.engine.Constant;
import org.foxbpm.engine.impl.Context;
import org.foxbpm.engine.impl.bpmn.behavior.StartEventBehavior;
import org.foxbpm.engine.impl.bpmn.behavior.TimerEventBehavior;
import org.foxbpm.engine.impl.entity.DeploymentEntity;
import org.foxbpm.engine.impl.entity.ProcessDefinitionEntity;
import org.foxbpm.engine.impl.entity.ResourceEntity;
import org.foxbpm.engine.impl.interceptor.CommandContext;
import org.foxbpm.engine.impl.persistence.DeploymentEntityManager;
import org.foxbpm.engine.impl.persistence.ProcessDefinitionManager;
import org.foxbpm.engine.impl.task.TaskDefinition;
import org.foxbpm.engine.impl.util.ExceptionUtil;
import org.foxbpm.engine.impl.util.GuidUtil;
import org.foxbpm.engine.impl.util.StringUtil;
import org.foxbpm.kernel.behavior.KernelFlowNodeBehavior;
import org.foxbpm.kernel.process.impl.KernelFlowNodeImpl;
import org.foxbpm.model.EventDefinition;
import org.foxbpm.model.StartEvent;
import org.foxbpm.model.TimerEventDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Bpmn发布处理类
 *
 * @author yangguangftlp
 * @date 2014年7月17日
 */
public class BpmnDeployer extends AbstractDeployer {
	/** 日志处理 */
	private final static Logger LOG = LoggerFactory.getLogger(BpmnDeployer.class);
	/** 版本号标记 */
	private final static String VERSION_FLAG = ":";

	public String deploy(DeploymentEntity deployment) {
		LOG.debug("start deploy BPMN");
		ResourceEntity resourceBpmnNew = null;
		// 获取资源实例
		for (ResourceEntity resourceEntity : deployment.getResources().values()) {
			if (resourceEntity.getName().toLowerCase().endsWith(BPMN_RESOURCE_SUFFIX)) {
				resourceBpmnNew = resourceEntity;
				break;
			}
		}
		// bpmn图不存在
		if (null == resourceBpmnNew) {
			throw ExceptionUtil.getException("10102001");
		}

		// 获取命令上下文
		CommandContext context = Context.getCommandContext();
		// 获取流程定义管理
		ProcessDefinitionManager processDefinitionManager = context.getProcessDefinitionManager();
		// 根据bpmn文件生成流程定义实例
		ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) processModelParseHandler.createProcessDefinition("dddd", new ByteArrayInputStream(resourceBpmnNew.getBytes()));
		String processDefineKey = processDefinitionEntity.getKey();
		// 获取发布Id
		String deploymentId = deployment.getId();

		// 处理新发布或者更新 isNew控制更新和添加
		if (deployment.isNew()) {
			// 获取发布实例管理器
			DeploymentEntityManager deploymentEntityManager = context.getDeploymentEntityManager();
			// 获取更新发布Id
			String updateDeploymentId = deployment.getUpdateDeploymentId();
			// 设置资源信息
			processDefinitionEntity.setResourceName(resourceBpmnNew.getName());
			processDefinitionEntity.setResourceId(resourceBpmnNew.getId());
			processDefinitionEntity.setDeploymentTime(deployment.getDeploymentTime());

			// 启动表单
			String formUri = getStartFormUri(processDefinitionEntity);
			// 处理更新发布
			if (StringUtil.isNotEmpty(updateDeploymentId)) {
				// 从sql缓存获取已存在的发布实例
				DeploymentEntity deploymentOld = deploymentEntityManager.findDeploymentById(updateDeploymentId);

				if (null == deploymentOld) {
					throw ExceptionUtil.getException("10102002" , updateDeploymentId);
				}

				ResourceEntity resourceBpmnOld = null;

				for (ResourceEntity resourceEntity : deploymentOld.getResources().values()) {
					if (resourceEntity.getName().toLowerCase().endsWith(BPMN_RESOURCE_SUFFIX)) {
						resourceBpmnOld = resourceEntity;
						break;
					}
				}
				// 如果不存在更新情况,可能发布的时候
				if (null == resourceBpmnOld) {
					Context.getCommandContext().getResourceManager().insert(resourceBpmnNew);
				} else {
					resourceBpmnOld.setBytes(resourceBpmnNew.getBytes());
					// 需要显示调用更新,主要更新bpmn资源
					deploymentEntityManager.update(resourceBpmnOld);
				}
				// 从sql缓存中获取流程定义实例,该操作会自动更新数据库
				ProcessDefinitionEntity processEntityNew = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(updateDeploymentId, processDefineKey);
				if (null == processEntityNew) {
					throw ExceptionUtil.getException("10102002" , updateDeploymentId);
				}
				processEntityNew.setCategory(processDefinitionEntity.getCategory());
				processEntityNew.setName(processDefinitionEntity.getName());
				processEntityNew.setResourceName(processDefinitionEntity.getResourceName());
				processEntityNew.setStartFormUri(formUri);
				// 获取流程定义Id
				processDefinitionEntity.setId(processEntityNew.getId());
				processDefinitionEntity.setDeploymentId(deploymentId);
			} else {// 新增
				int version = 1;
				// 如果外部传了version,则优先处理
				if (resourceBpmnNew.getVersion() != -1) {
					version = resourceBpmnNew.getVersion();
				} else { // 没有version,则取数据库中的最大version+1,数据库中也不存在时,则version=1
					ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefineKey);
					if (null != latestProcessDefinition) {
						version = latestProcessDefinition.getVersion() + 1;
					}
				}
				// 生成流程定义Id
				String processDefinitionId = new StringBuffer(processDefineKey).append(VERSION_FLAG).append(version).append(VERSION_FLAG).append(GuidUtil.CreateGuid()).toString();
				processDefinitionEntity.setId(processDefinitionId);
				processDefinitionEntity.setStartFormUri(formUri);
				processDefinitionEntity.setDeploymentId(deploymentId);
				processDefinitionEntity.setVersion(version);

				/********************* 数据库操作 *****************************/
				// 将bpmn资源实例入库
				deploymentEntityManager.insertResource(resourceBpmnNew);
				// 将流程定义实例添入库
				processDefinitionManager.insert(processDefinitionEntity);
			}
			// 添加自动调度,启动流程实例
			addAutoStartProcessInstanceJob(processDefinitionEntity);
		} else {
			// 不需要处理数据库,这里主要将重新封装流程定义实例包括两部分(bpmn模型,资源信息)
			ProcessDefinitionEntity processEntityNew = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefineKey);
			processDefinitionEntity.setDeploymentId(deploymentId);
			processDefinitionEntity.setId(processEntityNew.getId());
			processDefinitionEntity.setVersion(processEntityNew.getVersion());
			processDefinitionEntity.setResourceId(processEntityNew.getResourceId());
			processDefinitionEntity.setResourceName(processEntityNew.getResourceName());
			processDefinitionEntity.setDiagramResourceName(processEntityNew.getDiagramResourceName());
			processDefinitionEntity.setStartFormUri(processEntityNew.getStartFormUri());
			processDefinitionEntity.setDeploymentTime(processEntityNew.getDeploymentTime());
		}

		// 提供给其他发布器使用
		deployment.addProperty(Constant.PROCESS_DEFINE_ID, processDefinitionEntity.getId());
		// 将封装的流程定义实例添加到缓存
		Context.getProcessEngineConfiguration().getDeploymentManager().getProcessDefinitionCache().add(processDefinitionEntity.getId(), processDefinitionEntity);
		LOG.debug("end deploy BPMN");
		return processDefinitionEntity.getId();
	}

	/**
	 * 部署时候自动调度流程实例启动任务
	 *
	 * @param processDefinition
	 */
	private void addAutoStartProcessInstanceJob(ProcessDefinitionEntity processDefinition) {

		List<KernelFlowNodeImpl> flowNodes = processDefinition.getFlowNodes();
		KernelFlowNodeBehavior kernelFlowNodeBehavior = null;
		List<EventDefinition> eventDefinitions = null;

		for (KernelFlowNodeImpl kernelFlowNodeImpl : flowNodes) {
			kernelFlowNodeBehavior = kernelFlowNodeImpl.getKernelFlowNodeBehavior();
			// 获取START EVENT节点
			if (kernelFlowNodeBehavior instanceof StartEventBehavior) {
				eventDefinitions = ((StartEvent)((StartEventBehavior) kernelFlowNodeBehavior).getBaseElement()).getEventDefinitions();
				if(eventDefinitions != null){
					for (EventDefinition eventDefinition : eventDefinitions) {
						// 如果开始节点存在自动启动属性,那么就调度或者刷新 工作任务
						if (eventDefinition instanceof TimerEventDefinition) {
							TimerEventBehavior timerEventBehavior = new TimerEventBehavior((TimerEventDefinition)eventDefinition);
							Object[] params = new String[]{processDefinition.getId(), processDefinition.getKey(), processDefinition.getName(), kernelFlowNodeImpl.getId()};
							timerEventBehavior.execute(null, TimerEventBehavior.EVENT_TYPE_START, params);
						}
					}
				}
			}
		}
	}

	/**
	 * 获取发起节点表单
	 * <p>
	 * 顺序逻辑:startEvent后面人工节点的节点操作表单->流程定义默认表单
	 * </p>
	 *
	 * @param processDefinitionEntity
	 * @return
	 */
	private String getStartFormUri(ProcessDefinitionEntity processDefinitionEntity) {
		String formUri = null;
		TaskDefinition taskDefinition = processDefinitionEntity.getSubTaskDefinition();
		if (taskDefinition != null) {
			try{
				formUri = StringUtil.getString(taskDefinition.getFormUri().getValue(null));
			}catch(Exception ex){
				throw ExceptionUtil.getException("10104001",taskDefinition.getId());
			}

		}
		if (StringUtil.isNotEmpty(formUri)) {
			return formUri;
		}
		try{
			formUri = StringUtil.getString(processDefinitionEntity.getFormUri().getValue(null));
		}catch(Exception ex){
			throw ExceptionUtil.getException("10104002",processDefinitionEntity.getId());
		}

		return formUri;
	}

}


text: export * from './adapter/index';


text:
/**
 * @file libsyndicate/client.h
 * @author Jude Nelson
 * @date 9 Mar 2016
 *
 * @brief Header file for the Syndicate Gateway client API
 *
 * @see libsyndicate/client.cpp
 */

#ifndef _LIBSYNDICATE_CLIENT_H_
#define _LIBSYNDICATE_CLIENT_H_

#include "libsyndicate/libsyndicate.h"
#include "libsyndicate/manifest.h"
#include "libsyndicate/gateway.h"
#include "libsyndicate/download.h"

#define SG_CLIENT_MAX_REPLY_LEN         1024000 ///< Maximum length of a gateway reply: 1MB

// asynchronous upload
struct SG_client_request_async;
typedef size_t (*SG_client_read_callback_t)( char*, size_t, size_t, void* );

extern "C" {

// extra data to include in a write
struct SG_client_WRITE_data;

// set up a write reqeust
struct SG_client_WRITE_data* SG_client_WRITE_data_new(void);
int SG_client_WRITE_data_init( struct SG_client_WRITE_data* dat );
int SG_client_WRITE_data_set_write_delta( struct SG_client_WRITE_data* dat, struct SG_manifest* write_delta );
int SG_client_WRITE_data_set_mtime( struct SG_client_WRITE_data* dat, struct timespec* mtime );
int SG_client_WRITE_data_set_mode( struct SG_client_WRITE_data* dat, mode_t mode );
int SG_client_WRITE_data_set_size( struct SG_client_WRITE_data* dat, uint64_t mode );
int SG_client_WRITE_data_set_owner_id( struct SG_client_WRITE_data* dat, uint64_t owner_id );
int SG_client_WRITE_data_set_refresh( struct SG_client_WRITE_data* dat, int32_t read_freshness, int32_t write_freshness );
int SG_client_WRITE_data_set_routing_info( struct SG_client_WRITE_data* dat, uint64_t volume_id, uint64_t coordinator_id, uint64_t file_id, int64_t file_version );
int SG_client_WRITE_data_merge( struct SG_client_WRITE_data* dat, struct md_entry* ent );

// GET operations
int SG_client_get_manifest( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t remote_gateway_id, uint64_t coordinator_gateway_id, struct SG_manifest* manifest );
int SG_client_parse_manifest( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t coordinator_gateway_id, struct SG_chunk* serialized_manifest_chunk, struct SG_manifest* manifest );
int SG_client_get_block_async( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t remote_gateway_id, struct md_download_loop* dlloop, struct md_download_context* dlctx );
int SG_client_get_block_finish( struct SG_gateway* gateway, struct SG_manifest* manifest, struct md_download_context* dlctx, uint64_t* block_id, struct SG_chunk* block );
int SG_client_getxattr( struct SG_gateway* gateway, uint64_t gateway_id, char const* fs_path, uint64_t file_id, int64_t file_version, char const* xattr_name, uint64_t xattr_nonce, char** xattr_value, size_t* xattr_len );
int SG_client_listxattrs( struct SG_gateway* gateway, uint64_t gateway_id, char const* fs_path, uint64_t file_id, int64_t file_version, uint64_t xattr_nonce, char** xattr_list, size_t* xattr_list_len );

// signed blocks
int SG_client_serialize_signed_block( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_chunk* block_in, struct SG_chunk* block_out );
int SG_client_deserialize_signed_block( struct SG_gateway* gateway, struct SG_request_data* reqdat, uint64_t remote_gateway_id, struct SG_chunk* block_in, struct SG_chunk* block_out );

// gateway-to-gateway requests.
int SG_client_request_WRITE_setup( struct SG_gateway* gateway, SG_messages::Request* request, char const* fs_path, struct SG_client_WRITE_data* write_data );
int SG_client_request_TRUNCATE_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, off_t new_size );
int SG_client_request_RENAME_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, char const* new_path );
int SG_client_request_RENAME_HINT_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, struct SG_manifest_block* manifest_info, char const* new_path );
int SG_client_request_DETACH_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id );
int SG_client_request_REFRESH_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id );
int SG_client_request_PUTCHUNKS_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, struct SG_manifest_block* chunk_info, size_t chunk_info_len );
int SG_client_request_PUTCHUNKS_setup_ex( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id,  struct SG_manifest_block* chunk_info, size_t chunk_info_len, bool sign );
int SG_client_request_DELETECHUNKS_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, struct SG_manifest_block* chunk_info, size_t chunk_info_len );
int SG_client_request_DELETECHUNKS_setup_ex( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, struct SG_manifest_block* chunk_info, size_t chunk_info_len, bool sign );
int SG_client_request_SETXATTR_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, char const* xattr_name, char const* xattr_value, size_t xattr_value_len, int flags );
int SG_client_request_REMOVEXATTR_setup( struct SG_gateway* gateway, SG_messages::Request* request, struct SG_request_data* reqdat, uint64_t coordinator_id, char const* xattr_name );

// gateway-to-gateway messaging.  The corresponding driver methods will be run
struct SG_client_request_async* SG_client_request_async_new(void);
void SG_client_request_async_init( struct SG_client_request_async* req, SG_client_read_callback_t read_callback, size_t maxlen, void* cls );
void* SG_client_request_async_cls( struct SG_client_request_async* datareq );
int SG_client_request_send( struct SG_gateway* gateway, uint64_t dest_gateway_id, SG_messages::Request* control_plane, struct SG_chunk* data_plane, SG_messages::Reply* reply );
int SG_client_request_send_async( struct SG_gateway* gateway, uint64_t dest_gateway_id, SG_messages::Request* control_plane, struct SG_client_request_async* datareq, struct md_download_loop* dlloop, struct md_download_context* dlctx );
int SG_client_request_send_finish( struct SG_gateway* gateway, struct md_download_context* dlctx, SG_messages::Reply* reply );

// low-level download logic
int SG_client_download_async_start( struct SG_gateway* gateway, struct md_download_loop* dlloop, struct md_download_context* dlctx, uint64_t chunk_id, char* url, off_t max_size, void* cls, void (*free_cls)(void*) );
int SG_client_download_async_wait( struct md_download_context* dlctx, char** chunk_buf, off_t* chunk_len, void** cls );
void SG_client_download_async_cleanup( struct md_download_context* dlctx );
void SG_client_download_async_cleanup_loop( struct md_download_loop* dlloop );

// signed block authentication
int SG_client_block_sign( struct SG_gateway* gateway, struct SG_request_data* reqdat, struct SG_chunk* block_data, struct SG_chunk* signed_block_data );
int SG_client_block_verify( struct SG_gateway* gateway, struct SG_chunk* signed_block, uint64_t* ret_data_offset );

// errors
bool SG_client_request_is_remote_unavailable( int error );

}

#endif


text:
package com.codeforces.commons.math;

import junit.framework.TestCase;

import java.math.BigDecimal;

/**
 * @author Maxim Shipko (sladethe@gmail.com)
 *         Date: 17.06.14
 */
public class NumberUtilTest extends TestCase {
    public void testToLong() throws Exception {
        assertEquals("Can't convert double to long.", 100L, NumberUtil.toLong(100.01D));
        assertEquals("Can't convert double to long.", -1000000000L, NumberUtil.toLong(-1000000000.0D));
        assertEquals("Can't convert double to long.", -1000000000L, NumberUtil.toLong(-1000000000.9D));
        assertEquals("Can't convert double to long.", -1000000001L, NumberUtil.toLong(-1000000000.999999999999999999D));
        assertEquals("Can't convert string to long.", -100L, (long) NumberUtil.toLong("-100.0"));
        assertEquals("Can't convert string to long.", -101L, (long) NumberUtil.toLong(new BigDecimal("-101.0")));
    }
}


text:
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    context: __dirname + '/src',
    devtool: 'source-map',
    entry: './entry.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    },
    plugins: [
        new CopyWebpackPlugin([
            { from:  './index.html', to: 'index.html' }
        ]),
        new ExtractTextPlugin('style.css')
    ],
    module: {
        preLoaders: [
            {
                test: /\.(js|jsx)$/,
                loaders: ['eslint'],
                include:  __dirname + '/src/js'
            }
        ],
        loaders: [
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('style', 'css?sourceMap!autoprefixer?browsers=last 2 versions!sass')
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel', // Automatically generates source maps without the sourceMaps config
                query: {
                    presets: ['react', 'es2015']
                }
            }
        ]
    },
    eslint: {
        failOnWarning: false,
        failOnError: false
    }
};


text:
"""
    mpijob

    Python SDK for MPI-Operator  # noqa: E501

    The version of the OpenAPI document: v2beta1
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest
import datetime

import mpijob
from mpijob.models.v1_replica_status import V1ReplicaStatus  # noqa: E501
from mpijob.rest import ApiException

class TestV1ReplicaStatus(unittest.TestCase):
    """V1ReplicaStatus unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def make_instance(self, include_optional):
        """Test V1ReplicaStatus
            include_option is a boolean, when False only required
            params are included, when True both required and
            optional params are included """
        # model = mpijob.models.v1_replica_status.V1ReplicaStatus()  # noqa: E501
        if include_optional :
            return V1ReplicaStatus(
                active = 56,
                failed = 56,
                succeeded = 56
            )
        else :
            return V1ReplicaStatus(
        )

    def testV1ReplicaStatus(self):
        """Test V1ReplicaStatus"""
        inst_req_only = self.make_instance(include_optional=False)
        inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
    unittest.main()


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Torrey bot. Club 65: 659 (1938)

#### Original name
Poria alachuana Murrill, 1938

### Remarks
null


text:
Pattern: Use of `copy.copy(os.environ)`

Issue: -

## Description

`os.environ` is not a dictionary but a proxy object, so shallow copy has still effects on original object. Use `os.environ.copy()` instead.

Example of **incorrect** code:

```python
import copy
import os

wrong_env_copy = copy.copy(os.environ)  # will emit pylint warning
wrong_env_copy['ENV_VAR'] = 'new_value'  # changes os.environ
assert os.environ['ENV_VAR'] == 'new_value'
```

Example of **correct** code:

```python
import copy
import os

good_env_copy = dict(os.environ)
good_env_copy['ENV_VAR'] = 'different_value'  # doesn't change os.environ
assert os.environ['ENV_VAR'] == 'new_value'
```

## Further Reading

* [Python - Issue15373](https://bugs.python.org/issue15373)


text:
class Tdiff::Commands::Help < Tdiff::Commands::Base
  def run
  end
end


text:
using ZXing.QrCode.Internal;
using Shadowsocks.Controller;
using Shadowsocks.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shadowsocks.Model;

namespace Shadowsocks.View
{
    public partial class QRCodeForm : Form
    {
        private string code;

        public QRCodeForm(string code)
        {
            this.code = code;
            InitializeComponent();
            this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon());
            this.Text = I18N.GetString("QRCode and URL");
        }

        private void GenQR(string ssconfig)
        {
            string qrText = ssconfig;
            QRCode code = ZXing.QrCode.Internal.Encoder.encode(qrText, ErrorCorrectionLevel.M);
            ByteMatrix m = code.Matrix;
            int blockSize = Math.Max(pictureBox1.Height/m.Height, 1);

            var qrWidth = m.Width*blockSize;
            var qrHeight = m.Height*blockSize;
            var dWidth = pictureBox1.Width - qrWidth;
            var dHeight = pictureBox1.Height - qrHeight;
            var maxD = Math.Max(dWidth, dHeight);
            pictureBox1.SizeMode = maxD >= 7*blockSize ? PictureBoxSizeMode.Zoom : PictureBoxSizeMode.CenterImage;

            Bitmap drawArea = new Bitmap((m.Width*blockSize), (m.Height*blockSize));
            using (Graphics g = Graphics.FromImage(drawArea))
            {
                g.Clear(Color.White);
                using (Brush b = new SolidBrush(Color.Black))
                {
                    for (int row = 0; row < m.Width; row++)
                    {
                        for (int col = 0; col < m.Height; col++)
                        {
                            if (m[row, col] != 0)
                            {
                                g.FillRectangle(b, blockSize*row, blockSize*col, blockSize, blockSize);
                            }
                        }
                    }
                }
            }
            pictureBox1.Image = drawArea;
        }

        private void QRCodeForm_Load(object sender, EventArgs e)
        {
            var servers = Configuration.Load();
            var serverDatas = servers.configs.Select(
                server =>
                    new KeyValuePair<string, string>(ShadowsocksController.GetQRCode(server), server.FriendlyName())
                ).ToList();
            listBox1.DataSource = serverDatas;

            var selectIndex = serverDatas.FindIndex(serverData => serverData.Key.StartsWith(code));
            if (selectIndex >= 0) listBox1.SetSelected(selectIndex, true);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var url = (sender as ListBox)?.SelectedValue.ToString();
            GenQR(url);
            textBoxURL.Text = url;
        }

        private void textBoxURL_Click(object sender, EventArgs e)
        {
            textBoxURL.SelectAll();
        }
    }
}


text:
from . import api

from .resources.tests import Test

# 添加路由
api.add_resource(Test, '/tests')


text:
import argparse
from ipaddress import ip_address
from itertools import chain
import logging
from multiprocessing import Process, Queue
import os
import statistics
from time import perf_counter
from typing import Tuple, List, Optional

from twisted.internet import defer
from twisted.python.failure import Failure

from dnsagent.app import App, init_log
from dnsagent.resolver import HostsResolver, ExtendedResolver, TCPExtendedResolver
from dnsagent.server import ExtendedDNSServerFactory
from dnsagent.utils import get_reactor, wait_for_tcp

init_log()

# set log level for root logger
if os.environ.get('DEBUG'):
    logging.getLogger().setLevel(logging.DEBUG)
else:
    logging.getLogger().setLevel(logging.ERROR)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# use IOCP reactor if available to workaround descriptor limit
try:
    import twisted.internet.iocpreactor
except ImportError:
    pass
else:
    twisted.internet.iocpreactor.install()

DEFAULT_SERVER_ADDR = ('127.0.1.88', 5353)
_server_process = None

def gen_host_name(num: int):
    return 'a%08d' % (num % int(1e8))

def gen_ip_address(num: int):
    return str(ip_address(0x7f000001 + (num % int(1e8))))

def run_server(bind: Tuple[str, int]):
    logger.info('starting server on %r', bind)

    mapping = dict((gen_host_name(i), gen_ip_address(i)) for i in range(10000))
    resolver = HostsResolver(mapping=mapping)
    server = ExtendedDNSServerFactory(resolver=resolver)

    reactor = get_reactor()
    app = App(reactor=reactor)
    app.start((server, [bind]))

    reactor.run()

class QueryRunner:
    def __init__(
            self, addr: Tuple[str, int], count: int, concurrency=100,
            tcp_only=False, no_reuse_resolver=False,
            reactor=None, **extra
    ):
        assert count > 0 and concurrency > 0
        self.addr = addr
        self.count = count
        self.concurrency = concurrency
        self.tcp_only = tcp_only
        self.no_reuse_resolver = no_reuse_resolver
        self.reactor = get_reactor(reactor)

        self._resolver = None
        self.done = defer.Deferred()
        self.results = [None] * self.count      # type: List[Optional[float]]
        self.waitting = 0
        self.finished = 0
        self.started = 0

    def run(self):
        self.tick()
        return self.done

    def tick(self):
        if self.started < self.count:
            n = min(self.concurrency - self.waitting, self.count - self.started)
            for _ in range(n):
                self.waitting += 1
                self.spawn(self.started)
                self.started += 1
        else:
            assert self.started == self.count
            if self.finished == self.count:
                assert self.waitting == 0
                self.done.callback(self.results)

    def spawn(self, index):
        hostname = gen_host_name(index).encode()
        d = self.get_resolver().lookupAddress(hostname)
        d.addCallbacks(
            callback=self.got_answer, callbackArgs=(index, perf_counter()),
            errback=self.failed,
        ).addErrback(self.unexpected)

    def got_answer(self, answer, index: int, started_time: float):
        diff = perf_counter() - started_time
        self.results[index] = diff
        self.finished_one()

    def failed(self, err):
        self.finished_one()

    def finished_one(self):
        self.finished += 1
        self.waitting -= 1
        self.tick()

    def unexpected(self, err):
        logger.error('unhandled exception: %r', err)
        self.done.errback(err)
        return err

    def get_resolver(self):
        if not self._resolver or self.no_reuse_resolver:
            resolver_cls = ExtendedResolver if not self.tcp_only else TCPExtendedResolver
            self._resolver = resolver_cls(servers=[self.addr], reactor=self.reactor)
        return self._resolver

RunQueryResultType = Tuple[float, List[Optional[float]]]

def run_query(inqueue: Queue, outqueue: Queue):
    server_addr, options = inqueue.get()
    logger.info('run_query() begins')

    def got_result(result: List[Optional[float]]):
        diff = perf_counter() - started_time
        logger.info('%d requests finished in %.3f s', options.count, diff)
        outqueue.put((diff, result))

    querier = QueryRunner(addr=server_addr, **vars(options))
    started_time = perf_counter()
    d = querier.run()
    d.addCallback(got_result)

    reactor = get_reactor()
    reactor.run()

def process_results(results: List[RunQueryResultType], options):
    def convert_none(arg):
        if arg is None:
            return float('+inf')
        else:
            return arg

    total_queries = options.process * options.count
    concurrency = options.process * options.concurrency
    avg_process_time = statistics.mean(process_time for process_time, _ in results)
    qps = total_queries / avg_process_time

    proc_query_times_cat = chain.from_iterable(times for _, times in results)
    query_times = sorted(map(convert_none, proc_query_times_cat))

    failure_rate = sum(int(t == float('+inf')) for t in query_times) / total_queries

    median_query_time = statistics.median(query_times)

    print('options: ', options)

    interesting_vars = [
        'qps', 'failure_rate', 'median_query_time', 'total_queries', 'concurrency',
    ]
    for name in interesting_vars:
        value = locals()[name]
        print('{name}: {value}'.format_map(locals()))

    if options.stats_file:
        with open(options.stats_file, 'wt+') as fp:
            fp.writelines('%s\n' % t for t in query_times)

    # TODO: print bar chart of query time

def run_controller(server_addr, options):
    def server_ready(ignore):
        for inq, outq, proc in queriers:
            inq.put((server_addr, options))

        results = []     # type: List[Tuple[float, List[Optional[float]]]
        for inq, outq, proc in queriers:
            results.append(outq.get(timeout=60))
            proc.terminate()

        try:
            process_results(results, options)
        except Exception:
            logger.exception('process_result()')

    def server_failed(err):
        logger.error('failed to start server: %r', err)
        for _, _, proc in queriers:
            proc.terminate()

    def teardown(result):
        if isinstance(result, Failure):
            logger.error('unhandled error: %r', result)
            reactor.stop()

        if _server_process:
            _server_process.terminate()
        reactor.stop()

    queriers = []   # type: List[Tuple[Queue, Queue, Process]]
    for n in range(options.process):
        inqueue, outqueue = Queue(), Queue()
        client = Process(target=run_query, args=(inqueue, outqueue))
        client.start()
        queriers.append((inqueue, outqueue, client))

    d = wait_for_tcp(server_addr, logger=logger)
    d.addCallbacks(server_ready, server_failed).addBoth(teardown)

    reactor = get_reactor()
    reactor.run()

def parse_args():
    parser = argparse.ArgumentParser()

    modes = parser.add_mutually_exclusive_group()
    modes.add_argument(
        '-s', '--server', dest='mode', action='store_const', const='server',
        help='server only mode',
    )
    modes.add_argument(
        '-c', '--client', dest='mode', action='store_const', const='client',
        help='client only mode',
    )

    parser.add_argument(
        '--address', help='server address',
    )
    parser.add_argument(
        '-p', '--process', default=2, type=int,
        help='number of client process',
    )
    parser.add_argument(
        '-n', '--count', default=4000, type=int,
        help='number of queries to run per process',
    )
    parser.add_argument(
        '--con', '--concurrency', dest='concurrency', default=500, type=int,
        help='maximum concurrent queries per process',
    )
    parser.add_argument(
        '--tcp-only', default=False, action='store_true',
        help='only use TCP for query',
    )
    parser.add_argument(
        '--no-reuse-resolver', default=False, action='store_true',
        help='use a new resolver for every query',
    )

    parser.add_argument('--stats-file', help='write query times to this file')

    return parser.parse_args()

def main():
    global _server_process

    options = parse_args()
    if options.address:
        host, port = options.address.split(':')
        port = int(port)
        server_addr = host, port    # type: Tuple[str, int]
    else:
        server_addr = DEFAULT_SERVER_ADDR

    if options.mode == 'server':
        run_server(server_addr)
    else:
        if options.mode != 'client':
            _server_process = Process(target=run_server, args=(server_addr,))
            _server_process.start()

        run_controller(server_addr, options)

if __name__ == '__main__':
    main()


text:
The zend-server family of classes provides functionality for the various server
classes, including [zend-xmlrpc](https://zendframework.github.io/zend-xmlrpc) and
[zend-json-server](https://zendframework.github.io/zend-json-server/).
`Zend\Server\Server` provides an interface that mimics PHP's `SoapServer` class;
all RPC-style server classes should implement this interface in order to provide a
standard server API.

The `Zend\Server\Reflection` tree provides a standard mechanism for performing
function and class introspection for use as callbacks with the server classes,
and provides data suitable for use with `Zend\Server\Server`'s `getFunctions()`
and `loadFunctions()` methods.


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace CoreDocker.Dal.Persistence
{
    public interface IUpdateCalls<T>
    {
        IUpdateCalls<T> Set<TType>(Expression<Func<T, TType>> expression, TType value);
        IUpdateCalls<T> Inc(Expression<Func<T, int>> expression, int value);
        IUpdateCalls<T> Inc(Expression<Func<T, long>> expression, long value);
        IUpdateCalls<T> Push<TT>(Expression<Func<T, IEnumerable<TT>>> expression, TT value);
        IUpdateCalls<T> SetOnInsert<TT>(Expression<Func<T, TT>> expression, TT value);
    }
}


text:
require "spec_helper"

describe OodCore do
  it "has a version number" do
    expect(OodCore::VERSION).not_to be nil
  end
end


text:
We all know EZ_Client is crap. When you send a ROM which is not listed in `romname.lst` it gets stored with an empty name (".gba").

This script creates a new `romname.lst` file using your ROM filenames.

## Usage

### Print results to stdout

```bash
gba-romname-gen.js path/to/gba/roms
```
### Save results to file

```bash
gba-romname-gen.js path/to/gba/roms > romname.lst
```
## Possible problems

Some files are ignored/skipped:

* Files without .gba extension
* ROMs with empty title/code (unlicensed)
* ROMs without ASCII title/code

## License

MIT


text:
const Joi = require('joi');

const urlSchema = Joi.string().uri({
  scheme: [
    'http',
    'https',
  ],
});

const cookieSchema = Joi.object({
  name: Joi.string().required(),
  value: Joi.string().required(),
  url: Joi.string(),
  domain: Joi.string(),
  path: Joi.string(),
  expires: Joi.number().min(1),
  httpOnly: Joi.boolean(),
  secure: Joi.boolean(),
  sameSite: Joi.string().regex(/^(Strict|Lax)$/),
});

const sharedQuerySchema = Joi.object({
  attachmentName: Joi.string(),
  scrollPage: Joi.boolean(),
  emulateScreenMedia: Joi.boolean(),
  enableGPU: Joi.boolean(),
  ignoreHttpsErrors: Joi.boolean(),
  waitFor: Joi.alternatives([
    Joi.number().min(1).max(60000),
    Joi.string().min(1).max(2000),
  ]),
  cookies: Joi.array().items(cookieSchema),
  output: Joi.string().valid(['pdf', 'screenshot', 'html']),
  'viewport.width': Joi.number().min(1).max(30000),
  'viewport.height': Joi.number().min(1).max(30000),
  'viewport.deviceScaleFactor': Joi.number().min(0).max(100),
  'viewport.isMobile': Joi.boolean(),
  'viewport.hasTouch': Joi.boolean(),
  'viewport.isLandscape': Joi.boolean(),
  'goto.timeout': Joi.number().min(0).max(60000),
  'goto.waitUntil': Joi.string().min(1).max(2000),
  'pdf.scale': Joi.number().min(0).max(1000),
  'pdf.displayHeaderFooter': Joi.boolean(),
  'pdf.landscape': Joi.boolean(),
  'pdf.pageRanges': Joi.string().min(1).max(2000),
  'pdf.format': Joi.string().min(1).max(2000),
  'pdf.width': Joi.string().min(1).max(2000),
  'pdf.height': Joi.string().min(1).max(2000),
  'pdf.fullPage': Joi.boolean(),
  'pdf.footerTemplate': Joi.string(),
  'pdf.headerTemplate': Joi.string(),
  'pdf.margin.top': Joi.string().min(1).max(2000),
  'pdf.margin.right': Joi.string().min(1).max(2000),
  'pdf.margin.bottom': Joi.string().min(1).max(2000),
  'pdf.margin.left': Joi.string().min(1).max(2000),
  'pdf.printBackground': Joi.boolean(),
  'screenshot.fullPage': Joi.boolean(),
  'screenshot.quality': Joi.number().integer().min(0).max(100),
  'screenshot.type': Joi.string().valid(['png', 'jpeg']),
  'screenshot.clip.x': Joi.number(),
  'screenshot.clip.y': Joi.number(),
  'screenshot.clip.width': Joi.number(),
  'screenshot.clip.height': Joi.number(),
  'screenshot.selector': Joi.string().regex(/(#|\.).*/),
  'screenshot.omitBackground': Joi.boolean(),
});

const renderQuerySchema = Joi.object({
  url: urlSchema.required(),
}).concat(sharedQuerySchema);

const renderBodyObject = Joi.object({
  url: urlSchema,
  html: Joi.string(),
  attachmentName: Joi.string(),
  scrollPage: Joi.boolean(),
  ignoreHttpsErrors: Joi.boolean(),
  emulateScreenMedia: Joi.boolean(),
  cookies: Joi.array().items(cookieSchema),
  output: Joi.string().valid(['pdf', 'screenshot', 'html']),
  viewport: Joi.object({
    width: Joi.number().min(1).max(30000),
    height: Joi.number().min(1).max(30000),
    deviceScaleFactor: Joi.number().min(0).max(100),
    isMobile: Joi.boolean(),
    hasTouch: Joi.boolean(),
    isLandscape: Joi.boolean(),
  }),
  waitFor: Joi.alternatives([
    Joi.number().min(1).max(60000),
    Joi.string().min(1).max(2000),
  ]),
  goto: Joi.object({
    timeout: Joi.number().min(0).max(60000),
    waitUntil: Joi.string().min(1).max(2000),
  }),
  pdf: Joi.object({
    scale: Joi.number().min(0).max(1000),
    displayHeaderFooter: Joi.boolean(),
    landscape: Joi.boolean(),
    pageRanges: Joi.string().min(1).max(2000),
    format: Joi.string().min(1).max(2000),
    width: Joi.string().min(1).max(2000),
    height: Joi.string().min(1).max(2000),
    fullPage: Joi.boolean(),
    footerTemplate: Joi.string(),
    headerTemplate: Joi.string(),
    margin: Joi.object({
      top: Joi.string().min(1).max(2000),
      right: Joi.string().min(1).max(2000),
      bottom: Joi.string().min(1).max(2000),
      left: Joi.string().min(1).max(2000),
    }),
    printBackground: Joi.boolean(),
  }),
  screenshot: Joi.object({
    fullPage: Joi.boolean(),
    quality: Joi.number().integer().min(0).max(100),
    type: Joi.string().valid(['png', 'jpeg']),
    clip: {
      x: Joi.number(),
      y: Joi.number(),
      width: Joi.number(),
      height: Joi.number(),
    },
    selector: Joi.string().regex(/(#|\.).*/),
    omitBackground: Joi.boolean(),
  }),
  failEarly: Joi.string(),
});

const renderBodySchema = Joi.alternatives([
  Joi.string(),
  renderBodyObject,
]);

module.exports = {
  renderQuerySchema,
  renderBodySchema,
  sharedQuerySchema,
};