text:
Q: Magento2.1.9 : Out of stock product Backorder not working? I have to used Magento2.1.9 when I add out of stock product to cart it is not working and am getting error as this product out of stock I need backorder working properly for out of stock product and I find, this is a bug in magento2.1.9 and applied patch after resolve issue but i am not getting patch file . So Ihave tried the other way override this file and  add code below we are using.

\Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\QuantityValidator.php

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\CatalogInventory\Model\Quote\Item\QuantityValidator" type="XXXX\XXXX\Model\Quote\Item\QuantityValidator" />
</config>

this is my code used QuantityValidator.php
    <?php
    namespace XXXXX\XXXXX\Model\Quote\Item;

    use Magento\CatalogInventory\Model\Stock;

    /**
     * Quantity validation.
     */
    class QuantityValidator extends \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator
    {
         protected $optionInitializer;

        /**
         * @var QuantityValidator\Initializer\StockItem
         */
        protected $stockItemInitializer;

        /**
         * Stock registry.
         *
         * @var \Magento\CatalogInventory\Api\StockRegistryInterface
         */
        protected $stockRegistry;

        /**
         * Stock state.
         *
         * @var \Magento\CatalogInventory\Api\StockStateInterface
         */
        protected $stockState;

        /**
         * @param QuantityValidator\Initializer\Option $optionInitializer
         * @param QuantityValidator\Initializer\StockItem $stockItemInitializer
         * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
         * @param \Magento\CatalogInventory\Api\StockStateInterface $stockState
         */
        public function __construct(
            QuantityValidator\Initializer\Option $optionInitializer,
            QuantityValidator\Initializer\StockItem $stockItemInitializer,
            \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
            \Magento\CatalogInventory\Api\StockStateInterface $stockState
        ) {

$this->optionInitializer = $optionInitializer;
        $this->stockItemInitializer = $stockItemInitializer;
        $this->stockRegistry = $stockRegistry;
        $this->stockState = $stockState;
    }

    /**
     * Check product inventory data when quote item quantity declaring
     *
     * @param \Magento\Framework\Event\Observer $observer
     *
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function validate(\Magento\Framework\Event\Observer $observer)
    {
        /* @var $quoteItem \Magento\Quote\Model\Quote\Item */
        $quoteItem = $observer->getEvent()->getItem();
        if (!$quoteItem ||
            !$quoteItem->getProductId() ||
            !$quoteItem->getQuote() ||
            $quoteItem->getQuote()->getIsSuperMode()
        ) {
            return;
        }
        $product = $quoteItem->getProduct();
        $qty = $quoteItem->getQty();

        /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
        $stockItem = $this->stockRegistry->getStockItem(
            $quoteItem->getProduct()->getId(),
            $quoteItem->getProduct()->getStore()->getWebsiteId()
        );

        if (!$stockItem instanceof \Magento\CatalogInventory\Api\Data\StockItemInterface) {
            throw new \Magento\Framework\Exception\LocalizedException(__('The stock item for Product is not valid.'));
        }

        /** @var \Magento\CatalogInventory\Api\Data\StockStatusInterface $stockStatus */
        $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

        /** @var \Magento\CatalogInventory\Api\Data\StockStatusInterface|bool $parentStockStatus */
        $parentStockStatus = false;

        /**
         * Check if product in stock. For composite products check base (parent) item stock status
         */
        if ($quoteItem->getParentItem()) {
            $product = $quoteItem->getParentItem()->getProduct();
            $parentStockStatus = $this->stockRegistry->getStockStatus(
                $product->getId(),
                $product->getStore()->getWebsiteId()
            );
        }

        if ($stockStatus) {
            if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
               || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
             ) {
                $quoteItem->addErrorInfo(
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    __('This product is out of stock.')
                );
                $quoteItem->getQuote()->addErrorInfo(
                    'stock',
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    __('Some of the products are out of stock.')
                );
                return;
            } else {
                // Delete error from item and its quote, if it was set due to item out of stock
                $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY);
            }
        }
    }
}
?>

after override this file in our module getting this
ReflectionException
  Class XXXX\XXXX\Model\Quote\Item\QuantityValidator\Initializer\Option does not exist

if anyone know reply me

A: Problem in your __construct. Try the following way:
public function __construct(
    \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option $optionInitializer,
    \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem $stockItemInitializer,
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
    \Magento\CatalogInventory\Api\StockStateInterface $stockState
) {

A: It's working code here
add in your custom module di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\CatalogInventory\Model\Quote\Item\QuantityValidator" type="XXXXX\XXXXXX\Model\Quote\Item\QuantityValidator" />
</config>

add in you custom module inside  model file app/code/Namespace/Modulname/Model/Quote/Item/QuantityValidator.php
<?php
namespace XXXXXX\XXXXXX\Model\Quote\Item;

use Magento\CatalogInventory\Model\Stock;

/**
 * Quantity validation.
 */
class QuantityValidator extends \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator
{
     protected $optionInitializer;

    /**
     * @var QuantityValidator\Initializer\StockItem
     */
    protected $stockItemInitializer;

    /**
     * Stock registry.
     *
     * @var \Magento\CatalogInventory\Api\StockRegistryInterface
     */
    protected $stockRegistry;

    /**
     * Stock state.
     *
     * @var \Magento\CatalogInventory\Api\StockStateInterface
     */
    protected $stockState;

    /**
     * @param QuantityValidator\Initializer\Option $optionInitializer
     * @param QuantityValidator\Initializer\StockItem $stockItemInitializer
     * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
     * @param \Magento\CatalogInventory\Api\StockStateInterface $stockState
     */
    public function __construct(
    \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\Option $optionInitializer,
    \Magento\CatalogInventory\Model\Quote\Item\QuantityValidator\Initializer\StockItem $stockItemInitializer,
    \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
    \Magento\CatalogInventory\Api\StockStateInterface $stockState
) {
        $this->optionInitializer = $optionInitializer;
        $this->stockItemInitializer = $stockItemInitializer;
        $this->stockRegistry = $stockRegistry;
        $this->stockState = $stockState;
    }

    /**
     * Check product inventory data when quote item quantity declaring
     *
     * @param \Magento\Framework\Event\Observer $observer
     *
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function validate(\Magento\Framework\Event\Observer $observer)
    {
        /* @var $quoteItem \Magento\Quote\Model\Quote\Item */
        $quoteItem = $observer->getEvent()->getItem();
        if (!$quoteItem ||
            !$quoteItem->getProductId() ||
            !$quoteItem->getQuote() ||
            $quoteItem->getQuote()->getIsSuperMode()
        ) {
            return;
        }
        $product = $quoteItem->getProduct();
        $qty = $quoteItem->getQty();

        /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
        $stockItem = $this->stockRegistry->getStockItem(
            $quoteItem->getProduct()->getId(),
            $quoteItem->getProduct()->getStore()->getWebsiteId()
        );

        if (!$stockItem instanceof \Magento\CatalogInventory\Api\Data\StockItemInterface) {
            throw new \Magento\Framework\Exception\LocalizedException(__('The stock item for Product is not valid.'));
        }

        /** @var \Magento\CatalogInventory\Api\Data\StockStatusInterface $stockStatus */
        $stockStatus = $this->stockRegistry->getStockStatus($product->getId(), $product->getStore()->getWebsiteId());

        /** @var \Magento\CatalogInventory\Api\Data\StockStatusInterface|bool $parentStockStatus */
        $parentStockStatus = false;

        /**
         * Check if product in stock. For composite products check base (parent) item stock status
         */
        if ($quoteItem->getParentItem()) {
            $product = $quoteItem->getParentItem()->getProduct();
            $parentStockStatus = $this->stockRegistry->getStockStatus(
                $product->getId(),
                $product->getStore()->getWebsiteId()
            );
        }

        if ($stockStatus) {
            /*if ($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
                || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
            )*/
            if (($stockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK
               || $parentStockStatus && $parentStockStatus->getStockStatus() == Stock::STOCK_OUT_OF_STOCK) && !$stockItem->getBackorders()
             )
             {
                $quoteItem->addErrorInfo(
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    __('This product is out of stock.')
                );
                $quoteItem->getQuote()->addErrorInfo(
                    'stock',
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    __('Some of the products are out of stock.')
                );
                return;
            } else {
                // Delete error from item and its quote, if it was set due to item out of stock
                $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY);
            }
        }

        /**
         * Check item for options
         */
        if (($options = $quoteItem->getQtyOptions()) && $qty > 0) {
            $qty = $product->getTypeInstance()->prepareQuoteItemQty($qty, $product);
            $quoteItem->setData('qty', $qty);
            if ($stockStatus) {
                $result = $this->stockState->checkQtyIncrements(
                    $product->getId(),
                    $qty,
                    $product->getStore()->getWebsiteId()
                );
                if ($result->getHasError()) {
                    $quoteItem->addErrorInfo(
                        'cataloginventory',
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS,
                        $result->getMessage()
                    );

                    $quoteItem->getQuote()->addErrorInfo(
                        $result->getQuoteMessageIndex(),
                        'cataloginventory',
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS,
                        $result->getQuoteMessage()
                    );
                } else {
                    // Delete error from item and its quote, if it was set due to qty problems
                    $this->_removeErrorsFromQuoteAndItem(
                        $quoteItem,
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS
                    );
                }
            }

            foreach ($options as $option) {
                $result = $this->optionInitializer->initialize($option, $quoteItem, $qty);
                if ($result->getHasError()) {
                    $option->setHasError(true);

                    $quoteItem->addErrorInfo(
                        'cataloginventory',
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                        $result->getMessage()
                    );

                    $quoteItem->getQuote()->addErrorInfo(
                        $result->getQuoteMessageIndex(),
                        'cataloginventory',
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                        $result->getQuoteMessage()
                    );
                } else {
                    // Delete error from item and its quote, if it was set due to qty lack
                    $this->_removeErrorsFromQuoteAndItem(
                        $quoteItem,
                        \Magento\CatalogInventory\Helper\Data::ERROR_QTY
                    );
                }
            }
        } else {
            $result = $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty);
            if ($result->getHasError()) {
                $quoteItem->addErrorInfo(
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    $result->getMessage()
                );

                $quoteItem->getQuote()->addErrorInfo(
                    $result->getQuoteMessageIndex(),
                    'cataloginventory',
                    \Magento\CatalogInventory\Helper\Data::ERROR_QTY,
                    $result->getQuoteMessage()
                );
            } else {
                // Delete error from item and its quote, if it was set due to qty lack
                $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY);
            }
        }
    }

    /**
     * Removes error statuses from quote and item, set by this observer
     *
     * @param \Magento\Quote\Model\Quote\Item $item
     * @param int $code
     * @return void
     */
    protected function _removeErrorsFromQuoteAndItem($item, $code)
    {
        if ($item->getHasError()) {
            $params = ['origin' => 'cataloginventory', 'code' => $code];
            $item->removeErrorInfosByParams($params);
        }

        $quote = $item->getQuote();
        $quoteItems = $quote->getItemsCollection();
        $canRemoveErrorFromQuote = true;

        foreach ($quoteItems as $quoteItem) {
            if ($quoteItem->getItemId() == $item->getItemId()) {
                continue;
            }

            $errorInfos = $quoteItem->getErrorInfos();
            foreach ($errorInfos as $errorInfo) {
                if ($errorInfo['code'] == $code) {
                    $canRemoveErrorFromQuote = false;
                    break;
                }
            }

            if (!$canRemoveErrorFromQuote) {
                break;
            }
        }

        if ($quote->getHasError() && $canRemoveErrorFromQuote) {
            $params = ['origin' => 'cataloginventory', 'code' => $code];
            $quote->removeErrorInfosByParams(null, $params);
        }
    }
}
?>


text:
Q: Facing issue in lightning component managed package after upgrade where property name removed I'm facing the issue. I have the lightning component managed package which includes 2 design properties on page builder.

*

*first property name title (string type)

*2nd property name help (String type)

It's work fine I have created the managed package version 1.0 and test in my test org. I add the component on the home page and I see it its work perfectly.
Problem:
Now I remove the 2nd property name help (String type) from my component and upload the package create the new version v2.0  and send push upgrade to my test org where I have installed version1.0 after successfully upgrade I notice my component is not showing on the home page.
Workaround:
if I edit the page layout and save it again then the component shown.
but I don't want to edit all pages. anybody experience this issue before and how to deal with this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get list of all possible command line arguments for an exe Is there anyway for me to get the list of available command line arguments for an exe? I need to create a Powershell script that start the Relius Agent Manager program, but this program requires database login and password info to load.
I can obtain the login/pass info, but I need to know the names of the argument I'll need to pass them through.
It doesn't matter if I use Powershell or C# to retrieve the list of arguments, I just need to know their darn names.
I read up on the Process class in C# but I don't see anything that will actually list the available arguments, only how to list what was passed when a process was started.

A: There is no way to query the supported command line arguments. Try running the program from a command prompt with no arguments, with an invalid argument, with /h, /?, -h, --help and similar arguments to see if one of these prompts the program to output a list of allowed arguments.

A: Thanks for all of your help. I was able to solve it by having someone start it manually and then log in, and then I checked this list of all running processes with this command:
"WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid"
I was then able to find exactly what was passed when it was run from the file that command generated and execute that command in PowerShell using something like:
$exp = "&'C:\path\to\the\exe.exe' /param1 /param2 /param3"
invoke-expression $exp

A: search for universal silent switch finder. it is actually possible to do programmatically but requires deep diving into binary executable.  if interested check http://code.google.com/p/pefile/wiki/PEiDSignatures


text:
Q: Initialize only first argument of c++11 tuple Minimal working example:
#include <tuple>

struct example
{
    example(int, char) {}
};

int main()
{
    std::tuple<example, int, double>
        my_tuple(example(0, 'x'), 42, .0);
    // std::tuple t = make_my_tuple(0, 'x');
    return 0;
}

This works.
Is there a more elegant way to initialize only the first member, like I sketched in the comment? One which only takes the arguments to construct the first tuple member and does not initialize the others?
The reason I ask? I am just interested in the semantics of the language.

A: You say that giving values for the other two members is not necessary - are you worried about performance? Or that there may be no suitable value for these members?
If it's the latter, you could have your tuple hold boost::optionals. e.g.
#include <tuple>
#include <boost/optional.hpp>

using namespace boost;

struct example
{
    example(int, char) {}
};

typedef std::tuple<example, optional<int>, optional<double>> MyTuple;

int main()
{
   MyTuple my_tuple(example(0, 'x'), optional<int>(), optional<double>());
   return 0;
}

You now semantically have the int and float "uninitialised", and can query their value as such.
To make this more elegant, you can wrap this into a function, using the perfect forwarding idiom for the arguments (in general; in this case your arguments are cheap to copy, so no speed benefit from doing this):
template <class... Args>
MyTuple make_mytuple(Args&&... args)
{
    return MyTuple(example(std::forward<Args>(args)...), optional<int>(), optional<double));
}

The advantage of this template is that it's resilient to changes in example's constructor. If you add another argument, just call make_mytuple with the new arguments and it will work.
Your other point about the copying in the tuple construction is valid, but in reality I believe this will be optimal on most compilers. (a combination of RVO and elision of copies when passing an rvalue to a function by value).

A: You can use uniform initialization. Sadly, you cannot define a default value, argument will be initialized with the default constructor or 0.
#include <iostream>
#include <tuple>

enum class Result {Full, Partial, Empty};
std::tuple<bool, int, double> get_tuple(Result type)
{
    if (type == Result::Full)
        return {true, 42, 3.14159};
    else if (type == Result::Partial)
        return {true, 42, {}};
    else
        return {};
}

int main()
{
    bool b;
    int i;
    double d;

    std::tie(b, i, d) = get_tuple(Result::Full);
    std::cout << b << " " << i << " " << d << std::endl;

    std::tie(b, i, d) = get_tuple(Result::Partial);
    std::cout << b << " " << i << " " << d << std::endl;

    std::tie(b, i, d) = get_tuple(Result::Empty);
    std::cout << b << " " << i << " " << d << std::endl;

    return 0;
}

output:
1 42 3.14159
1 42 0
0 0 0


text:
Q: App crashes showing nullPointerException I was trying to make a basic intent from one activity to another but it crashes as soon as the button "next is clicked ".
    package com.example.aditya.myapplication;

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;

    public class MainActivity extends AppCompatActivity {
        private Button next;
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            next = (Button) findViewById(R.id.toNextActivity1);
            next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(v.getContext(), qu1.class);
                    startActivity(i);
                }
            });
        }
    }

That's the java code .
the activity_main.xml is this
<ImageView
    android:id="@+id/hello"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@mipmap/ic_launcher"
    android:scaleType="center"
    android:layout_marginTop="104dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

<Button
    android:id="@+id/toNextActivity1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:text="Play "
    android:layout_marginBottom="79dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@id/hello"
    android:layout_toEndOf="@id/hello" />

Logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aditya.myapplication/com.example.aditya.myapplication.qu1}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

A: Change v.getContext() to MainActivity.this
next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, qu1.class);
            startActivity(i);
        }
    });

A: Under the
    private Button next;

write
    Activity activity;

inside
    onCreate(){
    activity = this;

    }

then inside onClick
startActivity(new Intent(activity,qu1.class);

this shud solve your problem.

A: *

*May be you donot have add qu1.class activity to the manifest file.

*Change v.getContext to MainActivity.this


text:
Q: Document builder from xml gives error I am trying to parse a html response which is in xml format.
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream in = new FileInputStream(htmlresponse);
        InputSource inputSource = new InputSource(new InputStreamReader(in));
        Document xmlDocument = builder.parse(inputSource);   //Error is here

However I get an error on line which I have commented on.
Error - "the method parse(InputStream) in the type DocumentBuilder is not applicable for the arguments (InputSource)"

A: I had the same problem.
For me, problem was due to a bad import of class InputSource.
So, I had imported jdk.internal.org.xml.sax.InputSource instead of org.xml.sax.InputSource. With org.xml.sax.InputSource the problem is solved.

A: Modified code, Try this
    String xml = "<test>this is a test xml</test>";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new InputSource(new StringReader(xml)));


text:
Q: Mutate with multiple conditionals I'm trying to create a mutate a new column called category with each of the product name classifications. And also I would like to mutate a column wherein caffeine_mg>0 has caffeine, but caffeine_mg=0 has no caffeine.
sbucks <- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-12-21/starbucks.csv')

sbucks_new <- sbucks %>%
  mutate(category = case_when(grepl("Tea", product_name) ~ "Tea",
                              grepl(c("coffee","Coffee","Caffè"), product_name) ~ "Coffee",
                              grepl("Smoothie", product_name) ~ "Smoothie",
                              grepl("Hot Chocolate", product_name) ~ "Hot Chocolate",
                              grepl("Espresso", product_name) ~ "Espresso",
                              grepl("Refreshers", product_name) ~ "Refreshers",
                              TRUE ~ "Others")) %>%
  mutate(Caffeine = case_when(caffeine_mg=0 ~ "No",
                              caffeine_mg>0 ~ "Yes"))

A: There were several syntax errors in the OP's code:

*

*In the second call to grep, the vector of patterns should be collapsed into a single character regex as with xxx|yyy|zzz.

*In the second mutate, please see that the equality comparator would be == and not =.
bucks %>%
    mutate(category = case_when(grepl("Tea", product_name) ~ "Tea",
                                grepl("coffee|Coffee|Caffè", product_name) ~ "Coffee",
                                grepl("Smoothie", product_name) ~ "Smoothie",
                                grepl("Hot Chocolate", product_name) ~ "Hot Chocolate",
                                grepl("Espresso", product_name) ~ "Espresso",
                                grepl("Refreshers", product_name) ~ "Refreshers",
                                TRUE ~ "Others")) %>%
    mutate(Caffeine = case_when(caffeine_mg == 0 ~ "No",
                                caffeine_mg >0 ~ "Yes" ))

# A tibble: 1,147 × 17
   product_name                           size    milk  whip serv_size_…¹ calor…² total…³ satur…⁴ trans…⁵ chole…⁶ sodiu…⁷ total…⁸ fiber_g sugar_g caffe…⁹ categ…˟ Caffe…˟
   <chr>                                  <chr>  <dbl> <dbl>        <dbl>   <dbl>   <dbl>   <dbl> <chr>     <dbl>   <dbl>   <dbl> <chr>     <dbl>   <dbl> <chr>   <chr>
 1 brewed coffee - dark roast             short      0     0          236       3     0.1       0 0             0       5       0 0             0     130 Coffee  Yes
 2 brewed coffee - dark roast             tall       0     0          354       4     0.1       0 0             0      10       0 0             0     193 Coffee  Yes
 3 brewed coffee - dark roast             grande     0     0          473       5     0.1       0 0             0      10       0 0             0     260 Coffee  Yes
 4 brewed coffee - dark roast             venti      0     0          591       5     0.1       0 0             0      10       0 0             0     340 Coffee  Yes
 5 brewed coffee - decaf pike place roast short      0     0          236       3     0.1       0 0             0       5       0 0             0      15 Coffee  Yes
 6 brewed coffee - decaf pike place roast tall       0     0          354       4     0.1       0 0             0      10       0 0             0      20 Coffee  Yes
 7 brewed coffee - decaf pike place roast grande     0     0          473       5     0.1       0 0             0      10       0 0             0      25 Coffee  Yes
 8 brewed coffee - decaf pike place roast venti      0     0          591       5     0.1       0 0             0      10       0 0             0      30 Coffee  Yes
 9 brewed coffee - medium roast           short      0     0          236       3     0.1       0 0             0       5       0 0             0     155 Coffee  Yes
10 brewed coffee - medium roast           tall       0     0          354       4     0.1       0 0             0       5       0 0             0     235 Coffee  Yes
# … with 1,137 more rows, and abbreviated variable names ¹serv_size_m_l, ²calories, ³total_fat_g, ⁴saturated_fat_g, ⁵trans_fat_g, ⁶cholesterol_mg, ⁷sodium_mg,
#   ⁸total_carbs_g, ⁹caffeine_mg, ˟category, ˟Caffeine
# ℹ Use `print(n = ...)` to see more rows


text:
Q: Very fast webpage scraping (Python) So I'm trying to filter through a list of urls (potentially in the hundreds) and filter out every article who's body is less than X number of words (ARTICLE LENGTH). But when I run my application, it takes an unreasonable amount of time, so much so that my hosting service times out. I'm currently using Goose (https://github.com/grangier/python-goose) with the following filter function:
def is_news_and_data(url):
"""A function that returns a list of the form
    [True, title, meta_description]
    or
    [False]
"""
result = []
if url == None:
    return False
try:
    article = g.extract(url=url)
    if len(article.cleaned_text.split()) < ARTICLE_LENGTH:
        result.append(False)
    else:
        title = article.title
        meta_description = article.meta_description
        result.extend([True, title, meta_description])
except:
    result.append(False)
return result

In the context of the following. Dont mind the debug prints and messiness (tweepy is my twitter api wrapper):
def get_links(auth):
"""Returns a list of t.co links from a list of given tweets"""
api = tweepy.API(auth)
page_list = []
tweets_list = []
links_list = []
news_list = []
regex = re.compile('http://t.co/.[a-zA-Z0-9]*')

for page in tweepy.Cursor(api.home_timeline, count=20).pages(1):
    page_list.append(page)
for page in page_list:
    for status in page:
        tweet = status.text.encode('utf-8','ignore')
        tweets_list.append(tweet)

for tweet in tweets_list:
    links = regex.findall(tweet)
    links_list.extend(links)
#print 'The length of the links list is: ' + str(len(links_list))
for link in links_list:
    news_and_data = is_news_and_data(link)
    if True in news_and_data:
        news_and_data.append(link)
        #[True, title, meta_description, link]
        news_list.append(news_and_data[1:])
print 'The length of the news list is: ' + str(len(news_list))

Can anyone recommend a perhaps faster method?

A: This code is probably causing your slow performance:
len(article.cleaned_text.split())

This is performing a lot of work, most of which is discarded.  I would profile your code to see if this is the culprit, if so, replace it with something that just counts spaces, like so:
article.cleaned_text.count(' ')

That won't give you exactly the same result as your original code, but will be very close.  To get closer you could use a regular expression to count words, but it won't be quite as fast.

A: I'm not saying this is the most absolute best you can do, but it will be faster. You'll have to redo some of your code to fit this new function.
It will at least give you less function calls.
You'll have to pass the whole url list.
def is_news_in_data(listings):
    new_listings = {}
    tmp_listing = ''
    is_news = {}
    for i in listings:
        url = listings[i]
        is_news[url] = 0
        article = g.extract(url=url).cleaned_text
        tmp_listing = '';
        for s in article:
            is_news[url] += 1
            tmp_listing += s
            if is_news[url] > ARTICLE_LENGTH:
                new_listings[url] = tmp_listing
                del is_news[url]
    return new_listings


text:
Q: Question about memory allocation in CUDA kernel Hey there,
I have an array with the size SIZE*sizeof(double) on my host. I allocate a device pointer of the size of the host-array and copy the array to the device. Now I pass this device array dev_point to my kernel function. Each threads need to modify some values of the passed array and than calculates another _device__-function with the new array-values (different for each thread). Now I wonder how to do this? Before I had a complete CPU-version (serial code) of my program and I simply always created a new array like double new_array[ SIZE ] and than copied the data from the original array to it, modified it and than deleted it again. But how to do it in CUDA, since I can't allocate memory from within a kernel-function. Is there any possibility to use 'local' memory of the thread to store a new array in? Or do I have to allocate a big array of the size SIZE * number_of_total_threads * sizeof(double) before calling my kernel function so that each thread can store the modified array in it?
Thanks a lot in advance!
EDIT: FULL DESCRIPTION!
Okay here's a better problem description on my 'current' case: In my host program I have a array, let's say with 300 values (dependent on the user input between 100 and 400, let's call that variable numValues which is a size depending on the program parameters and not hardcoded into the program!) of doubles. Now I want each kernel-execution to take exactly this array (it is actually copied to GPU and passed to kernel function as a pointer), change the value to the n-th element (n = unique identifier which goes from 0 to numValues), whereas all other array elements stay the same. The modification is a simple addition of a certain constant value, which is also passed to the program by the user. And than call a function which is defined like that __device__ double thefunction(double *ary) passing the modified array.
So the first solution which I thought about was the one I asked here: Give each thread (each kernel execution) an own array-copy (I thought this could be done locally, but obviously can't because numValues is runtime specific) and than let each thread modify value n and calculate thefunction with it.
Now I just came up with another idea while writing this here: Perhaps it would be better to have the array in constant or shared memory ONCE so that each thread passes the array as unmodified array to thefunction but specifies as additional parameters to thefunction an index int idx about which element to modify and another parameter double *add about the value to add to the idx-th element.
The only thing which I wonder about is than: How to add the value *add to the idx-th Element without modifying the array ary passed to the function because this is passed as a pointer and I don't want to modify the original one!
Thanks!

A: If an array will be used by a single GPU thread, you can allocate it in local memory or global memory.  Local memory is declared inside the kernel function, and works exactly like declaring a local variable in C.  You can only use local memory if SIZE is an integer constant, not a run-time value.  Otherwise, you will have to use global memory.  To use global memory, as you said, allocate a big array.  Each thread would compute the offset into the big array that it would use  as its private array.
However, you should consider reorganizing the algorithm on the GPU.  Unlike a CPU, where one thread can use a large cache, the on-chip memory on a GPU is shared by hundreds of threads.  There is not enough on-chip memory for each thread to have a large private array, and off-chip memory is too slow to be useful.  (For example, a typical kernel on a G80 architecture would have 256 threads using 16KB of shared memory, which limits the maximum array size to 64 bytes.)  Is it possible to parallelize the computation of a private array?

A: If you only need to modify some values, as you say, then at the level of the data required to compute a single result, it follows you should only need a local copy of some of the input data. That local copy should, ideally, be held in registers, which is the fastest place to store thread local data.
If there is data dependency between the local modifications required for one result and the local modifications required for another, the usual solution is to group the computation of interdependent results into a single block and use shared memory to hold the modified data, which allows data exchange between threads within that block. If you algorithm is something like a recurrence relation where there is sequential dependence on data from a previous calculation, you need a new algorithm, because those types of calculations cannot be easily executed in parallel in any useful way.
That is about as good a answer as you will get without specifics of the code and algorithms involved.


text:
Q: confusion about alignment of two div in a single div I have a box of buttons and also a chart,should be aligned in a single div,but they are not, and I have no idea how to make them aligned
My buttons are in a box with following CSS:
.CrewPrsntButtonsError {
    font-size:11px;
    width:100px;
    height:100px;
    color:black;
    background:linear-gradient(to bottom, red 15%,  white 10%);
}

here is my Chart:

Considering these all :

             <button type="button" id="btnErrorStat" class="CrewPrsntButtonsError"></button>
             <button type="button" id="btnIdle" class="CrewPrsntButtonsError"></button>
             <button type="button" id="btnService" class="CrewPrsntButtonsError"></button>
             <button type="button" id="btnLinkDn" class="CrewPrsntButtonsError"></button>
             <button type="button" id="btnDataIn" class="CrewPrsntButtonsError" ></button>
             <button type="button" id="btnrepOff" class=CrewPrsntButtonsError"></button>
             <button type="button" id="btnCrew" class="CrewPrsntButtonsError"></button>

ScreenShot

A: There are some syntax errors like missing ". Please try below example. I hope it will work for you.

.CrewPrsntButtonsError {
  font-size:11px;
  width:100px;
  height:100px;
  color:black;
  background:linear-gradient(to bottom, red 15%,  white 10%);
}
.container{
  width: 100%;
  overflow: hidden;
}
#containerBtns{
  width: 70%;
  float:left;
  background: red;
}
#Chart{
  width: 20%;
  float:right;
  background: blue;
}

    <button type="button" id="btnErrorStat" class="CrewPrsntButtonsError">button</button>
    <button type="button" id="btnIdle" class="CrewPrsntButtonsError">button</button>
    <button type="button" id="btnService" class="CrewPrsntButtonsError">button</button>
    <button type="button" id="btnLinkDn" class="CrewPrsntButtonsError">button</button>
    <button type="button" id="btnDataIn" class="CrewPrsntButtonsError" >button</button>
    <button type="button" id="btnrepOff" class="CrewPrsntButtonsError">button</button>
    <button type="button" id="btnCrew" class="CrewPrsntButtonsError">button</button>

chart here

A:

                        Chart

                            <button type="button" id="btnErrorStat" class="CrewPrsntButtonsError">button</button>
                            <button type="button" id="btnIdle" class="CrewPrsntButtonsError">button</button>
                            <button type="button" id="btnService" class="CrewPrsntButtonsError">button</button>
                            <button type="button" id="btnLinkDn" class="CrewPrsntButtonsError">button</button>
                            <button type="button" id="btnDataIn" class="CrewPrsntButtonsError" >button</button>
                            <button type="button" id="btnrepOff" class="CrewPrsntButtonsError">button</button>
                            <button type="button" id="btnCrew" class="CrewPrsntButtonsError">button</button>


text:
Q: android custom markers with a transparent Bus image I am trying to add a transparent bus marker to my Google MAP, But it doesn't add the way i wanted as show in pic,GoodOne
image that i use for marker
But this what i get thisiswhatiget
Also it doesn't take bus exact shape but it draws in Rectangle format
here is my code from main activity
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.bus);
               Bitmap circle = getCircleBitmap(image, 80);
               Marker mMarker = googleMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromBitmap(circle))
                    .flat(true).anchor(0.25f, 0.25f)
                    .visible(true)
                    .position(position));

 public static Bitmap getCircleBitmap(Bitmap bmp, int size){
      Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bmp, 50, 50);
      Bitmap output = Bitmap.createBitmap(size, size,     Bitmap.Config.ARGB_8888);
     Canvas canvas = new Canvas(output);

    int color = Color.RED;
    Paint paint = new Paint();
    Rect rect = new Rect(0, 0, size, size);
    RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawOval(rectF, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(thumbnail, 15,15, paint);

    //thumbnail.recycle();
    return output;
  }

Please do help on this, Is it that BITMAP makes picture loose transparency?

A: If your drawable (bus.png for example) has a transparent background (this is very important and according to your result I think that it has a white background), you just need to change the PorterDuff mode to be SRC_OVER in your getCircleBitmap:
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));


text:
Q: How to put a textfile into sqlite simply using Python API? I have a tab delimited file in the format:
sentenceID (sid)    documentID (scid)   sentenceText (sent)

E.g.
100004  100 即便您喜爱流连酒吧,也定然在这轻松安闲的一隅,来一场甜蜜沉醉的约会。
100005  100 您可以慢慢探究菜单上所有的秘密惊喜。

I want to put it into sqlite3 with the following schema:
CREATE TABLE sent (
    sid INTEGER PRIMARY KEY,
    scid INTEGER,
    sent TEXT,
    );

Is there a quick way to use the python API for sqlite (http://docs.python.org/2/library/sqlite3.html) to put them into a table?
I've been doing it as such:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys, codecs

con = lite.connect('mycorpus.db')

with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE Corpus(sid INT, scid INT, sent TEXT, PRIMARY KEY (sid))")
    for line in codecs.read('corpus.tab','r','utf8'):
        sid,scid,sent = line.strip().split("\t")
        cur.execute("INSERT INTO Corpus VALUES("+sid+","+scid+"'"+sent+"')")

A: Here's an example using unicodecsv module:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3

import unicodecsv

con = sqlite3.connect('mycorpus.db')
cur = con.cursor()
cur.execute("CREATE TABLE Corpus(sid INT, scid INT, sent TEXT, PRIMARY KEY (sid))")

with open('corpus.tab', 'rb') as input_file:
    reader = unicodecsv.reader(input_file, delimiter="\t")
    data = [row for row in reader]

cur.executemany("INSERT INTO Corpus (sid, scid, sent) VALUES (?, ?, ?);", data)
con.commit()

Also see:

*

*Reading a UTF8 CSV file with Python

*Importing a CSV file into a sqlite3 database table using Python
Hope that helps.

A:     #!/usr/bin/python
    # -*- coding: utf-8 -*-

    import sqlite3 as lite

    con = lite.connect('myCorpus.db')
    cur = con.cursor()

    cur.execute("CREATE TABLE Corpus(sid INT, scid INT, sent TEXT, PRIMARY KEY (sid))")

    data=[row.split('\t') for row in file('myfile.tab','r').readlines()]
    cur.executemany("INSERT INTO Corpus (sid, scid,sent) VALUES (?, ?, ?);", data)

    con.commit()


text:
Q: How do I use a variable to get CSS info on an element? What I have is the following code to create a div.
function makeLinkdiv () {
  gCurrentBlock = $gBlockDivName + $gBlockPointer;
  var idPointer = gCurrentBlock;
  var linksBlock = $('

').appendTo("#canvas");
  linksBlock.draggable({containment: "#canvas", scroll: false, grid: [10, 10]}, {cursor: "move", cursorAt: {top: 125, left: 50}});
  linksBlock.append('
Article Title
');
  //
  // log the div data to the div object
  //
  var x = gCurrentBlock.css('left');
  var y = gCurrentBlock.css('top');
  alert ('top is - ' + y + ' left is - ' + x);
  divData.items.push({ID: $gBlockPointer, Block: gCurrentBlock, posTop : "450", posLeft : "540" });
  //
  // increment the block pointer
  //
  $gBlockPointer = $gBlockPointer + 1;
  //
}

What happens is that I do not get the CSS properties for top and left. Actually, nothing happens. I know that there must be something wrong in how I am using the variable gCurrentBlock, but I can't figure it out.

A: You can't use .css() without using it as a jQuery-object.
Try the following instead:
var x = document.getElementById(gCurrentBlock).style.left;
var y = document.getElementById(gCurrentBlock).style.top;

A: Not really sure what your code is trying to accomplish... but you need to check out jQuery's position and offset methods, which will give you coordinates for your element.
I would expect your code to look more like this:
...
var position = $('#' + gCurrentBlock).position();
var x = position.left;
var y = position.top;
...

And if the values are not what you expect, try changing position to offset.

A: Here gCurrentBlock is a id in which you are directly using jquery method, so it will not work.
Try x=$('#'+gCurrentBlock).css('left') //it will return you left position in pixel like 150px
if you want left position in number you can use
 x=$('#'+gCurrentBlock).position().left; //will return x as 150

same you can do for y.
y=$('#'+gCurrentBlock).css('top');

or
y=$('#'+gCurrentBlock).position().top;

A: I think you are not selecting the selector in a proper way:
 var x = gCurrentBlock.css('left');
 var y = gCurrentBlock.css('top');

you have appended it like this:
var linksBlock = $('

').appendTo("#canvas");
//--------------------------------^^^^^^^^^^^^^---this is the id of the div

so your code should be :
 var x = $('#'+gCurrentBlock).css('left');
 var y = $('#'+gCurrentBlock).css('top');

A: The gCurrentBlock is a variable which contains the id of the div only, Thus
Replace this
var x = gCurrentBlock.css('left');

With
var x = $("#"+gCurrentBlock).css('left');

Hope this will help !!


text:
Q: Can 32-bit Windows LiveCD modify the Registry of an Offline 64-bit Windows? Is it possible to mount the NTFS and registry hives from a 64-bit Windows on a 32-bit Windows Preinstallation Environment (32-bit). Does 64-bit change the file format?
Also can x86_64 machines boot unmodified 32-bit OSes?

A: There's no overall data/schema differences between the registries of 32-bit and 64-bit Windows - obviously the actual content will be different but there's no structural differences no.
And yes an x86 64-bit machine can 100% boot a 32-bit OS straight out of the box.

A: NTFS is the same for 32- and 64-bit, so you will be able to read any files.
As for the structure -

The registry in 64-bit versions of
  Windows is divided into 32-bit and
  64-bit keys. Many of the 32-bit keys
  have the same names as their 64-bit
  counterparts, and vice versa. KB article

so, your offline editor shall be capable of viewing/changing both parts.


text:
Q: Firebase: user is not set on the first rendering Based on this example, I wrote the following App component:
import React, {Component} from 'react';
import withFirebaseAuth from 'react-with-firebase-auth'
import firebase from 'firebase/app';
import 'firebase/auth';
import firebaseConfig from './firebaseConfig';

import './common.css'
import './fonts.css'
import NotSignedIn from './NotSignedIn/NotSignedIn'

const firebaseApp = firebase.initializeApp(firebaseConfig);

class App extends Component {
  render = () => {
    const {
      user,
      //signOut,
      signInWithGoogle,
    } = this.props;
    return user ?
Hello, {user.displayName}
 : <NotSignedIn signIn={signInWithGoogle}/>;
  }
}

const firebaseAppAuth = firebaseApp.auth();

const providers = {
  googleProvider: new firebase.auth.GoogleAuthProvider(),
};

export default withFirebaseAuth({
  providers,
  firebaseAppAuth,
})(App);

For some reason, if I refresh the page when the user is signed in, the <NotSignedIn> component is momentarily rendered, and only then the page is re-rendered and the "Hello [etc.]" message appears. Why does this happen and how do I fix this, so that user would be correctly set on the first rendering?

A: *

*Use a loader in state.

*In the authentication callback, update user in the state to render correct component based on condition.

This way you can get rid of the not logged in component and show a loading component on each page refresh.

*Optional - Once the auth is completed, store user id in cookie or localstorage and pull data from there to avoid showing loading all the time.

With the above step, you can get rid of loading component as well, and make your app load data quicker.
Here's an example with 1st & 2nd point in action: https://codesandbox.io/s/handle-login-non-login-user-8pljl?file=/src/App.js:493-514


text:
Q: complaining about logging and rethrowing the exception in sonar I have the following piece of code in my program and I am running SonarQube for code quality check on it after integrating it with Maven.
However, Sonar is complaining that I should Either log or rethrow this exception.
What am I missing here? Am I not already logging the exception?
public AccountResponse  getAccountStatus(AccessIDSearchResponse accessIDResponse) {
    accountResponse = null;
    try {
        AccountRequest request = new AccountRequest();
    } catch (ServiceException serviceException) {
        log.error("getAccountStatus-GotServiceException =" + ExceptionUtils.getStackTrace(serviceException));
        throw serviceException;
    } catch (Exception e) {
        throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, e.getMessage());
    }
    return accountResponse;
}


text:
Q: JFreechart right click on XYItemEntity I realized that the chartMouseClicked method gets called only when the user left-clicks on a chart.MousePressed() and mouseReleased() methods are called When when the user right-clicks on a chart. But I need something more. I need them together.I need to find if an user right clicks on XYItemEntity.Then I will show new pop up menu item. If user select menu item, I will pass information from XYITEM. If it is not XYItemEntity, I will not update Popupmenu of chart. That is how can I check XYITEM entity on chartMouseClicked.
panel.addChartMouseListener(new ChartMouseListener() {
        public void chartMouseClicked(final ChartMouseEvent event) {
            /** If Time Instance point is clicked */
            if (event.getEntity() instanceof XYItemEntity) {

}}

A: I have managed to find a solution combining chartMouseMoved and mouseReleased methods.
 public void chartMouseMoved(final ChartMouseEvent event) {
            if (event.getEntity() instanceof XYItemEntity) {
                panel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                clickedSimulationItem = (XYItemEntity) event.getEntity();
            } else if (event.getEntity() instanceof PlotEntity) {
                handleMouseMoveOnPlot(event);
            } else {
                panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                clickedSimulationItem = null;
            }
        }

private void addMouseListener() {
    panel.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                if (clickedSimulationItem != null) {

                        panel.getPopupMenu().add(new JMenuItem("denem"));
                        /** update pop up */
                    }
                }
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub
        }
    });
}


text:
Q: Is ReactiveCocoa API work the same as RXAndroid ? Is ReactiveCocoa API work the same as RXAndroid ?
Can I use it to call multiple requests at the same time and combine the results.

A: According to a blog post Using ReactiveCocoa to parallelize multiple requests, by Giovanni
This would be possible by using either

signals combination, and [sic] collection magic.

Read up on the linked article.


text:
Q: Is it possible to get the Model error code inside the controller in CakePHP? I have a simple unsubscribe function in my Unsubscribed controller.
if ($this->Unsubscribe->save($this->data['Unsubscribes'])) {
   // success
   $this->Session->setFlash('Your email has been unsubscribed!');
   $this->redirect('/unsubscribes/unsubscribe');
} else {
   // error
   $this->Session->setFlash('There was an error!');
   $this->redirect('/unsubscribes/unsubscribe');
}

Here is the problem. I want to set the email address in the database as unique. So if someone enters the email address multiple times (or we already have it in our unsubscribe list), we are not populating the database with duplicate records. However, I want the visitor to know they have been added to the database (so they know they are unsubscribed).
Is there a way to detect the Duplicate entry error from the controller so I can equate that to a success? The caveat, I don't want to create a extended app_model. Any ideas? Can it be done? How is the best way to do this?
SOLUTION: Here is the final solution I implemented. I added the validation (as suggested by the chosen answer below) and I updated my controller as follows:
// error
if(isset($this->Unsubscribe->validationErrors['email'])){
   $error = 'Your email has been unsubscribed!';
} else {
   $error = 'Something went wrong. Please try again.';
}

$this->Session->setFlash($error);
$this->redirect('/unsubscribes/unsubscribe');

A: What about using the isUnique validation rule? Then just use the validation error to inform the user.
var $validate = array(
    'login' => array(
        'rule' => 'isUnique',
        'message' => 'This username has already been taken.'
    )
);

Stole this directly from the cookbook. Section 4.1.4.14 isUnique to be precise.

A: I think you can do it like this:
if ($this->Unsubscribe->find('count',array('conditions'=>array('email'=>$this->data['Unsubscribes']['email']))) > 0   )
{
   $this->Session->setFlash('duplicate email!');
   $this->redirect('/unsubscribes/unsubscribe');
}
//then do your stuff

A: It depends. Is there any other error that might occur that you want to display? Or is this the only error that may occur? In case of the latter, just don't check:
$this->Unsubscribe->save($this->data['Unsubscribes']);
// I don't care if that actually saved or not,
// unless something horrible happened the email is in the database
$this->Session->setFlash('Your email has been unsubscribed!');
$this->redirect('/unsubscribes/unsubscribe');

Otherwise, you can use the invalidFields() method to find out what went wrong.


text:
Q: Why do equal duration transitions take different amounts of time? I have two nested elements: A and B. The outer element A is the same size as the inner element B. Element B contains some text. Both elements have a CSS transition with a duration of one second. On hover A changes the text colour, while B changes the background colour.

#A {
  color: red;
  transition: all 1s;
}

#B {
  font-size: 100px;
  background-color: red;
  transition: all 1s;
}

#A:hover {
  color: green;
}

#B:hover {
  background-color: green;
}

Example Text

I expected the transitions would complete at the same time, however the background transition finishes before the text transition. What causes this behaviour?

A: This is caused by this Chrome bug (and this Webkit one).
Basically they do fire the transitions of inherited properties once per level, and each level will delay the next one by the transition's duration.
You could avoid this issue by ensuring that the inherited property (here color) gets transitioned only once:

#A {
  color: red;
  transition: all 1s;
}

#B {
  font-size: 100px;
  background-color: red;
  transition: background-color 1s; /* limit this transition to bg-color only */
}

#A:hover {
  color: green;
}

#B:hover {
  background-color: green;
}

Example Text

or

#A {
  color: red;
}

#B {
  font-size: 100px;
  background-color: red;
  transition: all 1s; /* set the transition only on the child */
}

#A:hover {
  color: green;
}

#B:hover {
  background-color: green;
}

Example Text


text:
Q: ExtJS5: Checkbox afterSubTpl wraps icons The snippet below will not run on this site, but you can access a working demo here on JSFiddle.
I am trying to get the icon to appear to the right of the checkbox, but it appears to be wrapping. Is there a property that I need to set so that it will appear in-line? This worked in ExtJS4, but after I switched to ExtJS5 this does not work.

afterSubTpl Documentation

Ext.form.field.Checkbox -> config -> afterSubTpl
An optional string or XTemplate configuration to insert in the field markup after the subTpl markup. If an XTemplate is used, the component's render data serves as the context.

Code

Ext.require(['*']);

Ext.define('App.view.MainView', {
    extend: 'Ext.panel.Panel',
    xtype: 'mainView',
    alias: 'widget.mainview',
    title: 'Checkbox Template Example',
    referenceHolder: true,
    layout: {
        type: 'border'
    },
    initComponent: function () {
        var me = this,
            tooltip = me.getHelpIconWithTooltip();
        me.items = [{
            region: 'center',
            xtype: 'panel',
            title : 'A Panel Title',
            margin : 20,
            bodyStyle: 'padding: 8px;',
            layout : 'vbox',
            items : [{
                xtype: 'checkbox',
                fieldLabel : 'Checkbox',
                afterSubTpl: tooltip
            }]
        }],
        me.callParent();
    },

    getHelpIconWithTooltip: function () {
        return this.getFormIconWithTooltip('help-icon help-form-icon',
            'This is a help tooltip...');
    },

    getFormIconWithTooltip: function (iconClassList, toolTipText) {
        var getSpan = function(cl, qt) {
            return '';
        }
        return [
            '<tpl>',
            getSpan(iconClassList, toolTipText),
            '</tpl>'
        ];
    }
});

Ext.define('App.app.App', {
    extend: 'Ext.app.Application',
    name: 'App',
    launch: function () {
        Ext.create('Ext.Viewport', {
            layout: 'fit',
            flex: 1,
            items: [{
                xtype: 'mainview'
            }]
        });
    }
});

Ext.onReady(function () {
    Ext.application('App.app.App');
});
.help-icon {
    display: inline-block;
    background: url(http://www.famfamfam.com/lab/icons/silk/previews/index_abc.png) -705px -1125px no-repeat;
 width: 16px;
 height: 16px;
}

.help-form-icon {
    /*margin-left: 5px;*/
}
<link href="https://extjs.cachefly.net/ext/gpl/5.1.0/packages/ext-theme-crisp/build/resources/ext-theme-crisp-all-debug.css" rel="stylesheet" />

Edit
It looks like if I add a class to the checkbox, I can prevent it from wrapping, but now the icon is positioned too high.

{
    xtype: 'checkbox',
    fieldLabel: 'Checkbox',
    afterSubTpl: tooltip,
    cls: 'no-wrap-tooltip'
}

.no-wrap-tooltip .x-form-cb-wrap-inner {
    display: inline-block;
}

A: I may have figured it out, but this solution uses magic numbers which make it work in this instance.
Demo
{
    xtype: 'checkbox',
    fieldLabel: 'Checkbox',
    afterSubTpl: tooltip,
    cls: 'no-wrap-tooltip'
}

.no-wrap-tooltip .x-form-cb-wrap-inner {
    display: inline-block;
    line-height: 28px;
}


text:
Q: Derivatives of ODE trajectories w.r.t function values at specific time points - definitions in the neural ODEs paper I'm trying to understand proofs in the Neural ODE paper Appendix A, B.
And i'm stuck at the definitions. Equation (34) is introduced as "We will prove that if we define an adjoint state $a(t)=\frac{dL}{dz(t)}$ then ..."
Where $L$ is defined in equation (3): $L(\ z(t_1))=L(z(t_0)+\int_{t_0}^{t_1}f(z(t),t,\theta)dt\ )$ with scalar function $L$. And $z(t)$ satisfies $z'(t)=f(z(t),t,\theta)$.
Similarly the authors use $\frac{dT_{\epsilon} (z(t))}{dz(t)}$ where $T_\epsilon (z(t))=z(t+\epsilon)=z(t)+\int_{t}^{t+\epsilon}f(z(s),s,\theta)ds$ in (15)-(27).
But what are these derivatives $\frac{dT_{\epsilon} (z(t))}{dz(t)},\ \frac{dL}{dz(t)}$? How are they defined? They doesn't seem to be standard derivatives or Frechet derivatives of operators...
Upd:
Ok, it seems that $\frac{dL}{dz(t)}$ can be interpreted as just $L'(z(t))$, though i am still not sure. And i  still don't understand what is $\frac{dz(t+\epsilon)}{dz(t)}$ and how to get this from the chain rule (Appendix B, eq. 38):
$$\frac{dL}{\partial z(t)}=\frac{dL}{d z(t+\epsilon)}\frac{dz(t+\epsilon)}{dz(t)}$$
Upd 1:
From Neural ODE definition of derivative $\frac{d L}{dz(t)}$ (adjoint) it seems that
$$\frac{dL}{dz(t)} \neq L'(z(t))$$

A: It is easier than you might think. It all comes from Pontryagin maximum principle and the theory of Lagrange multipliers. You can check a follow up work of the original neural ODEs for the formal derivation of the Adjoint equations 1.


text:
Q: Add Index to postgreSQL query result My query result looks like this:
| A | B |
|-------|
| 1 | 2 |
| 1 | 4 |
| 1 | 6 |
| 1 | 9 |
| 1 | 1 |
| 1 | 6 |
| 1 | 9 |

Now I want to increase column A by the index of the result table, so the result would become like this:
| A | B |
|-------|
| 2 | 2 |
| 3 | 4 |
| 4 | 6 |
| 5 | 9 |
| 6 | 1 |
| 7 | 6 |
| 8 | 9 |

How can I do it?
Thanks!

A: You want row_number()
select (row_number() over (order by a) + 1) as A, b
from table t;

A: Maybe something like that:
SELECT
    (row_number() OVER (ORDER BY A) + A) AS columnAIndex,
     columnB
FROM ...

I don't have a PostgreSQL client installed here, therefore, i don't tested this query.


text:
Q: NetworkOnMainThreadException on 3.0 and higher I did learn about this on an article that, on 3.0 and higher, one has to use the AsyncTask to preform any network activity. Knowing this, I used the AsyncTask to call on a JSON request, and my main class looks like this:
MainPage.java
public class doTheFare extends AsyncTask<Void,Void,Void>
{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progress = new ProgressDialog(MainPage.this);
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setMessage("Processing Request ...");
        progress.show();
        UserFunctions users = new UserFunctions();
        jObj = users.distanceGET(location.getText().toString(), destination.getText().toString());
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        try{
            jArr = jObj.getJSONArray("rows");
            jObj1 = jArr.getJSONObject(0);
            jArr2 = jObj1.getJSONArray("elements");
            jObj2 = jArr2.getJSONObject(0);
            jObj3 = jObj2.getJSONObject("distance");
            distance_value = jObj3.getString("text");
            String value = jObj3.getString("value");
            SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            String sF = getPrefs.getString("startFare", "10");
            String pM = getPrefs.getString("perKilo", "27");
            startFare = Double.parseDouble(sF);
            perKilo = Double.parseDouble(pM);
            perMeter=perKilo/5;
            int parseDistance = Integer.parseInt(value);
            double fare = startFare+((parseDistance/200)*perMeter);
            int roundedValue = (int)Math.round(fare);
            //Fare to send
            taxiFare = String.valueOf(roundedValue);
            Log.i("Fare Estimate", taxiFare);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        progress.dismiss();
        from_split = location.getText().toString();
        to_split = destination.getText().toString();
        if(from_split.contains(","))
        {
            from_fill = from_split.split(",");
        }
        else
        {
            from_fill = from_split.split(" ");
        }
        if(to_split.contains(","))
        {
            to_fill = to_split.split(",");
        }
        else
        {
            to_fill = to_split.split(" ");
        }

        send_location=from_fill[0];
        send_destination=to_fill[0];
        send_fare = taxiFare;
        send_distance = distance_value;
        if(isMode.equalsIgnoreCase(""))
        {
            Calendar c = Calendar.getInstance();
            int hours = c.get(Calendar.HOUR_OF_DAY);
            if(hours<6)
                isMode = "nMode";
            else if(hours>=21)
                isMode = "nMode";
            else
                isMode = "dMode";
        }
        Intent toResults = new Intent(MainPage.this, ResultsDisplay.class);
        Bundle extras = new Bundle();
        extras.putString("TO", send_location);
        extras.putString("FROM", send_destination);
        extras.putString("FARE", send_fare);
        extras.putString("DISTANCE", send_distance);
        extras.putString("GMAPFROM", from_split.toString());
        extras.putString("GMAPTO", to_split.toString());
        extras.putString("MODE",isMode);
        toResults.putExtras(extras);
        startActivity(toResults);
        super.onPostExecute(result);
    }

}

In this Activity I have a OnClickListener that calls this AsyncTask even so the program is giving me the following
05-10 03:02:19.823: E/AndroidRuntime(1815): FATAL EXCEPTION: main
05-10 03:02:19.823: E/AndroidRuntime(1815): android.os.NetworkOnMainThreadException
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.example.calculator_taxi_fare.functions.JSONParser.getJSONFromUrl(JSONParser.java:56)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.example.calculator_taxi_fare.functions.UserFunctions.distanceGET(UserFunctions.java:28)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.example.calculator_taxi_fare.MainPage$doTheFare.onPreExecute(MainPage.java:251)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.AsyncTask.execute(AsyncTask.java:534)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.example.calculator_taxi_fare.MainPage$6.onClick(MainPage.java:230)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.view.View.performClick(View.java:4202)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.view.View$PerformClick.run(View.java:17340)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.Handler.handleCallback(Handler.java:725)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.os.Looper.loop(Looper.java:137)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at android.app.ActivityThread.main(ActivityThread.java:5039)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at java.lang.reflect.Method.invokeNative(Native Method)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at java.lang.reflect.Method.invoke(Method.java:511)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-10 03:02:19.823: E/AndroidRuntime(1815):     at dalvik.system.NativeStart.main(Native Method)
    location.setOnItemClickListener(new OnItemClickListener()
    {

Am I implementing this the right way ?? Please Help!
I also have implemented the Google PlacesAutocomplete in this app, in which the results/suggestions do show but are not select able on 3.0 or higher a Unexpected value from nativeGetEnabledTags: 0 error shows up. The code is as follows:
location.setOnItemClickListener(new OnItemClickListener()
    {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        // TODO Auto-generated method stub
        autoLocation = (Places) adapterView.getItemAtPosition(position);
        location.setText(autoLocation.description);
        location.clearFocus();
        destination.requestFocus();
        Log.d("AutoCompleteTask", location.getText().toString());
            }
});
destination.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
destination.setOnItemClickListener(new OnItemClickListener()
{

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            // TODO Auto-generated method stub
        autoDestination = (Places) adapterView.getItemAtPosition(position);
        destination.setText(autoDestination.description);
        destination.clearFocus();
        calculate.requestFocus();
        Log.d("AutoCompleteTask2", destination.getText().toString());
            }
});

A: It seems this code are getting data from network.
You have put it in workthread, put it on the doinBackground();
        jObj = users.distanceGET(location.getText().toString(), destination.getText().toString());

A: It seems your distanceGET method is doing network operation
According to doc here

onPreExecute(), invoked on the UI thread before the task is executed.
  This step is normally used to setup the task, for instance by showing
  a progress bar in the user interface.

Do your network things in doInBackground

A: You must Set your network operation on doInBackground() Method
jObj = users.distanceGET(location.getText().toString(), destination.getText().toString())

Must write in doInBackground()

A: Dont do network operations in pre-execute. Do network operations in doInBackground, that is the correct way.
protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
UserFunctions users = new UserFunctions();
    jObj = users.distanceGET(location.getText().toString(),
           destination.getText().toString());
    try{
        jArr = jObj.getJSONArray("rows");
        jObj1 = jArr.getJSONObject(0);
        --------------------
        --------------------
        }catch(Exception e){
        }
}


text:
Q: intersection of circle and lines ? $1$ what is the number of points in intersection,in $\mathbb{R^2}$ of the two plane curves $(1+x^2+y^2)(x^2+y^2-4)=0 $   and  $  y=7x $?
As I was visualising the diagram ,
from the diagram i can conclude that,,,number of points intersection $\mathbb{R^2}$ is $0$ as there is no intersection points.....
Please! verify my mistake where am I wrong?

A: $1+x^2+y^2=0$
$x^2+y^2=-1$
So it has no solutions (even when you substitute $y=7x$).
$x^2+y^2=4$
Has solutions. Substitute $y=7x$
$50x^2= 4$
$x^2=\frac{2}{25}$
So they intersect at two points, whose $x$ value is either $\sqrt{\frac{2}{25}}$ or $-\sqrt{\frac{2}{25}}$
To find $y$ of the points, substitute $x^2+y^2=4$: $\sqrt{\frac{2}{25}}$ and $-\sqrt{\frac{2}{25}}$

A: your figure is wrong. I am not able to comment the figure.


text:
Q: Timed out waiting for install to finish on Koji disk image build I am trying to build with Koji a disk image for CentOS7 that supports both BIOS and UEFI.  My problem is that while the following partitioning works during the build (even if it does not work when booting on a UEFI node):
# Partition clearing information
clearpart --all --disklabel gpt
# Disk partitioning information
part / --fstype="xfs" --size=1 --grow --asprimary
part biosboot --fstype=biosboot --size=1
# This is how upstream centos does it
part /boot/efi --fstype=vfat --grow --maxsize=200 --size=20

# Both UEFI AND BIOS cfg
grub2-mkconfig -o /boot/grub2/grub.cfg
grub2-mkconfig -o /boot/efi/EFI/centos/grub.cfg

The following doesn't, and all my partitioning changes end up with the bottom error.
# Disk partitioning information
part / --fstype="xfs" --ondisk=vda --size=3000 --mkfsoptions="-n ftype=1"
part biosboot --fstype=biosboot --size=1
# This is how upstream centos does it
part /boot/efi --fstype=vfat --grow --maxsize=200 --size=20

Error when building fails
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/imgfac/Builder.py", line 132, in _build_image_from_template
    self.os_plugin.create_base_image(self, template, parameters)
  File "/usr/lib/python2.7/site-packages/imagefactory_plugins/TinMan/TinMan.py", line 346, in create_base_image
    libvirt_xml = self.guest.install(self.app_config["timeout"])
  File "/usr/lib/python2.7/site-packages/oz/RedHat.py", line 703, in install
    self.virtio_channel_name)
  File "/usr/lib/python2.7/site-packages/oz/Guest.py", line 1576, in _do_install
    self._wait_for_install_finish(xml, timeout)
  File "/usr/lib/python2.7/site-packages/oz/Guest.py", line 827, in _wait_for_install_finish
    raise oz.OzException.OzException("Timed out waiting for install to finish.  %s" % (screenshot_text))
OzException: Timed out waiting for install to finish.  Check screenshot at /var/builder/builder/tasks/2080/1692080/oz_screenshots/factory-build-51bd5b7d-4463-4bf9-9069-2f4b109a0165-1580480811.51.ppm for more detail

Is there any way I can check where it acutally times out? Any debugging with Koji? How would I test this ppm screenshot?


text:
Q: How to implement a whatsapp mobile scroll effect in flutter I am trying to implement the scrolling effect on the home screen on whatsap on iphone, where the search bar disappears first while scrolling the the rest of the scrolling takes place. Any idea on how to implement it ?

A: You can try using the SliverAppBar with a CustomScrollView.
return Scaffold(
  //1
  body: CustomScrollView(
    slivers: <Widget>[
      //2
      SliverAppBar(
        expandedHeight: 250.0,
        flexibleSpace: FlexibleSpaceBar(
          title: Text('Goa', textScaleFactor: 1),
          background: Image.asset(
            'assets/images/beach.png',
            fit: BoxFit.fill,
          ),
        ),
      ),
      //3
      SliverList(
        delegate: SliverChildBuilderDelegate(
          (_, int index) {
            return ListTile(
              leading: Container(
                  padding: EdgeInsets.all(8),
                  width: 100,
                  child: Placeholder()),
              title: Text('Place ${index + 1}', textScaleFactor: 2),
            );
          },
          childCount: 20,
        ),
      ),
    ],
  ),
);


text:
Q: Ajax posting using rails 4.0 for commenting on the ForumThread I am developing an simple forum application using rails 4.0. I want my comments to be posted as Ajax rather than reloading an entire page please help me.
This is my show.html.erb for forum

   <%= @topic.title %>

    <%= @topic.content %>

    <%= @topic.comments.count %>
    Comments

   <%= render @topic.comments %>
   <%if user_signed_in? && current_user.user? %>

Reply to thread

   <%= render "comments/form" %>
  <% end %>

 <%if user_signed_in?%>
 <% if can? :update, @topic %>
  <%= link_to "Edit", edit_topic_path(@topic), class: "button" %>
 <% end %>

<% if can? :delete, @topic %>
 <%= link_to "Delete", topic_path(@topic), method: :delete, data: {      confirm: "Are you sure you want to do this?" }, class: "button" %>
<% end %>
<% end %>

And this is my _comment.html.erb partial

   <%= comment.comment %>

<%if user_signed_in?%>
<% if can? :update, @topic => Comment %>
  <%= link_to "Edit", edit_topic_comment_path(comment.topic, comment) %>
<% end %>
<% if can? :delete, @topic => Comment %>
  <%= link_to "Delete", [comment.topic, comment], method: :delete, data: { confirm: "Are you sure?" } %>
  <% end %>
<% end %>

A: You could use server-generated JavaScript and a remote form.

*

*Add remote: true to your form

*Prepare your controller to respond with JavaScript:
# CommentsController

def create
  @comment = @topic.comments.create!(comment_params)
  respond_to do |format|
    format.html { redirect_to @comment } # no js fallback
    format.js   # renders comments/create.js.erb
  end
end

*Create the create.js.erb template:
# comments/create.js.erb

$('#comments').prepend('<%=j render @comment %>');

What happens here is we tell Rails to render our comment (using the comment partial) as JavaScript-ready string (notice the <%=j), and we're creating JS that will prepend this new comment, rendered, to the beginning of the comments div. Do experiment with what you can do with this JS response; it's run in the context of the page with the form, so you can have a lot of fun with that.
Also read the article at https://signalvnoise.com/posts/3697-server-generated-javascript-responses - this is where I learned this technique, and you will no doubt find the similarities between the example code for your case and their example code.


text:
Q: Ramda - how to groupBy and transform I am trying to group elements by groupId and create a new structure.
Elements to group (For presentation purposes each group contains only one element but there are multiple groups with multiple elements):
const nodes = [
    {
        "id": 163779,
        "groupId": 0,
        "width": 400,
        "height": 368.28125
    },
    {
        "id": 163783,
        "groupId": 1,
        "width": 216.40625,
        "height": 102.453125
    }
]

I tried to use R.groupBy(R.prop('groupId'))(nodes) and that worked fine as a first step as a result I got:
{
    "0": [
        {
            groupId: 0,
            height: 368.28125,
            id: 163779,
            width: 400
        }
    ],
    "1": [
        {
            groupId: 1,
            height: 102.453125,
            id: 163783,
            width: 216.40625
        }
    ]
}

But I don't know how to achieve such a structure:
[
  {
    "id": 0,
    "children": [
      {
        "id": 163779,
        "groupId": 0,
        "height": 368.28125,
        "width": 400
      }
    ]
  },
  {
    "id": 1,
    "children": [
      {
        "id": 163783,
        "groupId": 1,
        "height": 102.453125,
        "width": 216.40625
      }
    ]
  }
]

Any help would be appreciated. Thank you

A: Create a function using R.pipe. First group by the groupId, and then convert to an array of [key, value] pairs using R.toPairs. Map the array of pairs to the required form with R.zipObj.

const { pipe, groupBy, prop, toPairs, map, zipObj, nth } = R

const fn = pipe(
  groupBy(prop('groupId')), // group by groupId
  toPairs, // convert to an array of [key, value] pairs
  map(zipObj(['id', 'children'])), // map to the required form
)

const nodes = [{"id":163779,"groupId":0,"width":400,"height":368.28125},{"id":163783,"groupId":1,"width":216.40625,"height":102.453125}]

const result = fn(nodes)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

since R.groupBy converts the array to an object with groupId as the key, the groupId is convert to a string. You can add another step to convert it back to a number by mapping and evolving id to a number:

const { pipe, groupBy, prop, toPairs, map, zipObj, nth, evolve } = R

const fn = pipe(
  groupBy(prop('groupId')), // group by groupId
  toPairs, // convert to an array of [key, value] pairs
  map(zipObj(['id', 'children'])), // map to the required form
  map(evolve({ id: Number })) // convert the id to number if needed
)

const nodes = [{"id":163779,"groupId":0,"width":400,"height":368.28125},{"id":163783,"groupId":1,"width":216.40625,"height":102.453125}]

const result = fn(nodes)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


text:
Q: can I securely access Gmail for a Rails app on shared hosting non-SSL without putting credentials at risk? That is, want a Rails application that lets me see a customized view of the user's Gmail calendar.  But it'll be on shared hosting so don't want to store credentials, or have them in the clear.
Question: Can I securely access Gmail for a Rails app on shared hosting non-SSL without putting credentials at risk?  How would I do this?  (e.g. does OAuth or OpenID solve this)
Requirements would be:

*

*Rails application will call Google Calendar via API

*No credentials stored on shared hosting site (e.g. in database or whatever) - MANDATORY

*Rails site is non-SSL - MANDATORY (for the purpose of this question)

*Ability to stay logged in whilst browser still open - DESIREABLE  (assume using session id...assuming this is secure)

For example exiting approach I've used which wouldn't satisfy my requirements on my non-SSL rails site (on a shared host) would be:
# Get Google Calendar
service = GCal4Ruby::Service.new
service.authenticate("<google account name>", "<password>")  # <== requires password
cal = GCal4Ruby::Calendar.find(service, "myCalendar")[0]

# Get Google Events
search_str = "<search str>"
@events = GCal4Ruby::Event.find(cal, search_str, params)

A: You will get mixed content if you try to include in an http page an https Google calendar view loaded as an iframe.
If you're just doing API calls, as long as the API calls are from your server to an encrypted endpoint, https://calendar.google.com or something similar, then there are no problems.
If you're doing API calls from a non-http page in the browser, then a determined attacker will be able to eavesdrop on any data you serve, including credentials sent to the browser for forwarding to the calendar service.
If you're sending credentials to the browser you should also worry about exfiltration via XSS.


text:
Q: Gradle using 2 different JDK I would like use some features from Java 9 and 10 in my PC java application which has common code with android app.
When I use jdk 10 or jdk 9 android application is building, but it doesn't launch(it is throwing a lots of errors). When I use jdk 8 for whole project everything is working correctly without any error. When I manually build project using 2 different jdk everything is working fine.
I tried set targetCompability and sourceCompability for android application for JavaVersion.Version_1_7 but it doesn't help. I tried use different jdks for java 9 and java 10 but it doesn't help with this problem.
I would like build android application and common component with jdk8 and other components with jdk10. Is it possible to force gradle to use different jdk for specific project without using external tools like bash?
My project structure looks like:
build.gradle
common-component(jdk8)/build.gradle
PC(jdk 10)/build.gradle
device-Android(jdk 8)/build.gradle

A: I found workaround. It works fine with gradle 4.7(Java 10 support was added in this release). This hack/workaround requires to launch project using lower JDK like Oracle JDK 8 or OpenJDK. We can build some components using higher version of JDK, but we can't build JDK project with JDK10 and then use it with JDK8 if we specify targetcompablility higher than 1.8. It will work only for java project and probably it won't work for android plugin and other JVM languages.
Part of build.gradle for PC application :
project (':pc-client') {
    dependencies {
        compile project(':net-default')
        testcompile JUNIT
    }
    compileJava {
        options.fork = true
        options.forkOptions.javaHome = file('/usr/lib/jvm/java-10-oracle')
        targetCompatibility = 1.10
        sourceCompatibility = 1.10
    }

   compileTestJava {
        options.fork = true
        options.forkOptions.javaHome = file('/usr/lib/jvm/java-10-oracle')
        targetCompatibility = 1.10
        sourceCompatibility = 1.10
    }
}


text:
Q: I'm having trouble POSTING a JSON string to a url for the output in JSON I'm trying to make a post request to this URL:
http://clan.z8games.com/clanServices.asmx/getPlayerPublicInfo

with this JSON string
{"usn":12434525}

to get an output similar to this;
 {"d":"{\"usn\":12434525,\"nick\":\"Guiness\",\"lev\":39,\"playCnt\":3734,\"winCnt\":3210,\"loseCnt\":239,\"enemyKillCnt\":129734,\"deathCnt\":5140,\"exp\":1072522,\"headshotKillCnt\":120339,\"friendKillCnt\":5,\"escapeCnt\":45,\"regDate\":\"2011\",\"lastPlayDate\":\"2012-08-12\",\"guildid\":217089,\"clanName\":\"Guiness™\",\"memberType\":null,\"gcClanID\":55000,\"hs5p\":202,\"fk1p\":0,\"k10p\":211,\"d20p\":2,\"esc4p\":0,\"sv3p\":676,\"matchLosses\":98,\"matchWins\":1894}"}

because I making a datascraper for game accounts (like stats) and each page is different based on the account ID.
I tried this:
<?php
$usn=$_GET["accountUSN"];
$url='http://clan.z8games.com/clanServices.asmx/getPlayerPublicInfo';

$options = array(
    'http' => array(
        'method' => "POST",
        'content' => http_build_query(
            array(
                'usn'=>$usn
             )
        )
    )
);

$context = stream_context_create($options);
$result =  file_get_contents($url,NULL,$context);
var_dump($result);
?>

Someone suggested this but it always returns
bool(false)

I just want to know how to do this properly, if it makes you feel any better I don't really want any full code. Also, I'm trying to avoid cURL and I'd like a native option.
Also, someone was trying to help me here:
https://stackoverflow.com/questions/11920064/php-simple-html-dom-parser-not-giving-me-text-for-a-td
but I accidentally deleted the post, being a new user. How can I undelete this?
EDIT:
<?php

$usn=$_GET['accountUSN'];
$url='http://clan.z8games.com/clanServices.asmx/getPlayerPublicInfo';

$options=array('http'=>array('method'=>'POST','content'=>'content' => '{\'usn\':$usn}'));

$context=stream_context_create($options);
$result=file_get_contents($url,NULL,$context);
var_dump($result);
?>

server error.

A: The way I've used this is to open the file, then get the stream content from the file pointer.
$context = stream_context_create($options);
$fp = fopen($url, 'rb', false, $context);
if (!$fp) {
   die('Failed to open stream');
}
$result = stream_get_contents($fp);
var_dump($result);

A: May be you could use firebug,see Net tab ,compare what you programmatically sent and what browser sent.
Make sure that you sent what it want.


text:
Q: Nested Array/Object access via [String][String] In AS3 I could access a nested array/object as follows:
var platformObj:Object = {"filters": {"manufacturer": ["Adobe Windows"]};
trace(platformObj["filters"]["manufacturer"]); //trace output: "Adobe Windows";

Errors in Haxe with: String should be Int (for the second argument):
    platformObj["filters"]["manufacturer"]
How can I do this in Haxe/OpenFL?

A: openfl.utils.Object is basically just a typedef for Dynamic, so the following works fine:
trace(platformObj.filters.manufacturer); // [trace] Main.hx:6: [Adobe Windows]

If you need to use a String to access the fields, you can do the following using a type check:
trace((platformObj["filters"] : Object)["manufacturer"]);

Under the hood, all of this is just reflection:
trace(Reflect.field(Reflect.field(platformObj, "filters"), "manufacturer"));

A: You could just use dot-notation:
var platformObj = {filters: {manufacturer: ["Adobe Windows"]}};
// the type of platformObj is `{filters:{manufacturer:Array<String>}}` in this case
trace(platformObj.filters.manufacturer);

Or you can use StringMap:
var platformObj = ["filters" => ["manufacturer" => ["Adobe Windows"]]];
// the type of platformObj is `Map<String, Map<String, Array<String>>>` in this case
trace(platformObj["filters"]["manufacturer"]);

Haxe doesn't have Object, but has Dynamic. You can retrieve its fields using Reflect:
var platformObj:Dynamic = {filters: {manufacturer: ["Adobe Windows"]}};
var filters = Reflect.field(platformObj, "filters");
var manufacturer = Reflect.field(filters , "manufacturer");
trace(manufacturer);

When you are using Haxe 3.3+ you can use Any instead of Dynamic.
The first two are safer to use. The last one using dynamic/reflection can have side effects.


text:
Q: Push-Pull formula for currents Let $f$ be transverse to $g$ so that
$\require{AMScd}$
\begin{CD}
V@>{f'}>> Z\\
@V{g'}VV @VV{g}V\\
Y @>{f}>> X
\end{CD}
is a Cartesian square of smooth manifolds. Then, if $g$ is proper and oriented, and $g'$ has the induced orientation, we get the formula
\begin{equation}
\label{eq}
f^*\circ g_* = g'_*\circ f'^* : H^*(Z;\mathbb R)\to H^{*+dim(X)-dim(Z)}(Y;\mathbb R).
\end{equation}
There is nothing special in using real coefficients. Now, I'm going to follow de Rham and compute my real cohomology groups using currents. The space of currents on $M$, which I'll denote by $\mathcal D^*(M)$, is the space of continuous linear functionals on the space of smooth, compactly supported forms on $M$. We have the pushforward
$$
g_*:\mathcal D^{*}(Z)\to \mathcal D^{*+dim(X)-dim(Z)}(X).
$$
We cannot pull back any current along $f$. However, I believe since $f$ is transverse to $g$, $f^*$ is defined on $g_*$ of forms. I've so far failed to find a concrete reference for that statement, but I think it follows from [Theorem 8.2.4, 1]. Let me explain why I think that (as a response to Shifrins comment): The theorem says that $f^*T$ can be defined if $N(f)\cap WF(T)=\emptyset$. Here $N(f)$ is the ''set of normals" of $f$, defined by
$$
N(f)=\{(x,\xi_x)\in X\times T^*X\backslash 0: \exists y\in Y\ s.t.\ \forall v\in T_yY \text{ we have } \xi(D_yfv)=0 \}.
$$
The wave front set I do not have a good grasp of. But I think it is true that $WF(g_*\omega)\subset N(g)$ when $\omega$ is a smooth form. If that is true, one must only observe that when $f$ and $g$ are transverse, $N(f)\cap N(g)=\emptyset$. That's easy to see: If $(x,\xi)\in N(f)\cap N(g)$, we can choose $z\in g^{-1}(x)$ and $y\in f^{-1}(x)$ such that $\xi(D_yf T_yY+D_zg T_zZ)=0$. But then $\xi=0,$ since the sum we are applying it to is $T_xX$ since $f\pitchfork g$.
My main question is: does the equation
$$
f^*\circ g_*=g'_*\circ f'^*
$$
hold as maps $\Omega^*(Z)\to \mathcal D^{*+dim(X)-dim(Z)}(Y)$?
[1] Hörmander, Lars, The analysis of linear partial differential operators. I: Distribution theory and Fourier analysis., Moskva: "Mir". 464 p. (1986). ZBL0619.35001.


text:
Q: How to Modify a link in core php Let the example be
I have a link:- localhost/project/search?uni=1
I want to change it in this way:- localhost/project/search/uni-of-uk
I am not using any framework , its a core PHP

A: Like this... based on the little info you gave ....
$link = 'localhost/project/search?uni=1';
$link = str_replace('?uni=1', '/uni-of-uk', $link);

NEW:  in PHP you can modify the header to change the url.
if($_GET['uni']==1)
{   header('Location: localhost/project/search/uni-of-uk');
    exit;
}

The important thing is that you DO NOT OUTPUT ANITHING before you call the header function.
So you should put this code on top of your script before any output.

A: What you are looking for is called URL Rewriting.
You can achieve this using mod_rewrite (assuming you are using apache).
You might want to look into this mod_rewrite Article

A: If you meant you want to change
localhost/project/search?uni=1

to
localhost/project/search/uni-of-uk/1

You can achieve it by creating a .htaccess in your root folder and adding something like this to it,
RewriteEngine on
RewriteRule ^/?search/uni-of-uk/([0-9]+)$ /search?uni=$1

Another method is PHP routing, big CMS sites follow this method as said here.

A: This can help you:
Write below code in your .htaccess file.
RewriteRule ^search/([^/]+) search.php?uni=$1 [NC]
Now, you can get value of "uni" using $_REQUEST['uni'] or $_GET['uni'] in your php file.


text:
Q: Inheriting a backup on a server SO! I've spent 2 days doing this so far and I've gotten so close to accomplishing my goal but I'm on the last step.
I've attached my Time Machine HDD to my landlords Mac mini (So I didn't have to carry it everywhere to backup) and installed server, and enabled Time Machine server.
I put my backup I made when it was plugged in via USB (said 20 hours over the network, USB3 is much faster :P) on the drive in the sparse image for my MBP.
I'm now trying to get Time Machine to "inherit" the backup, which it's not doing even though I'm not getting any errors.
These are the commands I've ran through terminal:
1) sudo tmutil setdestination /Volumes/Backups
2) sudo tmutil associatedisk -a / /Volumes/WD\ My\ Passport/Backups.backupdb/Austen\'s\ MacBook\ Pro/2014-09-15-121229/Macintosh
3) sudo tmutil inheritbackup /Volumes/WD\ My\ Passport/Backups.backupdb/Austen\'s\ MacBook\ Pro
but yet this still occurs in the TM settings:

I really can't figure out what's going on, so any help would be greatly appreciated! Thanks :)

A: Fixed it myself. Made a workflow that does the following:

and ran these commands:
1)sudo tmutil inheritbackup /Volumes/Backup/Backups.backupdb/Austen\'s\ MacBook\ Pro/
2)sudo tmutil associatedisk -a / /Volumes/Backup/Backups.backupdb/Austen\'s\ MacBook\ Pro/2014-09-15-161252/Macintosh


text:
Q: git: add line at the end of an existing commit without using editor Is it possible to auto amend an existing commit with a bug ID retrieved from a script, without launching the editor ?
Something like git commit --amend -C HEAD -s where instead of -s which adds the Signed-off-by: I want to add a Bug: xxxxx

A: git commit --amend -m "$(git log -1 --pretty=%B)" -m "Bug: xxxx"

A: Assuming you want to add the "Bug" line to the end, you could use something like this:
(git show --pretty=format:%B -s HEAD; echo; echo "Bug: 12345") | \
    git commit --amend -F-

A: Use command like this:
git -c core.editor='git interpret-trailers --in-place --trailer=Foo:bar' commit --amend


text:
Q: Como fazer com que o cursor esteja no Text ao inicio do programa? Gostaria de saber como fazer piscar o cursor num objeto tkinter.Text quando eu faço andar a aplicação, porque normalmente nenhum widget é selecionado. Gostaria de ter o mesmo efeito dum terminal quando é ligado, onde se vê o cursor piscar.
Este é o código que estou utilizando, mas não funciona:
self.prompt = tkinter.Text(self.root, bg=self.bg, fg=self.fg, insertbackground=self.fg)

self.prompt.insert(tkinter.END, self.PROMPT_M)
self.prompt.bind('<Return>', self.add_prompt)

self.prompt.pack()
self.prompt.focus()

A: Utilize Entry.focus()
from tkinter import *

root = Tk()
text = Text(root)
entry = Entry(root)
entry.pack()
entry.focus()

root.mainloop()


text:
Q: Variables and semantic search in MediaWiki I am in charge of a MediaWiki with Semantic MediaWiki extension installed. Now, I am trying to perform a semantic search this way:
Defining concepts:
{{#ifeq:{{#BioDB_value:transcript.swissprot_version}}|||
{{#BioDB_store_table:DB
|Uses DB=http://www.uniprot.org/ SwissProt
|Has Alias={{{transcript.transcript_alias}}}
|Uses DB Version={{{transcript.swissprot_version}}}
|Has Hit=http://www.uniprot.org/uniprot/{{{transcript.hit}}}/ {{{transcript.hit}}}
|Has Evalue={{{transcript.evalue}}}
}}}}

Semantic search:
{{#ask:[[DB::{{FULLPAGENAMEE}}]]|?Has Alias|?Uses DB|?Uses DB Version|?Has Hit|?Has Evalue|mainlabel=-|format=template|template=DBList|introtemplate=DBList_Header|outrotemplate=DBList_Footer}}}}

Template:
<includeonly>
|-
| {{{1|}}} || [{{{2|}}}] || {{{3|}}} || [{{{4|}}}] || {{{5|}}}
</includeonly>

In case of Uses DB, it is shown as SwissProt linked to the URL provided. No problem, is what I want. However, this behaviour changes when talking about Has Hit. It is shown as [O34598], without any link attached to that. It seems like it only sees the variable {{{transcript.hit}}} once, which contains O34598. I do not understand why this behaviour change. Whithout variables it works well.
Note: BioDB_value and BioDB_store_table comes from an extension that allows to obtain values from MySQL.