问:
How do I write my jQuery to let me swap each images as many times as I want?
I'm writing jQuery code to solve a puzzle. A 3x3 table has an image in each cell (8 picture images and 1 white square image) but they can only switch if the clicked image is adjacent to a white/blank square. My code is working to the point that it will only allow adjacent images to move. However, I can only swap each image once. How do I write it to let me swap each images as many times as I want?

```<code>$(document).ready(function(event) {
    $("img").click(function(){
        var blankSquare = $("#blank");
        var blankIndex = $("img").index(blankSquare);
        //alert(blankIndex); //this updates as square moves
        var imageSquare = $(this);
        var imageIndex = $("img").index(this); //returns index of selected image
        //alert(imageIndex); //will update as selected image changes
        //swap image if it's index (position) is next adjacent to the white square
        if(imageSquare !== blankSquare) {
            if(imageIndex == 0 && blankIndex == 1) { //switch if image is at index 0
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 0 && blankIndex == 3) { //switch if image is at index 0
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 0) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 2) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 4) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
                imageClicked.data('clicked') == false;
            } else if(imageIndex == 2 && blankIndex == 1) { //switch if image is at index 2
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 2 && blankIndex == 5) { //switch if image is at index 2
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 0) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 4) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 6) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 1) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 3) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 5) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 7) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 2) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 4) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 8) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 6 && blankIndex == 3) { //switch if image is at index 6
                imageSquare.replaceWith(blankSquare);
                imageSquare.appendTo("td:empty");
            } else if(imageIndex == 6 && blankIndex == 7) { //switch if image is at index 6
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 4) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 6) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 8) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 8 && blankIndex == 5) { //switch if image is at index 8
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 8 && blankIndex == 7) { //switch if image is at index 8
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            }
        }//end of !== if-statement
    });
});
</code>```

HTML

```<code>    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Tile Game</title>
    <script src=" https://code.jquery.com/jquery-3.2.0.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="puzzle2.js" type="text/javascript"></script>
    </head>
    <body>
    <table>
<tr>
  <td><img src="SockeyOneRow3A.jpg" /></td>
  <td><img src="SockeyOneRow2B.jpg" /></td>
  <td><img src="SockeyOneRow3B.jpg" /></td>
</tr>
<tr>
  <td><img src="SockeyOneRow2A.jpg" /></td>
  <td><img id="blank" src="blank.jpg"  /></td>
  <td><img src="SockeyOneRow1B.jpg" /></td>
</tr>
<tr>
  <td><img src="SockeyOneRow1A.jpg" /></td>
  <td><img src="SockeyOneRow2C.jpg" /></td>
  <td><img src="SockeyOneRow3C.jpg" /></td>
</tr>
</table>
</body>
</html>
</code>```

答:
Not sure if I should answer my own post or not, but I figured it out.

I switched to using the attr() method. So first I found the sources of my blank image and my clicked image and stored them into separate variables.

```<code>var blankSource = $(blankSquare).attr("src");
var imageSource = $(imageSquare).attr("src");
</code>```

I then switched the source of the selected image with that of the blank image. The blank image variable (blankSquare) was created with it's ID so I had to transfer that with the blank image as well. Here's that code:

```<code>imageSquare.attr("src", blankSource); //this sets the blank image's source to the clicked image's source
imageSquare.attr("id", "blank"); //this sets an the ID value of "blank" the clicked image
blankSquare.attr("src", imageSource); //this sets the clicked image's source to the blank image's source
blankSquare.attr("id", " "); //this removes the id from the blank image
</code>```

This block of code replaced my original statements that appeared between my if-else statements. (There's probably a better way to set the adjacent restrictions, but this works.)

So this

```<code>imageSquare.replaceWith(blankSquare);
imageSquare.detach().appendTo("td:empty");
</code>```

became this

```<code>imageSquare.attr("src", blankSource);
imageSquare.attr("id", "blank");
blankSquare.attr("src", imageSource);
blankSquare.attr("id", " ");
</code>```

Body:
I'm writing jQuery code to solve a puzzle. A 3x3 table has an image in each cell (8 picture images and 1 white square image) but they can only switch if the clicked image is adjacent to a white/blank square. My code is working to the point that it will only allow adjacent images to move. However, I can only swap each image once. How do I write it to let me swap each images as many times as I want?

$(document).ready(function(event) {
    $("img").click(function(){
        var blankSquare = $("#blank");
        var blankIndex = $("img").index(blankSquare);
        //alert(blankIndex); //this updates as square moves
        var imageSquare = $(this);
        var imageIndex = $("img").index(this); //returns index of selected image
        //alert(imageIndex); //will update as selected image changes
        //swap image if it's index (position) is next adjacent to the white square
        if(imageSquare !== blankSquare) {
            if(imageIndex == 0 && blankIndex == 1) { //switch if image is at index 0
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 0 && blankIndex == 3) { //switch if image is at index 0
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 0) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 2) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 1 && blankIndex == 4) { //switch if image is at index 1
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
                imageClicked.data('clicked') == false;
            } else if(imageIndex == 2 && blankIndex == 1) { //switch if image is at index 2
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 2 && blankIndex == 5) { //switch if image is at index 2
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 0) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 4) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 3 && blankIndex == 6) { //switch if image is at index 3
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 1) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 3) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 5) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 4 && blankIndex == 7) { //switch if image is at index 4
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 2) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 4) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 5 && blankIndex == 8) { //switch if image is at index 5
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 6 && blankIndex == 3) { //switch if image is at index 6
                imageSquare.replaceWith(blankSquare);
                imageSquare.appendTo("td:empty");
            } else if(imageIndex == 6 && blankIndex == 7) { //switch if image is at index 6
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 4) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 6) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 7 && blankIndex == 8) { //switch if image is at index 7
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 8 && blankIndex == 5) { //switch if image is at index 8
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            } else if(imageIndex == 8 && blankIndex == 7) { //switch if image is at index 8
                imageSquare.replaceWith(blankSquare);
                imageSquare.detach().appendTo("td:empty");
            }
        }//end of !== if-statement
    });
});

HTML

    <meta charset="utf-8">
    <title>Tile Game</title>

Body:
Not sure if I should answer my own post or not, but I figured it out.

I switched to using the attr() method. So first I found the sources of my blank image and my clicked image and stored them into separate variables.

var blankSource = $(blankSquare).attr("src");
var imageSource = $(imageSquare).attr("src");

I then switched the source of the selected image with that of the blank image. The blank image variable (blankSquare) was created with it's ID so I had to transfer that with the blank image as well. Here's that code:

imageSquare.attr("src", blankSource); //this sets the blank image's source to the clicked image's source
imageSquare.attr("id", "blank"); //this sets an the ID value of "blank" the clicked image
blankSquare.attr("src", imageSource); //this sets the clicked image's source to the blank image's source
blankSquare.attr("id", " "); //this removes the id from the blank image

This block of code replaced my original statements that appeared between my if-else statements. (There's probably a better way to set the adjacent restrictions, but this works.)

So this

imageSquare.replaceWith(blankSquare);
imageSquare.detach().appendTo("td:empty");

became this

imageSquare.attr("src", blankSource);
imageSquare.attr("id", "blank");
blankSquare.attr("src", imageSource);
blankSquare.attr("id", " ");


来源: stackexchange

问:
magento final_price,min_price,max_price wrong values insertion
Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function

```<code>public function finish()
{
    Mage::dispatchEvent('catalog_product_import_after', array());

    $entity = new Varien_Object();
    Mage::getSingleton('index/indexer')->processEntityAction(
        $entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
    );
}
</code>```

where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?

My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1

Unit Price:absolute:2691|Case Price:absolute:12420

Unit Price:absolute:762|Case Price:absolute:7029

The save database function is

```<code>public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();

if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}

if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}

if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);

if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();

/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);

foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}

$this->setProductTypeInstance($product);

if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}

foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}

if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}

if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}

$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
@list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;

case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */

case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;

case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}

$isArray = false;
$setValue = $value;

if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}

if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}

if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);

if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}

$product->setData($field, $setValue);
}

if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}

$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);

$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}

foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}

$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);

$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}

/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}

return true;
}
</code>```

答:
This section of the code has been quite well tested, so it's unlikely (though conceivable) that this is a bug that you need to correct in the indexer. Can you provide more detail about the discrepancy that you are seeing?

There is a very good chance that you are seeing unexpected results because of some product being enabled/disabled, etc etc.

ContentLicense: CC BY-SA 2.5

Body:
Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function

public function finish()
{
    Mage::dispatchEvent('catalog_product_import_after', array());

    $entity = new Varien_Object();
    Mage::getSingleton('index/indexer')->processEntityAction(
        $entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
    );
}

where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?

My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1

Unit Price:absolute:2691|Case Price:absolute:12420

Unit Price:absolute:762|Case Price:absolute:7029

The save database function is

public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();

if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}

if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}

if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);

if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();

/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);

foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}

$this->setProductTypeInstance($product);

if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}

foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}

if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}

if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}

$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
@list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;

case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */

case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;

case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}

$isArray = false;
$setValue = $value;

if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}

if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}

if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);

if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}

$product->setData($field, $setValue);
}

if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}

$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);

$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}

foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}

$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);

$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}

/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}

return true;
}


问:
How to print json console.log data in browser?
I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.

script.js

```<code>$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
        mode = 'movie/',
        movie_id,
        key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
            movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',
            success: function(json) {
                console.dir(json);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
    });
});
</code>```

index.php

```<code><input id="movie" type="text" /><button>Search</button>
</code>```

This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.

答:
To output your JSON data to the browser, you need to modify the HTML of the page.

First, add a few elements to your index.php like so:

index.php

```<code><input id="movie" type="text" /><button>Search</button>

<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>
</code>```

Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:

```<code>$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
    mode = 'movie/',
    movie_id,
    key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
        movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',

            success: function(json) {

                // grab the span elements by ID and replace their text with the json text

                $("#movie-title").text(json.title);
                $("#movie-budget").text(json.budget);

                console.dir(json);
            },

            error: function(e) {
                console.log(e.message);
            }
        });
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.

script.js

$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
        mode = 'movie/',
        movie_id,
        key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
            movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',
            success: function(json) {
                console.dir(json);
            },
            error: function(e) {
                console.log(e.message);
            }
        });
    });
});

index.php

<input id="movie" type="text" /><button>Search</button>

This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.

Body:
To output your JSON data to the browser, you need to modify the HTML of the page.

First, add a few elements to your index.php like so:

index.php

<input id="movie" type="text" /><button>Search</button>

<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>

Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:

$(document).ready(function() {
    var url = 'http://api.themoviedb.org/3/',
    mode = 'movie/',
    movie_id,
    key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';

    $('button').click(function() {
        var input = $('#movie').val(),
        movie_id = encodeURI(input);
        $.ajax({
            type: 'GET',
            url: url + mode + movie_id + key,
            async: false,
            jsonpCallback: 'testing',
            contentType: 'application/json',
            dataType: 'jsonp',

            success: function(json) {

                // grab the span elements by ID and replace their text with the json text

                $("#movie-title").text(json.title);
                $("#movie-budget").text(json.budget);

                console.dir(json);
            },

            error: function(e) {
                console.log(e.message);
            }
        });
    });
});


问:
Reference outside the sealed class in Kotlin?
I'm trying to create a class that uses its own state to operate on the state of an external object that it holds a reference to.  The external object can be of class A or B, which are similar, but not controlled by the author.  So a sealed class is created to access their common attributes, per this earlier answer from @SimY4.

```<code>// *** DOES NOT COMPILE ***
class A {   // foreign class whose structure is not modifiable
  val prop get()= "some string made the Class-A way"
}
class B {   // foreign class whose structure is not modifiable
  val prop get()= "some string made the Class-B way"
}
data class ABTool (val obj:AB, val i:Int, val j:Int) {
  // class that manipulates i and j and uses them to do
  // things with AB's "common" attributes through the sealed class AB
  sealed class AB {   // substitute for a common interface
    abstract val prop: String
    abstract val addmagic: String
    data class BoxA(val o:A) : AB() {
      override val prop get()= o.prop
      override val addmagic get() = prop + this@???.magic  // HOW TO REFERENCE?
    }
    data class BoxB(val o:B) : AB() {
      override val prop get()= o.prop
      override val addmagic get() = this@???.magic + prop  // HOW TO REFERENCE?
    }
  }
  val magic get()= "magic: ${i*j}"
}
</code>```

The problem now is that I've figured out I can't operate on the external object in the way I want, because a sealed class can't refer to its outer class members.  Is there a better way to make this work, even if using a different approach (other than sealed class), while:

not changing foreign classes A or B;

respecting that A and B (and many others in the real case) are similar, so I'm trying to write one tool that calculates and adds magic to A and B with the same code base; and

noting that although the ABTool tools are the same, the way they are applied to add magic is slightly different in A vs. B, just as the to access the conceptually common elements of A and B may be different.

Any thoughts on this or a similar workaround?  Maybe a more functional approach that I haven't conceived yet?

答:
An alternative would be to add an ABTool field to AB:

```<code>sealed class AB(val tool: ABTool) {
  abstract val prop: String
  abstract val addmagic: String
  data class BoxA(val o:A, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = prop + tool.magic
  }
  data class BoxB(val o:B, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = tool.magic + prop
  }
}
</code>```

and pass this when creating it from ABTool. That's just what inner really does, after all.

In this specific case the field happens to be unused in AB itself and so you can remove it from there and make it val in BoxA and BoxB.

Body:
I'm trying to create a class that uses its own state to operate on the state of an external object that it holds a reference to.  The external object can be of class A or B, which are similar, but not controlled by the author.  So a sealed class is created to access their common attributes, per this earlier answer from @SimY4.

// *** DOES NOT COMPILE ***
class A {   // foreign class whose structure is not modifiable
  val prop get()= "some string made the Class-A way"
}
class B {   // foreign class whose structure is not modifiable
  val prop get()= "some string made the Class-B way"
}
data class ABTool (val obj:AB, val i:Int, val j:Int) {
  // class that manipulates i and j and uses them to do
  // things with AB's "common" attributes through the sealed class AB
  sealed class AB {   // substitute for a common interface
    abstract val prop: String
    abstract val addmagic: String
    data class BoxA(val o:A) : AB() {
      override val prop get()= o.prop
      override val addmagic get() = prop + this@???.magic  // HOW TO REFERENCE?
    }
    data class BoxB(val o:B) : AB() {
      override val prop get()= o.prop
      override val addmagic get() = this@???.magic + prop  // HOW TO REFERENCE?
    }
  }
  val magic get()= "magic: ${i*j}"
}

The problem now is that I've figured out I can't operate on the external object in the way I want, because a sealed class can't refer to its outer class members.  Is there a better way to make this work, even if using a different approach (other than sealed class), while:

not changing foreign classes A or B;

respecting that A and B (and many others in the real case) are similar, so I'm trying to write one tool that calculates and adds magic to A and B with the same code base; and

noting that although the ABTool tools are the same, the way they are applied to add magic is slightly different in A vs. B, just as the to access the conceptually common elements of A and B may be different.

Any thoughts on this or a similar workaround?  Maybe a more functional approach that I haven't conceived yet?

Body:
An alternative would be to add an ABTool field to AB:

sealed class AB(val tool: ABTool) {
  abstract val prop: String
  abstract val addmagic: String
  data class BoxA(val o:A, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = prop + tool.magic
  }
  data class BoxB(val o:B, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = tool.magic + prop
  }
}

and pass this when creating it from ABTool. That's just what inner really does, after all.

In this specific case the field happens to be unused in AB itself and so you can remove it from there and make it val in BoxA and BoxB.


问:
getting the columnname and sum the values in datatable c#
```<code>for (int i = 9; i < dt.Columns.Count; i++)
{
    string dtcolumn = dt.Columns[i].ColumnName.ToString();

    dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "  " + dtcolumn + " > 0"));
}
</code>```

<p>it is working when column values are not null. but sometimes throwing invalidcastexception  and displaying Object cannot be cast from DBNull to other types.how to avoid invalidcastexception </p>

答:
You should add a null check like what @sajeetharan has said but the null check he has mentioned may not work because this is ADO.NET. You should check for null using DBNull.

Something like this

```<code>for (int i = 9; i < dt.Columns.Count; i++)
{
    if(!DBNull.Value.Equals(dt.Columns[i].ColumnName))
    {
        string dtcolumn = dt.Columns[i].ColumnName.ToString();
        dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "  " + dtcolumn + " > 0"));
     }
 }
</code>```

Body:
for (int i = 9; i
 0"));
}

it is working when column values are not null. but sometimes throwing invalidcastexception  and displaying Object cannot be cast from DBNull to other types.how to avoid invalidcastexception

Body:
You should add a null check like what @sajeetharan has said but the null check he has mentioned may not work because this is ADO.NET. You should check for null using DBNull.

Something like this

for (int i = 9; i < dt.Columns.Count; i++)
{
    if(!DBNull.Value.Equals(dt.Columns[i].ColumnName))
    {
        string dtcolumn = dt.Columns[i].ColumnName.ToString();
        dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM( " + dtcolumn + " )", "  " + dtcolumn + " > 0"));
     }
 }


问:
How long do Drupal caches last?
Using the devel module I can see a lot of calls to cache_get() and cache_set(). After how long does a cached value need to be refreshed? Does the cache get invalidated every few minutes? </p>

答:
The module that is using cache_set sets the expiration in the call.  Some things have explicit durations, others have permanent or semi-permanent lifetimes, based on the situation.

Caches get explicitly cleared when you invoke the method through the admin interface (or drush), or otherwise through the use of drupal_flush_all_caches or cache_clear_all.

Lately, I have been using a hook_cron to clear certain cache tables each night.

EDIT to answer comment:

To see which cache, I usually put this in a separate script somewhere:

```<code>require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
header("Content-Type: text/plain; encoding=utf-8");
$user = user_load(1);
print "Modules implementing hook_cron:\n" . implode("\n", module_implements('cron'));

</code>```

To see expirations, examine the various cache tables in the database and look at the expire column.  Modules can set expirations on each individual call to cache_set, so it can vary entry by entry.

Title: How long do Drupal caches last?

Body:
The module that is using cache_set sets the expiration in the call.  Some things have explicit durations, others have permanent or semi-permanent lifetimes, based on the situation.

Caches get explicitly cleared when you invoke the method through the admin interface (or drush), or otherwise through the use of drupal_flush_all_caches or cache_clear_all.

Lately, I have been using a hook_cron to clear certain cache tables each night.

EDIT to answer comment:

To see which cache, I usually put this in a separate script somewhere:

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
header("Content-Type: text/plain; encoding=utf-8");
$user = user_load(1);
print "Modules implementing hook_cron:\n" . implode("\n", module_implements('cron'));

To see expirations, examine the various cache tables in the database and look at the expire column.  Modules can set expirations on each individual call to cache_set, so it can vary entry by entry.


问:
Python asyncio aiohttp request data encoding
I'm using python's aiohttp basic request module to make requests. My request is base64 encoded string and request body looks like:

```<code>body = {'request': 'eyJhYmMiOiJ4eXoifQ=='}
</code>```

Here is the code for sending request:

```<code>response = yield from request(method='POST', url=url, allow_redirects=False, headers=headers, data=body)
</code>```

The problem here is, this is getting received at the other end as:

```<code>{'request': 'eyJhYmMiOiJ4eXoifQ%3D%3D'}
</code>```

which I believe is the url-encoded version of my request body.

How can I avoid this and send request as it is?

答:
Use json parameter. An example from documentation:

```<code>async with aiohttp.ClientSession() as session:
    async with session.post(url, json={'test': 'object'})
</code>```

Body:
I'm using python's aiohttp basic request module to make requests. My request is base64 encoded string and request body looks like:

body = {'request': 'eyJhYmMiOiJ4eXoifQ=='}

Here is the code for sending request:

response = yield from request(method='POST', url=url, allow_redirects=False, headers=headers, data=body)

The problem here is, this is getting received at the other end as:

{'request': 'eyJhYmMiOiJ4eXoifQ%3D%3D'}

which I believe is the url-encoded version of my request body.

How can I avoid this and send request as it is?

Body:
Use json parameter. An example from documentation:

async with aiohttp.ClientSession() as session:
    async with session.post(url, json={'test': 'object'})


问:
Send TextBox text to user control
I have a question and I am unsure on how to proceed and am seeking some directions.

Here's my scenario, I have a Form1 with a panel1, I can load 3 different User Controls inside panel1 (UserControl1, UserControl2 and UserControl3) inside each one of these user controls I can open Form2 which has a few TextBoxes.

What I need is to whenever I hit a button on my Form2 all the TextBox text be sent to the User Control that opened Form2.

I'm not sure if my question here is clear, if anyone can help me with that I appreciate, thanks.

答:
It depends how you are creating the new form. Check this it contains the two scenarios.

Child Form:

```<code>public partial class Child : Form
    {
        public event NotifyParentHandler NotifyParent;
        public delegate void NotifyParentHandler(string textValue);

        public Child()
        {
            InitializeComponent();
        }

    private void btnNotify_Click(object sender, EventArgs e)
    {
        //assuming that you want to send the value when clicking a button
        if (this.NotifyParent != null)
        {
            this.NotifyParent(textBox1.Text);
        }
    }
}
</code>```

Parent Form

```<code>public partial class Parent : Form
    {
        private Child childForm;

        public Parent()
        {
            InitializeComponent();
        }

    private void btnOpenChildForm_Click(object sender, EventArgs e)
    {
        // Open the child form
        childForm = new Child();
        childForm.NotifyParent += childForm_NotificationTriggered;
        childForm.ShowDialog();
    }

    void childForm_NotificationTriggered(string textValuePassed)
    {
       //here you can do anything
    }
}
</code>```

Title: Send TextBox text to user control

Body:
It depends how you are creating the new form. Check this it contains the two scenarios.

Child Form:

public partial class Child : Form
    {
        public event NotifyParentHandler NotifyParent;
        public delegate void NotifyParentHandler(string textValue);

        public Child()
        {
            InitializeComponent();
        }

    private void btnNotify_Click(object sender, EventArgs e)
    {
        //assuming that you want to send the value when clicking a button
        if (this.NotifyParent != null)
        {
            this.NotifyParent(textBox1.Text);
        }
    }
}

Parent Form

public partial class Parent : Form
    {
        private Child childForm;

        public Parent()
        {
            InitializeComponent();
        }

    private void btnOpenChildForm_Click(object sender, EventArgs e)
    {
        // Open the child form
        childForm = new Child();
        childForm.NotifyParent += childForm_NotificationTriggered;
        childForm.ShowDialog();
    }

    void childForm_NotificationTriggered(string textValuePassed)
    {
       //here you can do anything
    }
}


问:
self.present doesn't work after POST request
I am trying to create a page with server connection.

A simple POST (email and password fields) and upon response, I need to show an alert to the user.

This line causes an exception:

```<code>self.present(alerta2, animated:true, completion:nil)
</code>```

Here is my code:

```<code>request.httpMethod = "POST" // Compose a query string
let postString = "email=" + userEmail + "&password=" + userPassword
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
    if error != nil {
        self.mostraAlerta(mensagem: "Ocorreu um erro!")
        return
    }

    // Let's convert response sent from a server side script to a NSDictionary object:
    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
        // print(json)
        if let parseJSON = json {
            let status = parseJSON["status"] as? String
            let msg = parseJSON["msg"] as? String
            let titulo = parseJSON["titulo"] as? String
            switch status {
            case "0"?:
                let alerta2 = UIAlertController(title: titulo, message: msg!, preferredStyle: .alert)
                let okAction = UIAlertAction(title: "OK", style: .default) { action in
                    self.dismiss(animated: true, completion: nil)
                }
                alerta2.addAction(okAction)
                self.present(alerta2, animated: true, completion: nil)
                // print("Status: OK")
                break
            case "1"?:
                print("Status: " + msg!)
                break
            default:
                print("Status: N/D")
                break
            }
            // print("Status: \(status)")
        }
    } catch {
        print(error)
    }
}
task.resume()
</code>```

The exception:

The error:

libsystem_kernel.dylib`__pthread_kill: 0x110b48d38

  <+0>: movl $0x2000148, %eax ; imm = 0x2000148 0x110b48d3d

  <+5>: movq %rcx, %r10 0x110b48d40

  <+8>: syscall -> 0x110b48d42

  <+10>: jae 0x110b48d4c ; <+20> 0x110b48d44

  <+12>: movq %rax, %rdi 0x110b48d47

  <+15>: jmp 0x110b41caf ; cerror_nocancel 0x110b48d4c

  <+20>: retq 0x110b48d4d

  <+21>: nop 0x110b48d4e

  <+22>: nop 0x110b48d4f

  <+23>: nop

答:
I just got the error and the fix.

The error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue
  waitUntilAllTasksAreFinished] may only be called from the main thread.

The solution:

```<code>OperationQueue.main.addOperation {
    self.present(alerta2, animated:true, completion:nil)
}
</code>```

Body:
I am trying to create a page with server connection.

A simple POST (email and password fields) and upon response, I need to show an alert to the user.

This line causes an exception:

self.present(alerta2, animated:true, completion:nil)

Here is my code:

request.httpMethod = "POST" // Compose a query string
let postString = "email=" + userEmail + "&password=" + userPassword
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
    if error != nil {
        self.mostraAlerta(mensagem: "Ocorreu um erro!")
        return
    }

    // Let's convert response sent from a server side script to a NSDictionary object:
    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
        // print(json)
        if let parseJSON = json {
            let status = parseJSON["status"] as? String
            let msg = parseJSON["msg"] as? String
            let titulo = parseJSON["titulo"] as? String
            switch status {
            case "0"?:
                let alerta2 = UIAlertController(title: titulo, message: msg!, preferredStyle: .alert)
                let okAction = UIAlertAction(title: "OK", style: .default) { action in
                    self.dismiss(animated: true, completion: nil)
                }
                alerta2.addAction(okAction)
                self.present(alerta2, animated: true, completion: nil)
                // print("Status: OK")
                break
            case "1"?:
                print("Status: " + msg!)
                break
            default:
                print("Status: N/D")
                break
            }
            // print("Status: \(status)")
        }
    } catch {
        print(error)
    }
}
task.resume()

The exception:

The error:

libsystem_kernel.dylib`__pthread_kill: 0x110b48d38

  <+0>: movl $0x2000148, %eax ; imm = 0x2000148 0x110b48d3d

  <+5>: movq %rcx, %r10 0x110b48d40

  <+8>: syscall -> 0x110b48d42

  <+10>: jae 0x110b48d4c ; <+20> 0x110b48d44

  <+12>: movq %rax, %rdi 0x110b48d47

  <+15>: jmp 0x110b41caf ; cerror_nocancel 0x110b48d4c

  <+20>: retq 0x110b48d4d

  <+21>: nop 0x110b48d4e

  <+22>: nop 0x110b48d4f

  <+23>: nop

Body:
I just got the error and the fix.

The error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue
  waitUntilAllTasksAreFinished] may only be called from the main thread.

The solution:

OperationQueue.main.addOperation {
    self.present(alerta2, animated:true, completion:nil)
}


问:
InStr() functionality
Perhaps I'm misunderstanding how the AutoHotKey function works.  Here's some test code:

```<code>pos = InStr(123abc789, abc)
MsgBox, abc is at pos "%pos%"
Exit
</code>```

The MsgBox reads:

abc is at pos "InStr(123abc789, abc)"

I'm expecting the value of pos to be 4.

Now, the AutoHotKey help file states about InStr():

```<code>InStr(Haystack, Needle [, CaseSensitive = false, StartingPos = 1, Occurrence = 1]):
</code>```

Returns the position of an occurrence of the string Needle in the string Haystack... For example, the position of "abc" in "123abc789" is always 4.

What's up??

答:
Also:

```<code>MsgBox, abc is at pos "%pos%"
</code>```

can not work, variables are required to be between percentage signs, no quotes.

This will work:

```<code>MsgBox, abc is at pos %pos%
</code>```

Title: InStr() functionality

Body:
Perhaps I'm misunderstanding how the AutoHotKey function works.  Here's some test code:

pos = InStr(123abc789, abc)
MsgBox, abc is at pos "%pos%"
Exit

The MsgBox reads:

abc is at pos "InStr(123abc789, abc)"

I'm expecting the value of pos to be 4.

Now, the AutoHotKey help file states about InStr():

InStr(Haystack, Needle [, CaseSensitive = false, StartingPos = 1, Occurrence = 1]):

Returns the position of an occurrence of the string Needle in the string Haystack... For example, the position of "abc" in "123abc789" is always 4.

What's up??

Body:
Also:

MsgBox, abc is at pos "%pos%"

can not work, variables are required to be between percentage signs, no quotes.

This will work:

MsgBox, abc is at pos %pos%


问:
Identify frequency of elements in each key in python
I have a list of dictionary as follows.

```<code>mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]},
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]},
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]
</code>```

Now, I want to calculate the codes count for each key in the dictionary. For example "0": ["code1", "code5"] and "0": ["code8", "code5"] should give: mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}

So, for the above mylist the output should be;

```<code>mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}
</code>```

Please help me to do this using python!

答:
This might be the solution</p>

```<code>final_result = []
for i in mylist:
    current_list = mylist[i]
    d = {}
    for key in current_list:
        try:
            d[m]+=1
        except KeyError as e:
            d.update({m: 1})
        final_result.append(d)

for i in final_result:
    print(i)
</code>```

Body:
I have a list of dictionary as follows.

mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]},
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]},
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]

Now, I want to calculate the codes count for each key in the dictionary. For example "0": ["code1", "code5"] and "0": ["code8", "code5"] should give: mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}

So, for the above mylist the output should be;

mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}

Please help me to do this using python!

Body:
This might be the solution

final_result = []
for i in mylist:
    current_list = mylist[i]
    d = {}
    for key in current_list:
        try:
            d[m]+=1
        except KeyError as e:
            d.update({m: 1})
        final_result.append(d)

for i in final_result:
    print(i)


问:
Trouble running all migration files. What else can one do?
I have a very large amount of migration files that need to run and some of them apparently are outdated. For example:

This fails:

```<code>  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      ...
</code>```

With this error:

```<code>-- create_table(:users)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition
</code>```

I assume because Devise was updated at the time of writing this.

What else can I do?

It turns out there's a schema file. Here's part of it:

```<code>ActiveRecord::Schema.define(version: 20160221211458) do

  create_table "activities", force: true do |t|
    t.integer  "user_id",                  null: false
    t.string   "target_type", default: "", null: false
    t.integer  "target_id",                null: false
    t.string   "action",      default: "", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "activities", ["target_id"], name: "index_activities_on_target_id_and_target_type", using: :btree
  add_index "activities", ["user_id"], name: "index_activities_on_user_id", using: :btree

  create_table "addresses", force: true do |t|
  ...
</code>```

What's the difference between doing bundle exec rake db:schema:load vs trying to run the migrations. Is there a difference between the two?

Also, this database is a mysql database:

```<code># SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
  adapter: mysql2
  database: arthouse_development
  username: root
  password:
  host: localhost
  port: 3306
  #socket: /tmp/mysql.sock
</code>```

How do I see this database after running bundle exec rake db:schema:load

答:
I also ran into this issue on my existing app as I tried to deploy to a new staging server.

Ended up being that the Devise gem had been updated to 2.1 and I hadn't fixed the migration to work correctly with the new version.

Be sure to read through their migration to 2.1 doc on their wiki -- https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.1

Also, be sure to read through the doc for how to correctly adjust existing migrations -- https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0-migration-schema-style

Body:
I have a very large amount of migration files that need to run and some of them apparently are outdated. For example:

This fails:

  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      ...

With this error:

-- create_table(:users)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition

I assume because Devise was updated at the time of writing this.

What else can I do?

It turns out there's a schema file. Here's part of it:

ActiveRecord::Schema.define(version: 20160221211458) do

  create_table "activities", force: true do |t|
    t.integer  "user_id",                  null: false
    t.string   "target_type", default: "", null: false
    t.integer  "target_id",                null: false
    t.string   "action",      default: "", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "activities", ["target_id"], name: "index_activities_on_target_id_and_target_type", using: :btree
  add_index "activities", ["user_id"], name: "index_activities_on_user_id", using: :btree

  create_table "addresses", force: true do |t|
  ...

What's the difference between doing bundle exec rake db:schema:load vs trying to run the migrations. Is there a difference between the two?

Also, this database is a mysql database:

# SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
  adapter: mysql2
  database: arthouse_development
  username: root
  password:
  host: localhost
  port: 3306
  #socket: /tmp/mysql.sock

How do I see this database after running bundle exec rake db:schema:load


问:
var_dump() in Scala
Is there any convenient way to dump all members of a specified object in Scala,

like var_dump(), PHP function?

答:
As mentioned in "How to Dump/Inspect Object or Variable in Java" (yes, I know, the question is about Scala):

Scala (console) has a very useful feature to inspect or dump variables / object values :

```<code>scala> def b = Map("name" -> "Yudha", "age" -> 27)
b: scala.collection.immutable.Map[java.lang.String,Any]

scala> b
res1: scala.collection.immutable.Map[java.lang.String,Any] = Map((name,Yudha), (age,27))
</code>```

But if you want more details, you can give REPL Scala Utils a try, in order to get a "Easier object inspection in the Scala REPL"

So I've written a utility for use on the Scala REPL that will print out all of the "attributes" of an object.

(Note: "I" being here: Erik Engbrecht, also on BitBucket)

Here's some sample usage:

```<code>scala> import replutils._
import replutils._

scala> case class Test(a: CharSequence, b: Int)
defined class Test

scala> val t = Test("hello", 1)
t: Test = Test(hello,1)

scala> printAttrValues(t)
hashCode: int = -229308731
b: int = 1
a: CharSequence (String) = hello
productArity: int = 2
getClass: Class = class line0$object$$iw$$iw$Test
</code>```

That looks fairly anti-climatic, but after spending hours typing objName to see what's there, and poking at methods, it seems like a miracle.

  Also, one neat feature of it is that if the class of the object returned is different from the class declared on the method, it prints both the declared class and the actual returned class.

Title: var_dump() in Scala

Body:
As mentioned in "How to Dump/Inspect Object or Variable in Java" (yes, I know, the question is about Scala):

Scala (console) has a very useful feature to inspect or dump variables / object values :

scala> def b = Map("name" -> "Yudha", "age" -> 27)
b: scala.collection.immutable.Map[java.lang.String,Any]

scala> b
res1: scala.collection.immutable.Map[java.lang.String,Any] = Map((name,Yudha), (age,27))

But if you want more details, you can give REPL Scala Utils a try, in order to get a "Easier object inspection in the Scala REPL"

So I've written a utility for use on the Scala REPL that will print out all of the "attributes" of an object.

(Note: "I" being here: Erik Engbrecht, also on BitBucket)

Here's some sample usage:

scala> import replutils._
import replutils._

scala> case class Test(a: CharSequence, b: Int)
defined class Test

scala> val t = Test("hello", 1)
t: Test = Test(hello,1)

scala> printAttrValues(t)
hashCode: int = -229308731
b: int = 1
a: CharSequence (String) = hello
productArity: int = 2
getClass: Class = class line0$object$$iw$$iw$Test

That looks fairly anti-climatic, but after spending hours typing objName to see what's there, and poking at methods, it seems like a miracle.

  Also, one neat feature of it is that if the class of the object returned is different from the class declared on the method, it prints both the declared class and the actual returned class.


问:
PHP max_execution_timeout is not evaluated
I am running PHP 7.0.22 and have a problem while trying to set the max_execution_timeout option inside a PHP script. max_execution_timeout is set correctly but it is not taken into consideration by PHP:

```<code><?php

...
$iniset = ini_set('max_execution_time', 120 * 60); // 2 hours
$iniget = ini_get('max_execution_time');
var_dump($iniset, $iniget);
...
</code>```

And here is the output:

string '30' (length=2) string '7200' (length=4)

( ! ) Fatal error: Maximum execution time of 120 seconds exceeded in
  file.php on line 425

As you can see, the limit is increased to 7200 seconds, but then the script execution breaks after 120 seconds, as shown by the fatal error.

How is that possible?

P.S.: I have Xdebug installed, maybe it can cause this issue.

Thank you for your attention.

答:
As you mention you have safe mode disable, and ini_set() is not working.
The only workaround is to changing the time limit in the php.ini.

Body:
I am running PHP 7.0.22 and have a problem while trying to set the max_execution_timeout option inside a PHP script. max_execution_timeout is set correctly but it is not taken into consideration by PHP:

<?php

...
$iniset = ini_set('max_execution_time', 120 * 60); // 2 hours
$iniget = ini_get('max_execution_time');
var_dump($iniset, $iniget);
...

And here is the output:

string '30' (length=2) string '7200' (length=4)

( ! ) Fatal error: Maximum execution time of 120 seconds exceeded in
  file.php on line 425

As you can see, the limit is increased to 7200 seconds, but then the script execution breaks after 120 seconds, as shown by the fatal error.

How is that possible?

P.S.: I have Xdebug installed, maybe it can cause this issue.

Thank you for your attention.


问:
SQL- I need script text file need to know which tables and views and stored procedures having that script
I am having script text file that inside having

Create procedure

Create table

alter table

alter procedure

alter view

create view etc..

I need to know views, SPs, tables names and its roles (create or alter) when I run the script.

Example following are text file.

and the result should be following

proc, alter, bal.vendor
table, select, manager
table, create, employee
table, alter, persons

答:
All those are called Objects, so the only thing may come up to your mind is to use sys.all_objects view which can be found in:

YourDatabase -> Views -> SystemViews

All those objects has a type:

```<code>U  -> USER_TABLE
IF -> SQL_INLINE_TABLE_VALUED_FUNCTION
P  ->  SQL_STORED_PROCEDURE
TR ->  SQL_TRIGGER
V  ->   VIEW
...etc
</code>```

So, you can query this View to get the results you want as:

```<code>SELECT object_id,
       name,
       type,
       type_desc,
       CASE WHEN create_date = modify_date THEN 'Created' ELSE 'Altered' END AS state,
       create_date,
       modify_date
FROM sys.all_objects
WHERE type IN ('U', 'P', 'V'); --Optional you can remove it if you wan all types of objects
</code>```

Body:
All those are called Objects, so the only thing may come up to your mind is to use sys.all_objects view which can be found in:

YourDatabase -> Views -> SystemViews

All those objects has a type:

U  -> USER_TABLE
IF -> SQL_INLINE_TABLE_VALUED_FUNCTION
P  ->  SQL_STORED_PROCEDURE
TR ->  SQL_TRIGGER
V  ->   VIEW
...etc

So, you can query this View to get the results you want as:

SELECT object_id,
       name,
       type,
       type_desc,
       CASE WHEN create_date = modify_date THEN 'Created' ELSE 'Altered' END AS state,
       create_date,
       modify_date
FROM sys.all_objects
WHERE type IN ('U', 'P', 'V'); --Optional you can remove it if you wan all types of objects


问:
How to bypass "Visual Studio Just-In-Time Debugger" prompt
Visual Studio Just-In-Time Debugger prompts to select "Possible Debuggers",

only "New instance of Microsoft Visual Studio 2010" is available,

I tick "Set the currently selected debugger as the default", click "Yes",

but, the dialog keeps being displayed every time.

I am debugging JavaScript in IE8 on Windows 7 x64.

How do I bypass this prompt?

These registry values do not solve the problem:

[HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug]

"Auto"="1"

[HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug]

"Auto"="1"

答:
I actually just did this the other day.

In the following registry key:

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Messenger\Client]

Create 2 new DWORDs (Right-click --> New --> DWORD Value)

PreventAutoRun and PreventRun

Set both values to 1


问:
Automatically check or uncheck RecyclerView checkboxes with boolean values
I need to check my recyclerview checkboxes automatically based on boolean values coming from POJO class. below is my class details.

HealthStatusCheck.java:

```<code>public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}
</code>```

Above is my POJO class. Now I need to set the recyclerview checkboxes based on the boolean values assigned to the POJO class. In my recyclerview adapter, this POJO class is available.

Here is my adapter code:

```<code>public class DonorHealthStatusAdapter extends RecyclerView.Adapter<DonorHealthStatusAdapter.HealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> questionares;
private HealthStatusCheck healthStatusCheck;

public DonorHealthStatusAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> questionares,
                                HealthStatusCheck healthStatusCheck) {
    this.context = context;
    this.questionares = questionares;
    this.healthStatusCheck = healthStatusCheck;
}

@Override
public HealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_donor_health_info, parent, false);
    return new HealthViewHolder(view);
}

@Override
public void onBindViewHolder(final HealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare questionare = questionares.get(position);
    holder.tv_questions.setText(questionare.getQuestions());

    holder.cbYes.setOnCheckedChangeListener(null);
    holder.cbNo.setOnCheckedChangeListener(null);

}

@Override
public int getItemCount() {
    return questionares.size();
}

public class HealthViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;
    TextView tv_questions;
    CheckBox cbYes, cbNo;

    public HealthViewHolder(View itemView) {
        super(itemView);
        cardView = itemView.findViewById(R.id.card_view_health_status_rv);
        tv_questions = itemView.findViewById(R.id.tv_eligibility_question);
        cbYes = itemView.findViewById(R.id.checkBoxYes);
        cbNo = itemView.findViewById(R.id.checkBoxNo);
    }

}

}
</code>```

答:
Got your point.

Two options -

1) Create another ArrayList<HealthStatusCheck> answers and populate rows according to it.

2) Make a change in webserivce and get the answer of Question within the object of Question in Json format.

Body:
I need to check my recyclerview checkboxes automatically based on boolean values coming from POJO class. below is my class details.

HealthStatusCheck.java:

public class HealthStatusCheck {
private int id;
private int donorID;
private boolean q1;
private boolean q2;
private boolean q3;
private boolean q4;
private boolean q5;
private boolean q6;
private boolean q7;
private boolean q8;
private boolean q9;
private boolean q10;
private boolean q11;
private boolean q12;
private boolean q13;
private boolean q14;
private boolean q15;
private boolean q16;
private boolean q17;
private boolean q18;
private boolean q19;
private boolean q20;

public HealthStatusCheck() {}

public HealthStatusCheck(int id, int donorID, boolean q1, boolean q2, boolean q3, boolean q4, boolean q5, boolean q6,
                         boolean q7, boolean q8, boolean q9, boolean q10, boolean q11, boolean q12, boolean q13,
                         boolean q14, boolean q15, boolean q16, boolean q17, boolean q18, boolean q19, boolean q20) {
    this.id = id;
    this.donorID = donorID;
    this.q1 = q1;
    this.q2 = q2;
    this.q3 = q3;
    this.q4 = q4;
    this.q5 = q5;
    this.q6 = q6;
    this.q7 = q7;
    this.q8 = q8;
    this.q9 = q9;
    this.q10 = q10;
    this.q11 = q11;
    this.q12 = q12;
    this.q13 = q13;
    this.q14 = q14;
    this.q15 = q15;
    this.q16 = q16;
    this.q17 = q17;
    this.q18 = q18;
    this.q19 = q19;
    this.q20 = q20;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getDonorID() {
    return donorID;
}

public void setDonorID(int donorID) {
    this.donorID = donorID;
}

public boolean isQ1() {
    return q1;
}

public void setQ1(boolean q1) {
    this.q1 = q1;
}

public boolean isQ2() {
    return q2;
}

public void setQ2(boolean q2) {
    this.q2 = q2;
}

public boolean isQ3() {
    return q3;
}

public void setQ3(boolean q3) {
    this.q3 = q3;
}

public boolean isQ4() {
    return q4;
}

public void setQ4(boolean q4) {
    this.q4 = q4;
}

public boolean isQ5() {
    return q5;
}

public void setQ5(boolean q5) {
    this.q5 = q5;
}

public boolean isQ6() {
    return q6;
}

public void setQ6(boolean q6) {
    this.q6 = q6;
}

public boolean isQ7() {
    return q7;
}

public void setQ7(boolean q7) {
    this.q7 = q7;
}

public boolean isQ8() {
    return q8;
}

public void setQ8(boolean q8) {
    this.q8 = q8;
}

public boolean isQ9() {
    return q9;
}

public void setQ9(boolean q9) {
    this.q9 = q9;
}

public boolean isQ10() {
    return q10;
}

public void setQ10(boolean q10) {
    this.q10 = q10;
}

public boolean isQ11() {
    return q11;
}

public void setQ11(boolean q11) {
    this.q11 = q11;
}

public boolean isQ12() {
    return q12;
}

public void setQ12(boolean q12) {
    this.q12 = q12;
}

public boolean isQ13() {
    return q13;
}

public void setQ13(boolean q13) {
    this.q13 = q13;
}

public boolean isQ14() {
    return q14;
}

public void setQ14(boolean q14) {
    this.q14 = q14;
}

public boolean isQ15() {
    return q15;
}

public void setQ15(boolean q15) {
    this.q15 = q15;
}

public boolean isQ16() {
    return q16;
}

public void setQ16(boolean q16) {
    this.q16 = q16;
}

public boolean isQ17() {
    return q17;
}

public void setQ17(boolean q17) {
    this.q17 = q17;
}

public boolean isQ18() {
    return q18;
}

public void setQ18(boolean q18) {
    this.q18 = q18;
}

public boolean isQ19() {
    return q19;
}

public void setQ19(boolean q19) {
    this.q19 = q19;
}

public boolean isQ20() {
    return q20;
}

public void setQ20(boolean q20) {
    this.q20 = q20;
}
}

Above is my POJO class. Now I need to set the recyclerview checkboxes based on the boolean values assigned to the POJO class. In my recyclerview adapter, this POJO class is available.

Here is my adapter code:

public class DonorHealthStatusAdapter extends RecyclerView.Adapter<DonorHealthStatusAdapter.HealthViewHolder> {

private Context context;
private ArrayList<DonorHealthStatusQuestionare> questionares;
private HealthStatusCheck healthStatusCheck;

public DonorHealthStatusAdapter(Context context, ArrayList<DonorHealthStatusQuestionare> questionares,
                                HealthStatusCheck healthStatusCheck) {
    this.context = context;
    this.questionares = questionares;
    this.healthStatusCheck = healthStatusCheck;
}

@Override
public HealthViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_donor_health_info, parent, false);
    return new HealthViewHolder(view);
}

@Override
public void onBindViewHolder(final HealthViewHolder holder, int position) {

    DonorHealthStatusQuestionare questionare = questionares.get(position);
    holder.tv_questions.setText(questionare.getQuestions());

    holder.cbYes.setOnCheckedChangeListener(null);
    holder.cbNo.setOnCheckedChangeListener(null);

}

@Override
public int getItemCount() {
    return questionares.size();
}

public class HealthViewHolder extends RecyclerView.ViewHolder {

    CardView cardView;
    TextView tv_questions;
    CheckBox cbYes, cbNo;

    public HealthViewHolder(View itemView) {
        super(itemView);
        cardView = itemView.findViewById(R.id.card_view_health_status_rv);
        tv_questions = itemView.findViewById(R.id.tv_eligibility_question);
        cbYes = itemView.findViewById(R.id.checkBoxYes);
        cbNo = itemView.findViewById(R.id.checkBoxNo);
    }

}

}