text:
Q: Type Error occurred when creating object on mass action with override I've created a custom module to show order comments on the invoice which works ok with single invoices. When trying to print invoices via the order grid mass action I get this error:
{"0":"Type Error occurred when creating object: Magento\\Sales\\Controller\\Adminhtml\\Order\\Pdfinvoices\\Interceptor","1":"
#1 Magento\\Framework\\ObjectManager\\Factory\\Compiled->create('Magento\\Sales\\Co...', array()) called at [vendor\/magento\/framework\/ObjectManager\/ObjectManager.php:56]
#2 Magento\\Framework\\ObjectManager\\ObjectManager->create('Magento\\Sales\\Co...') called at [vendor\/magento\/framework\/App\/ActionFactory.php:44]
#3 Magento\\Framework\\App\\ActionFactory->create('Magento\\Sales\\Co...') called at [vendor\/magento\/framework\/App\/Router\/Base.php:304]
#4 Magento\\Framework\\App\\Router\\Base->matchAction(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#, array('areaFrontName' => 'adminarea', 'moduleFrontName' => 'sales', 'actionPath' => 'order', 'actionName' => 'pdfinvoices', 'variables' => array('key' => 'a16160358ca3a448...'))) called at [vendor\/magento\/framework\/App\/Router\/Base.php:165]
#5 Magento\\Framework\\App\\Router\\Base->match(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#) called at [vendor\/magento\/framework\/App\/FrontController.php:95]
#6 Magento\\Framework\\App\\FrontController->dispatch(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#) called at [vendor\/magento\/framework\/Interception\/Interceptor.php:58]
#7 Magento\\Framework\\App\\FrontController\\Interceptor->___callParent('dispatch', array(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#)) called at [vendor\/magento\/framework\/Interception\/Interceptor.php:138]
#8 Magento\\Framework\\App\\FrontController\\Interceptor->Magento\\Framework\\Interception\\{closure}(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#) called at [vendor\/magento\/framework\/Interception\/Interceptor.php:153]
#9 Magento\\Framework\\App\\FrontController\\Interceptor->___callPlugins('dispatch', array(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#), array(array('default_store_se...', 'page_cache_from_...', 'storeCookieValid...', 'install', 'configHash'))) called at [generated\/code\/Magento\/Framework\/App\/FrontController\/Interceptor.php:26]
#10 Magento\\Framework\\App\\FrontController\\Interceptor->dispatch(&Magento\\Framework\\App\\Request\\Http#000000004aa3a963000000000d13c128#) called at [vendor\/magento\/framework\/App\/Http.php:136]
#11 Magento\\Framework\\App\\Http->launch() called at [vendor\/magento\/framework\/App\/Bootstrap.php:258]
#12 Magento\\Framework\\App\\Bootstrap->run(&Magento\\Framework\\App\\Http\\Interceptor#000000004aa3a99c000000000d13c128#) called at [index.php:39]
<\/pre>","url":"\/adminarea\/sales\/order\/pdfinvoices\/key\/a16160358ca3a44836acecccac1531300de1f39f164af578cad46aa2f98aa8d6\/","script_name":"\/index.php"}

Here's my module code:
app\code\Denial\InvoiceComments\registration.php
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Denial_InvoiceComments', __DIR__);

app\code\Denial\InvoiceComments\etc\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\Sales\Model\Order\Pdf\Invoice" type="Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice" />
</config>

app\code\Denial\InvoiceComments\etc\module.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Denial_InvoiceComments" setup_version="0.0.1">
    <sequence>
    <module name="Magento_Sales" />
   </sequence>
</module>
</config>

app\code\Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice.php
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Denial\InvoiceComments\Model\Rewrite\Order\Pdf;

use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection;
use Magento\Sales\Model\Order\Pdf\AbstractPdf;
use Magento\Sales\Model\Order\Pdf\Config;

class Invoice extends AbstractPdf
{
/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $_storeManager;

/**
 * @var \Magento\Framework\Locale\ResolverInterface
 */
protected $_localeResolver;

/**
 * @param \Magento\Payment\Helper\Data $paymentData
 * @param \Magento\Framework\Stdlib\StringUtils $string
 * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 * @param \Magento\Framework\Filesystem $filesystem
 * @param Config $pdfConfig
 * @param \Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory
 * @param \Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory
 * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
 * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
 * @param \Magento\Sales\Model\Order\Address\Renderer $addressRenderer
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
 * @param array $data
 *
 * @SuppressWarnings(PHPMD.ExcessiveParameterList)
 */
public function __construct(
    \Magento\Payment\Helper\Data $paymentData,
    \Magento\Framework\Stdlib\StringUtils $string,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Framework\Filesystem $filesystem,
    Config $pdfConfig,
    \Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
    \Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
    \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
    \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
    \Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\Locale\ResolverInterface $localeResolver,
    array $data = []
) {
    $this->_storeManager = $storeManager;
    $this->_localeResolver = $localeResolver;
    parent::__construct(
        $paymentData,
        $string,
        $scopeConfig,
        $filesystem,
        $pdfConfig,
        $pdfTotalFactory,
        $pdfItemsFactory,
        $localeDate,
        $inlineTranslation,
        $addressRenderer,
        $data
    );
}

/**
 * Draw header for item table
 *
 * @param \Zend_Pdf_Page $page
 * @return void
 */
protected function _drawHeader(\Zend_Pdf_Page $page)
{
    /* Add table head */
    $this->_setFontRegular($page, 10);
    $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
    $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
    $page->setLineWidth(0.5);
    $page->drawRectangle(25, $this->y, 570, $this->y - 15);
    $this->y -= 10;
    $page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));

    //columns headers
    $lines[0][] = ['text' => __('Products'), 'feed' => 35];

    $lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];

    $lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];

    $lines[0][] = ['text' => __('Price'), 'feed' => 375, 'align' => 'right'];

    $lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' => 'right'];

    $lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right'];

    $lineBlock = ['lines' => $lines, 'height' => 5];

    $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
    $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
    $this->y -= 20;
}

/**
 * Return PDF document
 *
 * @param array|Collection $invoices
 * @return \Zend_Pdf
 */
public function getPdf($invoices = [])
{
   $this->_beforeGetPdf();
    $this->_initRenderer('invoice');

    $pdf = new \Zend_Pdf();
    $this->_setPdf($pdf);
    $style = new \Zend_Pdf_Style();
    $this->_setFontBold($style, 10);

    foreach ($invoices as $invoice) {
        if ($invoice->getStoreId()) {
            $this->_localeResolver->emulate($invoice->getStoreId());
            $this->_storeManager->setCurrentStore($invoice->getStoreId());
        }

        $page = $this->newPage();
        $order = $invoice->getOrder();
        /* Add image */
        $this->insertLogo($page, $invoice->getStore());
        /* Add address */
        $this->insertAddress($page, $invoice->getStore());
        /* Add head */
        $this->insertOrder(
            $page,
            $order,
            $this->_scopeConfig->isSetFlag(
                self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $order->getStoreId()
            )
        );
        /* Add document text and number */
        $this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
        /* Add table */
        $this->_drawHeader($page);
        /* Add body */
        foreach ($invoice->getAllItems() as $item) {
            if ($item->getOrderItem()->getParentItem()) {
                continue;
            }
            /* Draw item */
            $this->_drawItem($item, $page, $order);
            $page = end($pdf->pages);
        }
        /* Add totals */
        $this->insertTotals($page, $invoice);
        if ($invoice->getStoreId()) {
            $this->_localeResolver->revert();
        }

    foreach ($invoice->getOrder()->getStatusHistoryCollection() as $status){
    $textChunk = wordwrap(strip_tags($status->getComment()), 120, "\n");
    foreach(explode("\n", $textChunk) as $textLine){
            if ($textLine!=='') {
                    $page->drawText(strip_tags(ltrim($textLine)), 35, $this->y, 'UTF-8');
                    $this->y -= 15;
            }
    }
    }
    }
    $this->_afterGetPdf();
    return $pdf;
}

/**
 * Create new page and assign to PDF object
 *
 * @param  array $settings
 * @return \Zend_Pdf_Page
 */
public function newPage(array $settings = [])
{
    /* Add new table head */
    $page = $this->_getPdf()->newPage(\Zend_Pdf_Page::SIZE_A4);
    $this->_getPdf()->pages[] = $page;
    $this->y = 800;
    if (!empty($settings['table_header'])) {
        $this->_drawHeader($page);
    }
    return $page;
}

}

app\code\Denial\InvoiceComments\view\adminhtml\layout\sales_order_invoice_view.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceBlock name="order_comments">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">Denial_InvoiceComments::order/comments/view.phtml</argument>
    </action>
</referenceBlock>

</page>

app\code\Denial\InvoiceComments\view\adminhtml\templates\order\comments\view.phtml
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php if ($_entity = $block->getEntity()): ?>

            <?= /* @escapeNotVerified */ __('Comment Text') ?>

                <textarea name="comment[comment]"
                        class="admin__control-textarea"
                        rows="3"
                        cols="5"
                        id="history_comment"></textarea>

                <?php if ($block->canSendCommentEmail()): ?>

                        <input name="comment[is_customer_notified]"
                            type="checkbox"
                            class="admin__control-checkbox"
                            id="history_notify"
                            value="1" />
                        <?= /* @escapeNotVerified */ __('Notify Customer by Email') ?>

                <?php endif; ?>

                    <input name="comment[is_visible_on_front]"
                        type="checkbox"
                        id="history_visible"
                        class="admin__control-checkbox"
                        value="1" />
                     <?= /* @escapeNotVerified */ __('Visible on Storefront') ?>

                <?= $block->getChildHtml('submit_button') ?>

 Order Comments

<?php foreach ($_entity->getOrder()->getStatusHistoryCollection() as $status): ?>
    <?php  if ($status->getComment()): ?>
    <?= /* @noEscape */ $block->formatDate($status->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?>
            <?= /* @noEscape */ $block->formatTime($status->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?>

                <?= /* @escapeNotVerified */ __('Customer') ?>
                <?php if ($status->getIsCustomerNotified()): ?>
                    <?= /* @escapeNotVerified */ __('Notified') ?>
                <?php else: ?>
                    <?= /* @escapeNotVerified */ __('Not Notified') ?>
                <?php endif; ?>

<?= $block->escapeHtml($status->getComment(), ['b', 'br', 'strong', 'i', 'u', 'a']) ?>

    <?php endif; ?>
<?php endforeach; ?>

 Invoice Comments

        <?php foreach ($_entity->getCommentsCollection(true) as $_comment): ?>

                <?= /* @noEscape */ $block->formatDate($_comment->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?>
                <?= /* @noEscape */ $block->formatTime($_comment->getCreatedAt(), \IntlDateFormatter::MEDIUM) ?>

                    <?= /* @escapeNotVerified */ __('Customer') ?>
                    <?php if ($_comment->getIsCustomerNotified()): ?>
                        <?= /* @escapeNotVerified */ __('Notified') ?>
                    <?php else: ?>
                        <?= /* @escapeNotVerified */ __('Not Notified') ?>
                    <?php endif; ?>

<?= $block->escapeHtml($_comment->getComment(), ['b', 'br', 'strong', 'i', 'u', 'a']) ?>

        <?php endforeach; ?>

<?php endif; ?>

What have I missed?
More info from the logs:
[2019-12-05 09:58:31] main.CRITICAL: Type Error occurred when creating object: Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices\Interceptor, Argument 6 passed to Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices\Interceptor::__construct() must be an instance of Magento\Sales\Model\Order\Pdf\Invoice, instance of Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice given, called in /home/sitename/public_html/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 116 [] []
[2019-12-05 09:58:31] main.ERROR: Type Error occurred when creating object: Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices\Interceptor [] []

How do I change the required instance name?

A: Please replace following code in

Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice.php file

 <?php
    /**
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
    namespace Denial\InvoiceComments\Model\Rewrite\Order\Pdf;

    use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection;
    use Magento\Sales\Model\Order\Pdf\AbstractPdf;
    use Magento\Sales\Model\Order\Pdf\Config;
    use Magento\Sales\Model\Order\Pdf\Invoice as MagentoInvoice;

    class Invoice extends MagentoInvoice
    {

        /**
         * Draw header for item table
         *
         * @param \Zend_Pdf_Page $page
         * @return void
         */
        protected function _drawHeader(\Zend_Pdf_Page $page)
        {
            /* Add table head */
            $this->_setFontRegular($page, 10);
            $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
            $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
            $page->setLineWidth(0.5);
            $page->drawRectangle(25, $this->y, 570, $this->y - 15);
            $this->y -= 10;
            $page->setFillColor(new \Zend_Pdf_Color_Rgb(0, 0, 0));

            //columns headers
            $lines[0][] = ['text' => __('Products'), 'feed' => 35];

            $lines[0][] = ['text' => __('SKU'), 'feed' => 290, 'align' => 'right'];

            $lines[0][] = ['text' => __('Qty'), 'feed' => 435, 'align' => 'right'];

            $lines[0][] = ['text' => __('Price'), 'feed' => 375, 'align' => 'right'];

            $lines[0][] = ['text' => __('Tax'), 'feed' => 495, 'align' => 'right'];

            $lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right'];

            $lineBlock = ['lines' => $lines, 'height' => 5];

            $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
            $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
            $this->y -= 20;
        }

        /**
         * Return PDF document
         *
         * @param array|Collection $invoices
         * @return \Zend_Pdf
         */
        public function getPdf($invoices = [])
        {
            $this->_beforeGetPdf();
            $this->_initRenderer('invoice');

            $pdf = new \Zend_Pdf();
            $this->_setPdf($pdf);
            $style = new \Zend_Pdf_Style();
            $this->_setFontBold($style, 10);

            foreach ($invoices as $invoice) {
                if ($invoice->getStoreId()) {
                    $this->_localeResolver->emulate($invoice->getStoreId());
                    $this->_storeManager->setCurrentStore($invoice->getStoreId());
                }

                $page = $this->newPage();
                $order = $invoice->getOrder();
                /* Add image */
                $this->insertLogo($page, $invoice->getStore());
                /* Add address */
                $this->insertAddress($page, $invoice->getStore());
                /* Add head */
                $this->insertOrder(
                    $page,
                    $order,
                    $this->_scopeConfig->isSetFlag(
                        self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                        $order->getStoreId()
                    )
                );
                /* Add document text and number */
                $this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
                /* Add table */
                $this->_drawHeader($page);
                /* Add body */
                foreach ($invoice->getAllItems() as $item) {
                    if ($item->getOrderItem()->getParentItem()) {
                        continue;
                    }
                    /* Draw item */
                    $this->_drawItem($item, $page, $order);
                    $page = end($pdf->pages);
                }
                /* Add totals */
                $this->insertTotals($page, $invoice);
                if ($invoice->getStoreId()) {
                    $this->_localeResolver->revert();
                }

                foreach ($invoice->getOrder()->getStatusHistoryCollection() as $status){
                    $textChunk = wordwrap(strip_tags($status->getComment()), 120, "\n");
                    foreach(explode("\n", $textChunk) as $textLine){
                        if ($textLine!=='') {
                            $page->drawText(strip_tags(ltrim($textLine)), 35, $this->y, 'UTF-8');
                            $this->y -= 15;
                        }
                    }
                }
            }
            $this->_afterGetPdf();
            return $pdf;
        }

        /**
         * Create new page and assign to PDF object
         *
         * @param  array $settings
         * @return \Zend_Pdf_Page
         */
        public function newPage(array $settings = [])
        {
            /* Add new table head */
            $page = $this->_getPdf()->newPage(\Zend_Pdf_Page::SIZE_A4);
            $this->_getPdf()->pages[] = $page;
            $this->y = 800;
            if (!empty($settings['table_header'])) {
                $this->_drawHeader($page);
            }
            return $page;
        }
}

A: Here is the problem,
As per log sixth argument of Magento\Sales\Controller\Adminhtml\Order\Pdfinvoices must be type of Magento\Sales\Model\Order\Pdf\Invoice. You have defined preference for Magento\Sales\Model\Order\Pdf\Invoice. So, magetno will use Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice instead of Magento\Sales\Model\Order\Pdf\Invoice.
And here is the solution,
 Extend Denial\InvoiceComments\Model\Rewrite\Order\Pdf\Invoice to Magento\Sales\Model\Order\Pdf\Invoice and override necessary code.
class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    \\ Your code here
}


text:
Q: Is it possible to create a local repository that will clone GitHub's? Let me explain,
Is it possible to create a local git directory(lets call it my_github) that will be the clone of:

https://github.com/USER_NAME?tab=repositories

And then if i'll be interested in creating a new repository, i'll be able just to create a new folder in my_github, and just push it, and it will be pushed as a new repository.
And then my local directory will look like that:
~/my_github/new_repo
and when i'll push it, it will create github.com/USER_NAME/new_repo.
I tried to do that with https://github.com/USER_NAME/USER_NAME as my remote origin but it didn't work because it adds the files into the USER_NAME/USER_NAME repository, but I want it to add it to /USER_NAME.
I hope I was clear enough.
I just want to create repositories quickly and easier and push it to my github to the front page of my profile and not into some other repository.
The other way is to manually create a repository each time I want to create one through the web explorer, and link it to the local one. But I want to avoid this and want my ~/my_github/ directory to be synced with github.com/USER_NAME.
Thanks.

A: I don't think that is possible. You are asking for gitto do things specific to GitHub.
So I could propose you a workaround:

I just want to create repositories quickly and easier and push it to my github

Perhaps have a look at the official GitHub cli:
https://cli.github.com/manual/gh_repo_create
And you could still use gitor shell alias to make the use suits your need:
https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases
Especially last paragraph.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the statement query Find the course with the second maximum number of prerequisites. You should return the result as the name of the course and the number of the prerequisites in this question. Please consider that there might be some courses, which may not have any prerequisites.
prereq table
| course_id      | prereq_id      |
| BIO-301        | BIO-101        |
| BIO-399        | BIO-101        |
| CS-190         | CS-101         |
| CS-315         | CS-101         |
| CS-319         | CS-101         |
| CS-347         | CS-101         |
| EE-202         | EE-181         |
| FIN-201        | MTH-101        |
| MTH-102        | MTH-101        |
| MTH-221        | MTH-101        |
| PHY-101        | MTH-101        |
| MTH-201        | MTH-102        |
| MTH-221        | MTH-102        |
| PHY-550        | MTH-102        |
| PHY-550        | MTH-221        |
| MU-199         | MU-101         |
| CS-319         | PHY-101        |
| EE-181         | PHY-101        |
| EE-202         | PHY-101        |
| PHY-550        | PHY-101        |
| NULL           | NULL           |

A: This can be solved with select substring and select max query. For your reference, you can see this
http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php
You can use this query to solve your problem :
select course_id, prereq_id from prereq_table where substring(prereq_id,5,1)=(select max(substring(prereq_id,5,1)) from prereq_table)

I fill my table with this

and by using the query above, it will return this


text:
Q: message: "Internal server error" when try to access aws gateway api Created Lambda Hello world function using Node.js and created API GateWay trigger for Get call, tried the URL to access Lambda function,  getting below error.
message: "Internal server error".
(very new to AWS)

A: For accessing dynamodb through lambda function from api gateway it needs:

*

*Create a role in AWS console that have access to dynamodb operations.

*Create a lambda function and assign the above created role to your lambda function.

*Create a api from API gateway in AWS management console and allow it to access to your lambda function.

*In order for your api to show a proper response the return type of lambda function should be a specific format i.e :
return {
  "statusCode": 200,
  "body": json.dumps(your response)
}

A: You need to pass the statusCode after executing the Lambda function. If you don't pass it the API Gateway will trigger an error 502 Bad Gateway by default.
message = {
   'message': 'Execution started successfully!'
}
return {
    'statusCode': 200,
    'headers': {'Content-Type': 'application/json'},
    'body': json.dumps(message)
}

EDIT: This sample is for Python. For node.js you just need to handle callback, the message is basically the same.
callback(null, {
    statusCode: 200,
    body: JSON.stringify(message),
    headers: {'Content-Type': 'application/json'}
});

A: It's already explained above, but my problem was this worked for me with just calling the lambda:
exports.handler = async (event) => {
    return "gugus"
};

So all the tests in lambda were fine. The logs looked fine too. Just the API response was not ok.
To call it with the API gateway it needs something like this:
exports.handler = async (event) => {
...
    var res ={
        "statusCode": 200,
        "headers": {
            "Content-Type": "*/*"
        }
    };
    res.body = "gugus";
    return res;
};

A: I had this problem using API Gateway + Lambda. In my case the problem was simply a permission issue. I was using stages in my API.
I had to execute
aws lambda add-permission --function-name X --source-arn "X" --principal apigateway.amazonaws.com --statement-id X --action lambda:InvokeFunction

Hope this helps.

A: Be sure to pass the body across as a string in the response.  If it's an object it will fail and give you the error you see.  See here for more - http://www.awslessons.com/2017/lambda-api-gateway-internal-server-error/

A: Don't forget to click Deploy API under AWS API Gateway. Without it, change doesn't work.

A: In my case the problem was that I created API Gateway from Lambda. In this case no method was created on the API Gateway side of REST API.
Fixed by going to API Gateway, create method manually (GET), attach Lambda function, and (!) Deploy changes.
After this link started to work.

A: I had this problem, but in my case I was using API Gateway and java lambda function. When looking in cloudwatch there was no error, every things look fine. The problem happen when API Gateway is attempting to render the response.
In my case, I had in my response object, the statusCode which was not an int while API gateway need it to be a int.
This
    private final ResponseCode statusCode;
    private final String body;
    private final Map<String, String> headers;
    private final boolean isBase64Encoded;

After I change statusCode to int
    private final int statusCode;

This works

A: callback(null, {
    statusCode: 200,
    body: JSON.stringify(message),
    headers: {'Content-Type': 'application/json'}
});

This worked for me perfectly

A: This error indicates that there was a problem with the configuration of the API. If you enable CloudWatch Logs you can see more information: https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cloudwatch-logs/

A: In my case spelling of headers is wrong, it was 'header' in place of 'headers' so make sure you have the right JSON response body.

A: Sometimes CloudWatch logs nothing for this error. To see the error details go to the Lambdas page, click on the Test tab, and execute your function with a test event. You should see what CloudWatch isn't showing.

A: When returning JSON body, added isBase65Encoded = False which solved it, this is actually happening when using Proxy Integration on API Gateway,
so this should work:
import json
return {
        "statusCode": 200,
        "headers":{'Content-Type': 'application/json'},
        "body": json.dumps(json_body),
        "isBase64Encoded": False
    }

A: Try increasing the function timeout.
Configuration (Tab) -> General Configuration -> Edit -> Timeout


text:
Q: Alphabetical Sorting is backwards using string.compare() I have a function that adds a word to a linked list at the appropriate place in the alphabet. It should be sorted A-Z, but for some reason it's the other way around. I think the issue is I'm using string.compare() wrong, but it could be something else. It's probably an easy fix, I've just been staring at it for a while and would appreciate a new perspective!
void LinkedList::addWord( const string& theWord )
{
    ListNode* toAdd = new ListNode(theWord, NULL);

    if( !mpHead ){
        mpHead = toAdd;
        return;
    }

    if(mpHead->word.compare(theWord) < 0){
        toAdd->pNextNode = mpHead;
        mpHead = toAdd;
        return;
    }

    if(mpHead->pNextNode == NULL){
        mpHead->pNextNode = toAdd;
        return;
    }

    ListNode* pCurrent = mpHead;
    ListNode* pCurrentNext = mpHead->pNextNode;

    while( pCurrent->pNextNode->word.compare(theWord) > 0 )
    {
        pCurrent = pCurrentNext;
        pCurrentNext = pCurrentNext->pNextNode;
    }

    toAdd->pNextNode = pCurrent->pNextNode;
    pCurrent->pNextNode = toAdd;
}

A: just use std::set.
#include <set>
#include <string>
// ...
std::set<std::string> s;
s.insert("foo");
s.insert("fred");
// ...

with std::list (linked list + duplicates allowed):
#include <list>
#include <algorithm>
// ...
std::list<std::string> l;
l.insert(std::lower_bound(l.begin(), l.end(), "foo"), "foo");
l.insert(std::lower_bound(l.begin(), l.end(), "fred"), "fred");
l.insert(std::lower_bound(l.begin(), l.end(), "foo"), "foo");
// ...

note: there's also std::multiset within <set>, which also allows duplicates.

A: It seems you've swapped the arguments of compare. Think of a.compare(b) < 0 as equivalent to a < b. Then you'll see you're doing:
if (Head < theWord) { insert theWord before Head; }

You probably meant if (theWord < Head) instead, so the real code would be:
if(theWord.compare(mpHead->word) < 0){
    toAdd->pNextNode = mpHead;
    mpHead = toAdd;
    return;
}

// ...

while( theWord.compare(pCurrent->pNextNode->word) > 0 )
{
    pCurrent = pCurrentNext;
    pCurrentNext = pCurrentNext->pNextNode;
}

Of course, since you're only using the result of each compare() once, you could use the operator < directly instead:
if(theWord < mpHead->word)

//...

while( theWord > pCurrent->pNextNode->word)


text:
Q: Does naive bayes classifier perform text annotation? Does naive bayes classifier perform text annotation (sequence tagging)?
If yes, i need a tutorial please.
What do you think about MALLET for naive baies?

A: Naive Bayes is a form of classifier that makes a prediction about one variable, for example a label for a document. In a sequence tagging problem, you are making predictions about a sequence of variables: one for each token.
You can do this by treating each token as its own independent classification problem, or you can use a model that makes predictions for the whole sequence jointly, with the decision for one token affecting the decision for neighboring tokens.
The sequence equivalent for Naive Bayes is a Hidden Markov Model. An equivalent classifier/sequence-tagger pair is logistic regression and conditional random fields (CRFs). Mallet implements all of these, as do many other systems.


text:
Q: Trouble connecting to Microsoft SQL Server with Windows Authentication I am building a flask project for internal use at my company. I start by using flask and postgre and used sqlalchemy and set up that connection using the model formats like below:
app = Flask(__name__)

app.config.from_object('config')

db = SQLAlchemy(app)

and that worked well. Now for security reasons we are switching to using Microsoft SQL Server with window authentication on an IIS server but i am having a lot of trouble connecting.
I changed the database URI to
SQLALCHEMY_DATABASE_URI = "mssql+pyodbc://server/database"

I've checked the SQL Sever configuration and I am pretty sure that is correct. However I get the error
psycopg2.OperationalError: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

I have researched this issue and have used the pool_pre_ping solution but I get the same error (shown below)
SQLALCHEMY_ENGINE_OPTIONS = {"pool_pre_ping": True}

I have seen a lot of answers around this stuff that use the sqlalchemy.engine stuff but if possible I was hoping to use all of the db.models I have already written out but if that's not possible I can rewrite some stuff. Any help appreciated.

A: Windows Authentication will become a problem when you deploy to production. I recommend creating a SQL user to connect to your database.
Try this connection string:
mssql+pyodbc://<UID>:<PWD>@<SERVER>/<DATABASE>?driver=ODBC+Driver+17+for+SQL+Server;Trusted_Connection=no

Also make sure you've installed pyodbc msft docs
pip install pyodbc


text:
Q: buffon needle experiment Hi, what are the "best" values for lenght of needle (l) and distance between paralles (d) for an accurate approximation of pi? Does it have to be l-d-1.0 or ld? Thanx

A: Indeed, the result of the experiment is strongly dependent on arithmetic properties of the parameters - the ratio $\rho$ of needle's lenght to the distance between parallel lines, and of course, the number $N$ of needles. There is a funny story about that. In 1901 the Italian mathematician  Mario Lazzarini claimed to have obtained an experimental value of $\pi$ with 7 correct digits, using 3408 needles, and a ratio $\rho=5/6$ (a harmless choice, apparently). That was quite embarrassing, as it was quite clear he had cheated -after and before Lozzerini's experiment, everybody else, even with larger numbers of needles, never got a better result than 3.13 or 3.15., and today Lazzerini's experiment it is sometimes reported as a case of false. The point is a little more subtle: with the parameters he had taken, he was quite likely to obtain as approximantion the ratio 355/113 (the lucky number being 1808 intersections). My personal guess is that he somehow meant to mock the other scientists, physicists or naturalists, who performed Buffon's experiment ignoring the arithmetic axpect of the matter. One can easily do even more striking experiments, of course: with a convenient (irrational) choice of the ratio, and just 2 or 3 needles, you have a good chance to obtain an exact value of $\pi$ from Buffon's experiment...

A: I'm guessing that the longer the needle the better (meaning, highest $\ell/d$ ratio). It seems like you'll get significant experimental issues from the cases where the needle just barely crosses-or-doesn't-cross a line, and if your needle is long enough to cross lots of lines then this becomes less relevant. Probably you want to color the lines so every tenth and every hundredth are a different color, the better to accurately count them.

A: The question is well defined for estimating $\frac 1 \pi$, but not for estimating $\pi$.
If $l>d$, you need to evaluate $cos^{-1}$ which requires knowledge of $\pi$, otherwise the variance of the estimator decreases with$ \frac l d$, so you'd "practically" settle for $l=d$.

A: The naive estimator is biased. If there are $N$ trials and $i$ success, a Rao-Blackwellisation of the naive estimator gives the unbiased estimator $\frac{2l}{d}\left(\frac{n}{i}+\frac{1}{i}\right)$ (to be fair this hides an assumption for a uniform prior for the probability of crossing, which induces a weird prior on $\pi$).
One can look at the variance of the estimator conditional on obtaining one success. The strategy is then to set $l=d$. Intuitively this makes sense, we want the term in $1/i$ to be as small as possible. Though for $n$ small enough, the prior dominates and the optimum is actually achieved for a small value of $2l/(d\pi)$.


text:
Q: Embedding Uglified Javascript into a Jade template I have a project that uses grunt to build my site from a Jade template and also builds and concatenates JavaScript using an uglify task (grunt-contrib-uglify).
As I am building a single page app, rather than link to the external uglified version of my JavaScript I would like to build the uglified version into my jade template and save on the extra http request.
Within my grunt file, how can I get uglify to pass its content into the my Jade template rather than build it as an external file?
Any thoughts welcome.

A: One approach would be to simply pass the uglified javascript string as data for your jade template. For the jade task, use a function for your data key which reads and returns the contents of the uglified file (using grunt.file.read for example).
Obviously ensure your uglified task is run before your jade task.


text:
Q: How to convert this AppInventor Blocks to Kotlin Code? Any Idea Hi there I want to convert those blocks from the AppInventor project to Android Studio Project Using Kotiln as my programing language but I am very new to android development can anyone help me with that?

What this app does is opening webview and reload my webpage URL at a randomly generated time.
What I tried so far!
package com.technosoftkpk.y_view

import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myWebView: WebView = findViewById(R.id.webview)
        myWebView.setWebViewClient(WebViewClient())
        myWebView.loadUrl("https://technosoft.pk")
        val webSettings = myWebView.settings
        webSettings.displayZoomControls = true
        webSettings.javaScriptEnabled = true

    }
}

A: Would something like this work? This will randomly wait between 0 and 5 seconds. (Add the code at the end of onCreate):
import kotlin.concurrent.thread
import kotlin.random.Random

thread {
    while (true) {
        Thread.sleep(Random.nextLong(5000))
        runOnUiThread { myWebView.reload() }
    }
}

This might look complicated, but we need to make a new thread to avoid blocking the UI thread and allowing user input. But then the reloading needs to happen on the UI thread again. An alternative would be to use postDelayed.


text:
Q: How can i add a sheet in another workbook that not active can someone help me, i try to write a code with 2 file open ABC.xlsm and KM.xlsm
.Thisworkbook is ABC.xlsm
sub copy()
Dim sh As Workbook
Dim tensheet As String
Set sh = Workbooks("KM.xlsm")
tensheet = Range("O2").Value
sh.Sheets.Add(After:=Sheets(Sheets.Count)).Name = tensheet
end sub

i get this error "runtime error 1004 application-defined or object-defined error"
this code will run if i add "sh.active" before add a new sheet but i dont want to. Any help?

A: Try fully qualifying Sheets and Sheets.Count.
Sub AddSheet()
Dim sh As Workbook
Dim tensheet As String

    Set sh = Workbooks("KM.xlsm")
    tensheet = Range("O2").Value
    sh.Sheets.Add(After:=sh.Sheets(sh.Sheets.Count)).Name = tensheet

End Sub


text:
Q: What pattern do you use for executing generic steps on a pool of machines I'm trying to figure out how to model my build process in hudson.  At present most of our hudson builds are somewhat hard coded in that the build process is series of steps and we have one process per branch.
I have another build system that has many active branches and each build has a series of integration tests which require a suit of machines to execute.   As I migrate from the home grown to hudson I'm not quite sure what's the right way to model this to keep sustainability costs and build times to a minimum
Here's my basic build:

*

*create workspace

*compile, link, package

*transfer artifacts to test systems

*invoke test harness on multiple systems to handle installation and acceptance tests

*collect results

*publish results

I'd like the integration part to be a group of generic machines (perhaps an elastic group) which can handle integration-tests for any branch.  I want to run as much in parallel as possible to keep my build times low.  It looks like the best way to execute in parallel on hudson is to break up steps into jobs and use the Parameterized Trigger Plugin to customize the generic jobs.
So, i'd have two main jobs: build, test
I could have on build job per branch and a generic test job.  The build job would use Parameterized Trigger Plugin to call the test job and provide the location of the build artifacts.  The test job would call a series of jobs in parallel passing down parameters for branch, artifact.
test
   test-client-install (params: artifact location, branch)
   test-server-install (params: artifact location, branch)
   test-run (params: client machine, server machine)
   join - collect results (params: client machine, server machine)
Each of the test-* jobs would pull a slave out of the group of slaves and execute.  I'm not quite sure how to inform the slaves running the client and server jobs how to find each other nor am I sure how to reserve them from the pool and release them back into it.
I guess, I could have a write properties to a common share and have the sub jobs use that for inter-job communication.
Has anyone created this kind of complex setup in hudson, or is this usually done in another system with which hudson interacts (hudson + STAF with STAF managing resources)?

A: A few thoughts. The fewer jobs you have, the easier it is to maintain them. The more jobs you have, the more flexible you are and you can run more in parallel. Since you emphasized fast build times, have a look at the join plugin, to run a few jobs in parallel and when all of these are finished to go on with another job in that chain.
If your server is big enough, you can experiment a little bit with the clone workspace plugin. It will help you to reduce the need for manual copying files between jobs and the need for the parametrized trigger plugin.
Reserving a slave is easy. You can group the slaves with labels. In your job you define what label you node has to have in order to execute your job. A node can have more than one label and your job can be bound to more than one label. This way, Hudson decides where to put your job depending on availability. If your slaves have more than one build queue, they can run two jobs in parallel. I haven't used the locks-and-latches plugin for synchronizing across nodes. So I don't know if locks are only per node or for the whole Hudson installation. Latches are not supported yet. If you need to ensure that two jobs need to run on the same slave, try to combine them, otherwise you will lose the advantage of Hudson to distribute your jobs freely over the available nodes.


text:
Q: How to count signups and cancellations with a sql query efficiently (postgresql 9.0) Imagine an account table that looks like this:
   Column   |            Type             | Modifiers
------------+-----------------------------+-----------
 id         | bigint                      | not null
 signupdate | timestamp without time zone | not null
 canceldate | timestamp without time zone |

I want to get a report of the number of signups and cancellations by month.
It is pretty straight-forward to do it in two queries, one for the signups by month and then one for the cancellations by month. Is there an efficient way to do it in a single query? Some months may have zero signups and cancellations, and should show up with a zero in the results.
With source data like this:
id    signupDate     cancelDate
 1    2012-01-13
 2    2012-01-15     2012-02-05
 3    2012-03-01     2012-03-20

we should get the following results:
Date      signups    cancellations
2012-01         2                0
2012-02         0                1
2012-03         1                1

I'm using postgresql 9.0
Update after the first answer:
Craig Ringer provided a nice answer below. On my data set of approximately 75k records, the first and third examples performed similarly. The second example seems to have an error somewhere, it returned incorrect results.
Looking at the results from an explain analyze (and my table does have an index on signup_date), the first query returns:
Sort  (cost=2086062.39..2086062.89 rows=200 width=24) (actual time=863.831..863.833 rows=20 loops=1)
  Sort Key: m.m
  Sort Method:  quicksort  Memory: 26kB
  InitPlan 2 (returns $1)
    ->  Result  (cost=0.12..0.13 rows=1 width=0) (actual time=0.063..0.064 rows=1 loops=1)
          InitPlan 1 (returns $0)
            ->  Limit  (cost=0.00..0.12 rows=1 width=8) (actual time=0.040..0.040 rows=1 loops=1)
                  ->  Index Scan using account_created_idx on account  (cost=0.00..8986.92 rows=75759 width=8) (actual time=0.039..0.039 rows=1 loops=1)
                        Index Cond: (created IS NOT NULL)
  InitPlan 3 (returns $2)
    ->  Aggregate  (cost=2991.39..2991.40 rows=1 width=16) (actual time=37.108..37.108 rows=1 loops=1)
          ->  Seq Scan on account  (cost=0.00..2612.59 rows=75759 width=16) (actual time=0.008..14.102 rows=75759 loops=1)
  ->  HashAggregate  (cost=2083057.21..2083063.21 rows=200 width=24) (actual time=863.801..863.806 rows=20 loops=1)
        ->  Nested Loop  (cost=0.00..2077389.49 rows=755696 width=24) (actual time=37.238..805.333 rows=94685 loops=1)
              Join Filter: ((date_trunc('month'::text, a.created) = m.m) OR (date_trunc('month'::text, a.terminateddate) = m.m))
              ->  Function Scan on generate_series m  (cost=0.00..10.00 rows=1000 width=8) (actual time=37.193..37.197 rows=20 loops=1)
              ->  Materialize  (cost=0.00..3361.39 rows=75759 width=16) (actual time=0.004..11.916 rows=75759 loops=20)
                    ->  Seq Scan on account a  (cost=0.00..2612.59 rows=75759 width=16) (actual time=0.003..24.019 rows=75759 loops=1)
Total runtime: 872.183 ms

and the third query returns:
Sort  (cost=1199951.68..1199952.18 rows=200 width=8) (actual time=732.354..732.355 rows=20 loops=1)
  Sort Key: m.m
  Sort Method:  quicksort  Memory: 26kB
  InitPlan 4 (returns $2)
    ->  Result  (cost=0.12..0.13 rows=1 width=0) (actual time=0.030..0.030 rows=1 loops=1)
          InitPlan 3 (returns $1)
            ->  Limit  (cost=0.00..0.12 rows=1 width=8) (actual time=0.022..0.022 rows=1 loops=1)
                  ->  Index Scan using account_created_idx on account  (cost=0.00..8986.92 rows=75759 width=8) (actual time=0.022..0.022 rows=1 loops=1)
                        Index Cond: (created IS NOT NULL)
  InitPlan 5 (returns $3)
    ->  Aggregate  (cost=2991.39..2991.40 rows=1 width=16) (actual time=30.212..30.212 rows=1 loops=1)
          ->  Seq Scan on account  (cost=0.00..2612.59 rows=75759 width=16) (actual time=0.004..8.276 rows=75759 loops=1)
  ->  HashAggregate  (cost=12.50..1196952.50 rows=200 width=8) (actual time=65.226..732.321 rows=20 loops=1)
        ->  Function Scan on generate_series m  (cost=0.00..10.00 rows=1000 width=8) (actual time=30.262..30.264 rows=20 loops=1)
        SubPlan 1
          ->  Aggregate  (cost=2992.34..2992.35 rows=1 width=8) (actual time=21.098..21.098 rows=1 loops=20)
                ->  Seq Scan on account  (cost=0.00..2991.39 rows=379 width=8) (actual time=0.265..20.720 rows=3788 loops=20)
                      Filter: (date_trunc('month'::text, created) = $0)
        SubPlan 2
          ->  Aggregate  (cost=2992.34..2992.35 rows=1 width=8) (actual time=13.994..13.994 rows=1 loops=20)
                ->  Seq Scan on account  (cost=0.00..2991.39 rows=379 width=8) (actual time=2.363..13.887 rows=998 loops=20)
                      Filter: (date_trunc('month'::text, terminateddate) = $0)
Total runtime: 732.487 ms

This certainly makes it appear that the third query is faster, but when I run the queries from the command-line using the 'time' command, the first query is consistently faster, though only by a few milliseconds.
Surprisingly to me, running two separate queries (one to count signups and one to count cancellations) is significantly faster. It took less than half the time to run, ~300ms vs ~730ms. Of course that leaves more work to be done externally, but for my purposes it still might be the best solution. Here are the single queries:
select
    m,
    count(a.id) as "signups"
from
    generate_series(
        (SELECT date_trunc('month',min(signup_date)) FROM accounts),
        (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
        interval '1 month') as m
INNER JOIN accounts a ON (date_trunc('month',a.signup_date) = m)
group by m
order by m
;

select
    m,
    count(a.id) as "cancellations"
from
    generate_series(
        (SELECT date_trunc('month',min(signup_date)) FROM accounts),
        (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
        interval '1 month') as m
INNER JOIN accounts a ON (date_trunc('month',a.cancel_date) = m)
group by m
order by m
;

I have marked Craig's answer as correct, but if you can make it faster, I'd love to hear about it

A: Here are three different ways to do it. All depend on generating a time series then scanning it. One uses subqueries to aggregate data for each month. One joins the table twice against the series with different criteria. An alternate form does a single join on the time series, retaining rows that match either start or end date, then uses predicates in the counts to further filter the results.
EXPLAIN ANALYZE will help you pick which approach works best for your data.
http://sqlfiddle.com/#!12/99c2a/9
Test setup:
CREATE TABLE accounts
    ("id" int, "signup_date" timestamp, "cancel_date" timestamp);

INSERT INTO accounts
    ("id", "signup_date", "cancel_date")
VALUES
    (1, '2012-01-13 00:00:00', NULL),
    (2, '2012-01-15 00:00:00', '2012-02-05'),
    (3, '2012-03-01 00:00:00', '2012-03-20')
;

By single join and filter in count:
SELECT m,
  count(nullif(date_trunc('month',a.signup_date) = m,'f')),
  count(nullif(date_trunc('month',a.cancel_date) = m,'f'))
FROM generate_series(
  (SELECT date_trunc('month',min(signup_date)) FROM accounts),
  (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
  INTERVAL '1' MONTH
) AS m
INNER JOIN accounts a ON (date_trunc('month',a.signup_date) = m OR date_trunc('month',a.cancel_date) = m)
GROUP BY m
ORDER BY m;

By joining the accounts table twice:
SELECT m, count(s.signup_date) AS n_signups, count(c.cancel_date) AS n_cancels
FROM generate_series(
  (SELECT date_trunc('month',min(signup_date)) FROM accounts),
  (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
  INTERVAL '1' MONTH
) AS m LEFT OUTER JOIN accounts s ON (date_trunc('month',s.signup_date) = m) LEFT OUTER JOIN accounts c ON (date_trunc('month',c.cancel_date) = m)
GROUP BY m
ORDER BY m;

Alternately, using subqueries:
SELECT m, (
  SELECT count(signup_date)
  FROM accounts
  WHERE date_trunc('month',signup_date) = m
) AS n_signups, (
  SELECT count(signup_date)
  FROM accounts
  WHERE date_trunc('month',cancel_date) = m
)AS n_cancels
FROM generate_series(
  (SELECT date_trunc('month',min(signup_date)) FROM accounts),
  (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
  INTERVAL '1' MONTH
) AS m
GROUP BY m
ORDER BY m;

A: New answer after update.
I'm not shocked that you get better results from two simpler queries; sometimes it's simply more efficient to do things that way. However, there was an issue with my original answer that will've signficicantly impacted performance.
Erwin accurately pointed out in another answer that Pg can't use a simple b-tree index on a date with date_trunc, so you're better off using ranges. It can use an index created on the expression date_trunc('month',colname) but you're better off avoiding the creation of another unnecessary index.
Rephrasing the single-scan-and-filter query to use ranges produces:
SELECT m,
  count(nullif(date_trunc('month',a.signup_date) = m,'f')),
  count(nullif(date_trunc('month',a.cancel_date) = m,'f'))
FROM generate_series(
  (SELECT date_trunc('month',min(signup_date)) FROM accounts),
  (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
  INTERVAL '1' MONTH
) AS m
INNER JOIN accounts a ON (
  (a.signup_date >= m AND a.signup_date < m + INTERVAL '1' MONTH)
  OR (a.cancel_date >= m AND a.cancel_date < m + INTERVAL '1' MONTH))
GROUP BY m
ORDER BY m;

There's no need to avoid date_trunc in non-indexable conditions, so I've only changed to use interval ranges in the join condition.
Where the original query used a seq scan and materialize, this now uses a bitmap index scan if there are indexes on signup_date and cancel_date.
In PostgreSQL 9.2 better performance may possibly be gained by adding:
CREATE INDEX account_signup_or_cancel ON accounts(signup_date,cancel_date);

and possibly:
CREATE INDEX account_signup_date_nonnull
ON accounts(signup_date) WHERE (signup_date IS NOT NULL);

CREATE INDEX account_cancel_date_desc_nonnull
ON accounts(cancel_date DESC) WHERE (cancel_date IS NOT NULL);

to allow index-only scans. It's hard to make solid index recommendations without the actual data to test with.
Alternately, the subquery based approach with improved indexable filter condition:
SELECT m, (
  SELECT count(signup_date)
  FROM accounts
  WHERE signup_date >= m AND signup_date < m + INTERVAL '1' MONTH
) AS n_signups, (
  SELECT count(cancel_date)
  FROM accounts
  WHERE cancel_date >= m AND cancel_date < m + INTERVAL '1' MONTH
) AS n_cancels
FROM generate_series(
  (SELECT date_trunc('month',min(signup_date)) FROM accounts),
  (SELECT date_trunc('month',greatest(max(signup_date),max(cancel_date))) FROM accounts),
  INTERVAL '1' MONTH
) AS m
GROUP BY m
ORDER BY m;

will benefit from ordinary b-tree indexes on signup_date and cancel_date, or from:
CREATE INDEX account_signup_date_nonnull
ON accounts(signup_date) WHERE (signup_date IS NOT NULL);

CREATE INDEX account_cancel_date_nonnull
ON accounts(cancel_date) WHERE (cancel_date IS NOT NULL);

Remember that every index you create imposes a penalty on INSERT and UPDATE performance, and competes with other indexes and help data for cache space. Try to create only indexes that make a big difference and are useful for other queries.


text:
Q: How can i have multiple mappers and reducers? I have this code in which i have set one mapper and one reducer.I want to include one more mapper and a reducer for doing further jobs.
The problem is that i have to take the output file of the first map reduce job as the input to the next map reduce job.Is it possible to do that?if yes then how can i do it?
public int run(String[] args) throws Exception
          {
            JobConf conf = new JobConf(getConf(),DecisionTreec45.class);
            conf.setJobName("c4.5");

            // the keys are words (strings)
            conf.setOutputKeyClass(Text.class);
            // the values are counts (ints)
            conf.setOutputValueClass(IntWritable.class);
            conf.setMapperClass(MyMapper.class);
            conf.setReducerClass(MyReducer.class);

            //set your input file path below
            FileInputFormat.setInputPaths(conf, "/home/hduser/Id3_hds/playtennis.txt");
            FileOutputFormat.setOutputPath(conf, new Path("/home/hduser/Id3_hds/1/output"+current_index));
            JobClient.runJob(conf);
            return 0;
          }

A: yes its possible to do that. you can check the following tutorial to see how chaining occurs. http://gandhigeet.blogspot.com/2012/12/as-discussed-in-previous-post-hadoop.html
Make sure you delete the intermediate output data in HDFS which will be created by each MR phase by using fs.delete(intermediateoutputPath);

A: Look at how this works.
You need to have two jobs. Job2 is dependent on job1.
public class ChainJobs extends Configured implements Tool {

 private static final String OUTPUT_PATH = "intermediate_output";

 @Override
 public int run(String[] args) throws Exception {
  /*
   * Job 1
   */
  Configuration conf = getConf();
  FileSystem fs = FileSystem.get(conf);
  Job job = new Job(conf, "Job1");
  job.setJarByClass(ChainJobs.class);

  job.setMapperClass(MyMapper1.class);
  job.setReducerClass(MyReducer1.class);

  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(IntWritable.class);

  job.setInputFormatClass(TextInputFormat.class);
  job.setOutputFormatClass(TextOutputFormat.class);

  TextInputFormat.addInputPath(job, new Path(args[0]));
  TextOutputFormat.setOutputPath(job, new Path(OUTPUT_PATH));

  job.waitForCompletion(true); /*this goes to next command after this job is completed. your second job is dependent on your first job.*/

  /*
   * Job 2
   */
  Configuration conf2 = getConf();
  Job job2 = new Job(conf2, "Job 2");
  job2.setJarByClass(ChainJobs.class);

  job2.setMapperClass(MyMapper2.class);
  job2.setReducerClass(MyReducer2.class);

  job2.setOutputKeyClass(Text.class);
  job2.setOutputValueClass(Text.class);

  job2.setInputFormatClass(TextInputFormat.class);
  job2.setOutputFormatClass(TextOutputFormat.class);

  TextInputFormat.addInputPath(job2, new Path(OUTPUT_PATH));
  TextOutputFormat.setOutputPath(job2, new Path(args[1]));

  return job2.waitForCompletion(true) ? 0 : 1;
 }

 /**
  * Method Name: main Return type: none Purpose:Read the arguments from
  * command line and run the Job till completion
  *
  */
 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub
  if (args.length != 2) {
   System.err.println("Enter valid number of arguments <Inputdirectory>  <Outputlocation>");
   System.exit(0);
  }
  ToolRunner.run(new Configuration(), new ChainJobs(), args);
 }
}


text:
Q: ¿Qué es yield en python? ¿Cuál es el uso de la palabra clave yield en Python? ¿Qué hace?
Estoy intentando entender el siguiente código1:
def _get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild

La llamada de la función (o método en este caso) es:
result, candidates = [], [self]
while candidates:
    node = candidates.pop()
    distance = node._get_dist(obj)
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

¿Qué sucede cuando se llama al método _get_child_candidates? ¿Devuelve una lista o un solo elemento? ¿Es llamado de nuevo? ¿Cuándo se detendrán las llamadas subsiguientes?

1. El código proviene de Jochen Schulz (jrschulz), quien creó una excelente biblioteca de Python para espacios métricos. Este es el enlace a la fuente completa: Module mspace.

A: Explicación sencilla (y falsa)
Un yield puede entenderse como una especie de return que no retorna realmente del todo.
Cuando ejecutando una función se encuentra yield loquesea, la función retorna el valor loquesea, pero "guarda por donde iba". Posteriormente se puede reanudar en el punto donde se dejó, y seguirá ejecutándose por la instrucción siguiente al yield.
Es frecuente por tanto encontrar yield dentro de un bucle, de modo que cada vez que la función se "reanuda" se itera un nuevo valor del bucle y se "retorna" ese nuevo valor.
Cuando la función llega a su final, se produce un "verdadero" return (que retorna None) y entonces ya no se puede reanudar más.
Explicación verdadera (y no tan complicada)
Cuando python está compilando el programa (sí, Python compila todo el código a una representación binaria intermedia antes de pasar a ejecutarlo) si encuentra una función (llamémosla por ejemplo foo) que contiene una o más instrucciones yield, la marca de forma especial. Esa función será un generador.
Cuando el código llame a la función foo() ésta no se ejecuta de forma normal. De hecho ni siquiera comienza su ejecución. El intérprete hace que el resultado de foo() sea un iterador. Es decir, por ejemplo, en:
v = foo()

v pasaría a contener un iterador. Un iterador es un objeto al que se le puede hacer next().
Cuando se haga next(v) entonces sí, el código de foo() comenzará a ejecutarse, y se pausará cuando alcance la instrucción yield. Por ejemplo:
r = next(v)

haría que comenzara el código de foo, y que ante el primer yield el flujo retornara, y el valor retornado por next() sería precisamente el que yield especificó.
Más adelante puede hacerse de nuevo next(v) y entonces la función foo reanudará su ejecución donde estaba (después del yield) y seguirá hasta encontrar otro yield, y así sucesivamente.
Cuando al hacer next(v) la ejecución de la función alcanza su final "real" y por tanto retorna None, el itérprete lanzará la excepción StopIteration.
Por tanto si queremos iterar por todos los valores que vaya "retornando" esa función hasta que se acaben haríamos:
v = foo()
while True:
    try:
        r = next(v)
        print("Valor retornado:", r)
    except StopIteration:
        print("Y no hay más valores")

Pero Python tiene una sintaxis mucho más elegante para hacer esto mismo, a la que estamos bien acostumbrados aún si no sabíamos cómo lo hacía "por debajo". Se trata del bucle for. Lo anterior equivale a:
for r in foo():
   print("Valor retornado:", r)
print("Y no hay más valores")

for se ocupa "por debajo" de recoger el iterador retornado por foo() e ir haciendo next() sobre él, asignando cada valor a r hasta que se detecta StopIteration y se sale del bucle.
El for de las list comprehensions también funciona con generadores, de modo que puedes hacer algo como:
lista = [r for r in foo()]

y así se creará una lista con todos los valores devueltos por el generador. También podríamos abreviarlo a:
lista = list(foo())

ya que list espera un iterable como parámetro, por lo que internamente iterará sobre él, y lo mismo le da que sea un generador que una verdadera lista u otro tipo de objeto, con tal de que implemente el interfaz iterable, es decir, que admita que se le pueda hacer next().
Los generadores son preferibles a las listas cuando el número de elementos es grande, pues se van creando a medida que se necesitan, en vez de tener todos los elementos creados de antemano. Un generador podria incluso no terminar nunca. Por ejemplo, se podría pensar en un generador que cada vez que haces next() te devuelva el siguiente primo.
Para qué se usan
Como he dicho el uso habitual es para hacer generadores que después se puedan iterar en un bucle for.
Pero durante un tiempo (antes de que Python recibiera los keywords async/await, cosa que sucedió en la versión 3.5), se usaban también como una forma un poco enrevesada de conseguir programación asíncrona mediante tareas cooperativas.
Ya que yield no retorna del todo sino que puede seguir por donde se dejó, puede utilizarse para implementar el concepto de corutina que permite a varias funciones entremezclar sus ejecuciones produciendo la ilusión de que ambas avanzan más o menos a la vez, sin necesidad de usar programación multihilo, posibilitando la programación asíncrona.
Pero esa es otra historia. En tu código se está usando (aunque no lo parezca) como un generador.
Esto se debe a que la llamada a la función aparece como parámetro de extend. Es decir, el código hace el equivalente de:
lista.extend(foo())

Ya que extend espera como parámetro un iterable, lo que hará será iterar por los valores devueltos por el generador foo, para añadirlos a lista. Es decir, es equivalente a haber hecho:
lista.extend([v for v in foo()])

o
lista.extend(list(foo())

Respondiendo ya a tus preguntas:

*

*¿Qué sucede cuando se llama al método _get_child_candidates?

Se crea un iterable, y eso es lo que retorna.

*¿Devuelve una lista o un solo elemento?

Ni lo uno ni lo otro, retorna un iterable. Pero según el contexto en que lo uses, probablemente se iterará sobre ese iterable. En tu caso, como ya expliqué, estás pasando el iterable como parámetro de extend() por lo que éste llamará a next() sobre el iterable hasta que lo agote. Cada vez que lo llama se ejecuta hasta el siguiente yield.
Si observamos el código de _get_child_candidates, vemos no contiene bucles y sólo hay dos yield por lo que iterar sobre este caso producirá sólo dos iteraciones como máximo (si ambos if fuesen ciertos, si no puede incluso iterar cero veces)

*¿Es llamado de nuevo? ¿Cuándo se detendrán las llamadas subsiguientes?

A riesgo de ser pesado y aunque ya debe de estar claro, la función sólo se llama una vez. Pero se reanuda varias veces, hasta que ya no ejecute más yield y llegue a su final. En este caso puede generar 0, 1 ó 2 resultados según se cumplan o no los if
De modo que la lista sobre la que se ha hecho .extend() se extenderá con el hijo izquierdo, o el derecho, o ambos, o ninguno :-)
Sin yield
Para cerrar, decir que la función _geg_child_candidates() perfectamente se podría haber implementado sin usar yield. Se podría crear una lista que contenga al hijo izquierdo, o el derecho, o ambos, o ninguno, según corresponda, y retornar esa lista. Así:
def _get_child_candidates(self, distance, min_dist, max_dist):
    result = []
    if self._leftchild and distance - max_dist < self._median:
        result.append(self._leftchild)
    if self._rightchild and distance + max_dist >= self._median:
        result.append(self._rightchild)
    return result

Desde fuera, en este caso, se usaría exactamente de la misma forma:
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))

.extend() espera algo sobre lo que iterar, y en este caso estaría recibiendo una lista, lo que le vale. Añadiría a candidates los elementos de la lista retornada por node._get_child_candidates(). En el caso original, recibía un iterable, lo que también le valía.
No veo mucha ventaja en este caso en usar un generador, pues la lista a crear es realmente muy pequeña. En casos en que la lista pueda ser enorme, el generador tiene la ventaja ya comentada de que es más ligero en el uso de memoria, y si cada elemento tarda un tiempo en ser calculado, el generador te permite obtener el siguiente elemento tan pronto esté listo, sin tener que esperar a generar una lista entera de ellos. Este método es lo que se llama "lazy" (perezoso), porque un dato no se computa hasta que no se necesita.


text:
Q: Numpy operations for generating a 2D array from a 3D array I have an array A with shape [2, 512, 21128]  and another list [7,41]
I want to create a new array with shape [2,21128] from A[0,7,:] and A[1,41,:].
I can use a loop to do such things, is there any convenient way to do this? I try to find it online but I actually do not know how to ask this question.

A: You can use advanced indexing:
arr = np.random.rand(2, 512, 21128)
out = arr[[0, 1], [7, 41]]

out.shape:
(2, 21128)


text:
Q: ORA-22993: specified input amount is greater than actual source amount while creating table with WITH DATA CLAUSE I need to concatenate the job message descriptions by ett_date and create a new table. After this I am going to operate a different step. My problem is that while i am  creating table with WITH DATA CLAUSE, I am getting ORA-22993: specified input amount is greater than actual source amount error. Could you help me about how to solve this problem ?
create table mytable as
WITH DATA AS(
SELECT
ett_date,JOB_NAME,PLAN_NAME,JOB_PERSON1_INFO,JOB_PERSON2_INFO,JOB_PROCEDURE
  ,RTRIM(XMLAGG(XMLELEMENT(e,REGEXP_REPLACE(job_message_desc, '[^0-9A-Za-z]', ' ')  , ' ',',').EXTRACT('//text()')).getCLOBVal() ,',') a
   from mytable group by ett_date,JOB_NAME,PLAN_NAME,JOB_PERSON1_INFO,JOB_PERSON2_INFO,JOB_PROCEDURE)
  select *from DATA


text:
Q: Saving high scores is not working for me Im trying to save the highscores, i have 5 textbox for 5 high scores and i want to replace them when they get beaten, obviously. but for me it always goes into the if statement: if ([hs.text floatValue] == 0) and it just replaces the fist highscore text box no matter how many times i run it. what am i doing wrong?
- (void)viewDidLoad
    {
        [super viewDidLoad];
        highscore = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore"];
        highscore1 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore1"];
        highscore2 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore2"];
        highscore3 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore3"];
        highscore4 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore4"];

    if ([hs.text floatValue] == 0) {
        hs.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if ([hs1.text floatValue] == 0) {
        hs1.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if ([hs2.text floatValue] == 0) {
        hs2.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if ([hs3.text floatValue] == 0) {
        hs3.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if ([hs4.text floatValue] == 0) {
        hs4.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if (finTime < highscore) {
        hs4.text = hs3.text;
        hs3.text = hs2.text;
        hs2.text = hs1.text;
        hs1.text = hs.text;
        hs.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if (finTime < highscore1) {
        hs4.text = hs3.text;
        hs3.text = hs2.text;
        hs2.text = hs1.text;
    }
    else if (finTime < highscore2) {
        hs4.text = hs3.text;
        hs3.text = hs2.text;
        hs2.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if (finTime < highscore3) {
        hs4.text = hs3.text;
        hs3.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    else if (finTime < highscore4) {
        hs4.text = [NSString stringWithFormat:@"%.4f",finTime];
    }
    [self saveScore];
}

-(void) saveScore
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setFloat:finTime forKey:@"highScore"];
    [defaults setFloat:finTime forKey:@"highScore1"];
    [defaults setFloat:finTime forKey:@"highScore2"];
    [defaults setFloat:finTime forKey:@"highScore3"];
    [defaults setFloat:finTime forKey:@"highScore4"];

    [[NSUserDefaults standardUserDefaults] synchronize];

}

A: The problem is that hs.text will not be set (or will be set to 0 if you did that in the xib/Storyboard) when viewDidLoad gets called. Because of that, it always goes into the first if statement and you do not use the values stored in NSUserDefaults.
I would suggest setting the text fields as follows:
- (void)viewDidLoad
{
  [super viewDidLoad];
  highscore = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore"];
  highscore1 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore1"];
  highscore2 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore2"];
  highscore3 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore3"];
  highscore4 = [[NSUserDefaults standardUserDefaults] floatForKey: @"highScore4"];

  if (highscore)
    hs.text = [NSString stringWithFormat:@"%.4f", highscore];
  if (highscore1)
    hs1.text = [NSString stringWithFormat:@"%.4f", highscore1];
  if (highscore2)
    hs2.text = [NSString stringWithFormat:@"%.4f", highscore2];
  if (highscore3)
    hs3.text = [NSString stringWithFormat:@"%.4f", highscore3];
  if (highscore4)
    hs4.text = [NSString stringWithFormat:@"%.4f", highscore4];

  ...

Also, I don't think that the saveScore method is working properly, as it sets all the highscores to finTime. You probably want to set them to the float values from each of the hs text fields.


text:
Q: Angular2 simplest server I have a problem with configuring project in Angular2 so it works.
I did the tutorial, Tour of Heroes on angular site and it uses lite-server.
Now, this is perfect for me, I don't want anything complicated - simplest server, because all of my backend logic is elsewhere.
I tried to deploy it to server but it won't run. Also, on github page of lite-server it says Lightweight development only node server.
I tried express and webpack but those are extremely complicated, with advanced routing and stuff like that. I don't know how  I can simply port what worked on light-server to those servers.
Is there any server like light-server which I can run in production? Or any simples seed, that isn't full-blown node server?


text:
Q: AngularJs - PHP POST issue I am trying to make a post request with angularjs to php. The post response is always 200 OK and the returned 'data' variable in the response is empty always. I am kind of new at this as you can see, what am I doing wrong here?
AngularJs code:
$scope.postData = function(){
    $http.post('send.php', $scope.data).then(function(response){
      console.log(response);
    });
  }

PHP:
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

A: You need to echo data back to the client, in your code you not returning anything back hence the response is empty.
<?php
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

echo json_encode($data); // return data back to the client


text:
Q: Issue in adding third party dependency in Maven during Jenkins build - ODM I am trying to build ODM projects outside of eclipse using the Jenkins pipeline and Maven plugin. I am following the link : https://www.ibm.com/support/knowledgecenter/en/SSQP76_8.9.0/com.ibm.odm.dserver.rules.designer.run/build_topics/con_buildcmd_intro.html
Though this link works well without the Jenkins pipeline in my local(Windows), but when I try to run the same setup in Jenkins(Linux machine), I am getting the following error :
[WARNING] The POM for com.ibm.rules.buildcommand:rules-compiler-maven-plugin:jar:8.10.0.0 is missing, no dependency information available
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ helloWorld:hello-xom:[unknown-version], /var/lib/jenkins/workspace/odm-devops-build/Hello XOM/pom.xml, line 19, column 21
[ERROR] Unresolveable build extension: Plugin com.ibm.rules.buildcommand:rules-compiler-maven-plugin:8.10.0.0 or one of its dependencies could not be resolved: Failure to find com.ibm.rules.buildcommand:rules-compiler-maven-plugin:jar:8.10.0.0 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced @
[ERROR] Unknown packaging: decisionservice @ helloWorld:hello-main:[unknown-version], /var/lib/jenkins/workspace/odm-devops-build/Hello Main Service/pom.xml, line 14, column 16

The pom file which is referred in the above error is as below:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>helloWorld</groupId>
        <artifactId>parent</artifactId>
        <version>1.0.0</version>
        <relativePath>..</relativePath>
    </parent>

    <artifactId>hello-main</artifactId>
    <packaging>decisionservice</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>com.ibm.rules.buildcommand</groupId>
                <artifactId>rules-compiler-maven-plugin</artifactId>
                <configuration>

                    <deployments>
                        <deployment>
                            <name>simple dep</name>
                        </deployment>
                    </deployments>

                    <resolvers>
                        <resolver>
              <!-- The values of the kind and url of the project correspond to the 'kind' and 'url' attribute values of an 'entries' element in the .ruleproject file. -->
                            <kind>JAVA_PROJECT</kind>
                            <url>platform:/Hello XOM</url>
              <!-- The artifactKey references the groupId and artifactId of a Maven dependency. -->
                            <artifactKey>${project.groupId}:hello-xom</artifactKey>
                        </resolver>
                    </resolvers>

                </configuration>
            </plugin>
        </plugins>

    </build>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>hello-xom</artifactId>
            <type>jar</type>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

</project>

Please let me know if anyone has faced a similar issue or has a possible resolution to the above issue.
Thanks in advance.

A: Possible resolution: "install the Build Command Maven plugin and its related Operational Decision Manager artifacts in your Maven repository" ... "on each machine that contains build agents"

To deploy the Build Command Maven plugin to a remote Maven repository, you must configure Maven in your environment. You then use the following command: mvn deploy:deploy-file -Dfile=rules-compiler-maven-plugin.jar -DpomFile=rules-compiler-maven-plugin.pom

This requires access to the Jenkins / Maven server, and at many companies would be done by DevOps.

A: You install the Build Command Maven plugin and its related Operational Decision Manager artifacts in your Maven repository.
Deploying the Build Command plugin
You deploy the plugin only once on each machine that contains build agents.
To deploy the Build Command Maven plugin to a remote Maven repository, you must first configure Maven in your environment.
Then, in <InstallDir>/buildcommand/rules-compiler, open a command prompt.
Use the following command:
mvn deploy:deploy-file -Dfile=rules-compiler.jar -DpomFile=rules-compiler-maven-plugin.pom

If you do not have a remote repository, you can test the plugin locally. You run the following command:
mvn install:install-file -Dfile=rules-compiler.jar -DpomFile=rules-compiler-maven-plugin.pom

This command adds the following plugin in your local Maven repository:
com/ibm/rules/buildcommand/rules-compiler

 Deploying the annotations archive
If you want to build COBOL projects or projects that use XOM annotations, you must also deploy the annotations archive to your environment before you can build the projects.
In <InstallDir>/buildcommand/rules-compiler, open a command prompt.
Use the following command:
mvn deploy:deploy-file -Dfile=rules-compiler.jar -DpomFile=xom-annotations.pom

If you do not have a remote repository, you can test the plugin locally. You run the following command:
mvn install:install-file -Dfile=rules-compiler.jar -DpomFile=xom-annotations.pom

This command adds the following plugin in your local Maven repository:
com/ibm/rules/buildcommand/xom-annotation

Source


text:
Q: Next.js page not found if route ends with a slash I am currently working on a next.js application. The issue i am facing is with next/link. Link works well if i am navigating through the application. Every page is rendered properly. The problem shows up when i refresh a page and the URL ends with a slash.
http://localhost:3000/about/

The above route is showing "Page not found" while the following route will load the page successfully.
http://localhost:3000/about

I am using link as follow:
<Link href="/about">
   About
</Link>

Any help will be appreciated. Thanks.

A: I hope there should be an easiest way to do that. However you can do this using custom server. Here is an example:-
server.get("/about/", (req, res) => {
  return app.render(req, res, "/about")
})

A: I worked around this issue by switching out the  tags for a simple  tag.
Not ideal but at least it prevented the default handling of the trailling slash by nextjs.
About

In my case I was directing to a page where I had no control over the url format.


text:
Q: Get the text before and after strstr in C I need to be able to extract the characters before and after a substring, currently I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){

   char *text = (char *) malloc (10000000);
   char *word = argv[1];
   int rep;

   FILE *f;

   if(argc < 2)
   {
       printf("Usage: GET <website> | ./word_counter <word>\n");
       exit(1);
   }

   fread(text, 100, 10000000, stdin);

   const char *tmp = text;

   f = fopen("output.txt", "w");
   fprintf(f, "%s\n", "REPS");

   while(tmp = strstr(tmp, word)){
      printf("%.50s\n", tmp);
      rep++;
      tmp++;
   }

   printf("Word count: %d\n", rep);
   fclose(f);
   system("gedit output.txt");

   return 0;
}

I made a copy of the original input so I could leave it untouched and get the "before" characters from it.
Using strstr() on tmp (the original input copy) I can find the instances of the word I'm looking for and print the first 50 characters. But knowing this, how can I access the 50 characters BEFORE this instance?
Any help will be appreciated. Thanks!

A: Apart from the printing question itself, there are a couple of errors in your code. I have corrected most of them; a short list is:

*

*Always test if malloc succeeded.

*fread(text, 100, 10000000, ..) reads way too many text. 100 * 10000000 = 1000000000, almost a full gigabyte. You only allocated enough memory for 10 Mb.

*You read from a text file and treat this data as a string. Therefore, you must make sure the data ends with a 0, else functions such as printf and strstr will try to continue reading after the end.

*Your rep variable starts out uninitialized and therefore you will always see a random number.

*Always free memory you allocated.

That said, it is slightly more efficient to use a dedicated function to print out text – if only to not put too much in your main. And since it's a function, you can add as many useful parameters into it as you want; I added before and after variables, so you can vary the number of characters shown.
For added niceness, this function prints a correct number of spaces when the phrase is found before the minimum number of before characters, so the results line up nicely. Also, since printing out characters such as tab and newlines will mess up your output, I replaced them with ?.
There is, admittedly, some repetition in print_range but in this case I went for clarity, rather than brevity.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LENGTH  10000000

void print_range (char *source_text, int startindex, int before, int after, int phrase_length)
{
    int i;

    if (before > startindex)
    {
        for (i=0; i<before-startindex; i++)
            printf (" ");
        startindex = before;
    }

    for (i=0; i<before; i++)
    {
        if (strchr ("\t\r\n", source_text[startindex-before+i]))
            printf ("?");
        else
            printf ("%c", source_text[startindex-before+i]);
    }
    for (i=0; i<phrase_length; i++)
    {
        if (strchr ("\t\r\n", source_text[startindex+i]))
            printf ("?");
        else
            printf ("%c", source_text[startindex+i]);
    }
    for (i=0; i<after; i++)
    {
        if (!source_text[startindex+phrase_length+i])
            break;
        if (strchr ("\t\r\n", source_text[startindex+phrase_length+i]))
            printf ("?");
        else
            printf ("%c", source_text[startindex+phrase_length+i]);
    }
    printf ("\n");
}

int main (int argc, char *argv[]){

    char *text = (char *) malloc (MAX_LENGTH);
    char *word = argv[1];
    int rep = 0;

    if (!text)
        return -1;

    if(argc < 2)
    {
         printf("Usage: GET <website> | ./word_counter <word>\n");
         exit(1);
    }

    fread(text, 1, MAX_LENGTH, stdin);
    text[MAX_LENGTH] = 0;

    const char *tmp = text;

    do
    {
        tmp = strstr(tmp, word);
        if (!tmp)
            break;
        print_range (text, tmp-text, 16,16, strlen(word));
        rep++;
        tmp++;
    } while (1);

    free (text);

    printf ("Word count: %d\n", rep);

    return 0;
}

Result of running this on its own source code:
~/Documents $ ./wordcounter printf < wordcounter.c
tindex; i++)????printf (" ");???starti
-before+i]))????printf ("?");???else??
"?");???else????printf ("%c", source_t
before+i]);??}??printf ("{");??for (i=
rtindex+i]))????printf ("?");???else??
"?");???else????printf ("%c", source_t
tindex+i]);??}??printf ("}");??for (i=
_length+i]))????printf ("?");???else??
"?");???else????printf ("%c", source_t
length+i]);??}??printf ("\n");?}??int
argc < 2)??{??? printf("Usage: GET <we
?free (text);???printf ("Word count: %
Word count: 12


text:
Q: My command prompt wont run the whole program This code runs perfectly in my IDE; I even tried it in an online compiler just to be sure, but when I try to open the .exe it will only ask for the integer and automatically close. I tried it with another program from the school where I asked for like 15 numbers but right before a goodbye message it just closes. Any idea how to fix cmd?
#include <stdio.h>

int main()
{
    int numberOfWidgets;

    printf("Give me a number: ");
    scanf("%d", &numberOfWidgets);

    printf("You choose the number: %d", numberOfWidgets);

    return 0;
}

A: You need to add two lines to the end of your program:
int main() {
    ...
    getchar();
    getchar();

    return 0;
}

The first call to getchar will clear the return key you pressed when you entered the number, the second one will stop and wait for a key to be pressed.
That way, your program will not exit until you press a key, and you will be able to read the output.


text:
Q: New to React and trying to compile an APK but failing I'm trying to setup a build process that can run when our dev commits to the GitLab repository.  I'm trying to get this thing to build the APK and the method that I'm using for this is suggested by this thread the error I'm getting is here which implies that the file aapt doesn't exist.  Although investigating that path it most certainly exists so I have no idea what I'm doing wrong here.
The docker container that I'm using as a base is /runmymind/docker-android-sdk/:latest then I'm using this dockerfile at /chamunks/ReactNativeAndroid/
I'm not entirely certain how I'm failing at this as I've never compiled an android app before but this process being as crazy as it is makes me wonder how anyone ever builds an android app.

A: You can try deleting android/build and android/app/build directories and then call gradle to build and install the app.
For Debug you should call these in your project root directory;

*

*(cd android/ && ./gradlew assembleDebug)

*(cd android/ && ./gradlew installDebug)
For Release you should call these in your project root directory. This option needs a generated .keystore file. The produced .apk files are under android/app/build/outputs/apk path;

*

*(cd android/ && ./gradlew assembleRelease)

*(cd android/ && ./gradlew installRelease)
You might also try reinstalling your android-sdk. You might have a problem with version 23.0.3.


text:
Q: Deny entering special character in textbox using jquery How can i deny user from entering special characters in textbox using jquery?
special characters are like \ / ? * [ or ]

A: i think you can achieve this using javascript only
call the below function in KeyPress event of text box
function AlphaNumericOnly(e,isAlphaonly)
{
   // copyright 1999 Idocs, Inc. http://www.idocs.com
   var key = [e.keyCode||e.which];

   var keychar = String.fromCharCode([e.keyCode||e.which]);
   keychar = keychar.toLowerCase();

   if(isAlphaonly=='true')
         checkString="abcdefghijklmnopqrstuvwxyz";
   else
         checkString="abcdefghijklmnopqrstuvwxyz0123456789";

   if ((key==null) || (key==0) || (key==8) ||
         (key==9) || (key==13) || (key==27) )
        return true;
   else if (((checkString).indexOf(keychar) > -1))
        return true;
   else
        return false;
}

A: Using jQuery:
    $(function () {
        //Add handler to input where the id ends with txtName
        $("input[id$='txtUrl']").keypress(function (event) {
            if (!IsUrlReady(event)) {
                event.preventDefault();
            }
        });
    });

    function IsUrlReady(e) {
        var key = [e.keyCode || e.which];
        var keychar = String.fromCharCode([e.keyCode || e.which]).toLowerCase();

        // 8 = backspace
        // 9 = tab
        //13 = enter key
        //35 = end | #
        //36 = home | $
        //37 - (direction) left | %
        //38 - (direction) up | &
        //39 - (direction) right | '
        //40 - (direction) down | (

        if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27) || (key >= 35 && key <= 40)) {
            var pattern = new RegExp("['#$%&\(]");
            return !pattern.test(keychar);
        } else {
            var pattern = new RegExp("[A-Za-z0-9_-]");
            return pattern.test(keychar);
        }
    }

A: check the keycodes within a keydown or keyup event handler.
$('input').bind('keydown', function(e){
   if(e.shiftKey){
     switch(e.which){
           case 55:{   // slash
                return(false);
           }
           case 187:{   // *
                return(false);
           }
           // and so forth
     }
   }
});

A: Like @Reigel pointed out, listening for keyboard entries can easily be bypassed by simply pasting the content so I think you would be better off with something like the jQuery Validation plugin.
It has tons of features, like custom validation rules so you can have it validate after your own custom rules (obviously). Below is an example of how you can have the validation trigger when the watched field's content changes (rather than waiting until the form is submitted), be it by typing or pasting:
$("#myTextField").change(function() {
    if(!$(this).valid()) {
        /* do something, show an alert, or whatever you need it to do */
    }
});

I won't go into greater detail on how to use this plugin because SO is already full of examples, but I hope it does set you on the right direction.


text:
Q: Copy properties from selector to another selector in Less I'm new to Less. I know about variables, the basics of mixins and nested definitions.
I have a selector
.my-parent .my-child { color: red; }

and another selector
.foo .bar { color: green; }

I know every class is a mixin in Less by default, so I can do this
.foo .bar { .my-parent() }

however when I do this
.foo .bar { .my-child() }

my compiler complains because .my-child doesn't exist because it's part of another selector.
Can I create a new mixin that will copy all the properties from 1 whole selector to another?


text:
Q: eclipse code templates - indentation I have created a code template to add a logger and the corresponding import:
${:import(org.apache.log4j.Logger)}
private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

If I add this now, the logger always starts at the beginning of the line, even if my cursor is already indented. Is there a way to to force the placement at the position of the cursor?
This is a screenshot to show what I mean:

====>>>>

Edit: The answer from Grove helped in this specific case. But how about this example? I also want to add a comment to the logger. If I define the template like this in the same line, the logger actually apears in the same line as the comment.
${:import(org.apache.log4j.Logger)}
/**
 *  Logger
 */ private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

A: Yes there is, do not add a new line between the import and the logger definition:
${:import(org.apache.log4j.Logger)}private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

Side-note: If needed, you can also position the cusrsor in your template with the ${cursor} variable
EDIT AFTER QUESTION UPDATE: The same thing applies, the import variable does not have to be the first in the pattern, it can be anywhere and it will be evaluated nonetheless:
/**
 *  Logger
 */
${:import(org.apache.log4j.Logger)}private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

A: I don't think you need to concentrate on templates for this. You can use Formatter for this.
Create your own formatter in Windows > Preferences > Java > Code Style > Formatter and enable Save Actions in Windows > Preferences > Java > Editor > Save Actions (Select Format Source code and Format all lines options)  and here you choose your formatter created before.
Once you insert the logger template editor becomes dirty then save the editor(press Ctrl + S) then automatic indentation will happen as per the settings in formatter.
Refer this and this for formatter creation. In Indentation tab use the number of space you like. I used Tab Policy = Spaces only and Indentation size = 4.


text:
Q: Unable to activate conda environment with a spawned tmux window I have a workflow that spawns a new tmux window and executes a command inside that fresh window.
The command being executed is a Python application that requires a specific conda environment.
I have just realised that once that new window is invoked, it is invoked with the default conda environment. When I try to invoke the tmux window with a conda activate myEnv command, I am getting an error.
Here is the command I have used in my test:
tmux new-window -n:mywindow 'echo "__START__"; conda activate py37; echo "___END___"; sleep 5'

The following is the error I'm getting within the tmux window that is invoked:
__START__

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

___END___

Any ideas?
Further details:
conda 4.7.12
Linux (Ubuntu 18.04)
Python3.7
tmux 3.0a
vim-dispatch (the plugin that invokes a new pane to run my app)

A: conda stuff is all in the shell you are using, so whether it bash or something else, you need to make sure you've run conda init, and the CONDA_DEFAULT_ENV environment variable exists. I have a semi-related answer here that may help someone - https://stackoverflow.com/a/66312869/8490364


text:
Q: Split a line after single quote into a newline I have a text file like this
'ABC&\]D' 'DEFGH' 'QUEMKLEMEL' 'SSBJ|!KFFL'

and would like to convert it to
'ABC&\]D'
'DEFGH'
'QUEMKLEMEL'
'SSBJ|!KFFL'

to split the textfile at the single quotes into a newline.
The original issue is to convert a bash script from windows (the EOL characters to Unix format). I tried
sed 's/\r//' input >output

but keep getting the error when I submit the script
sbatch: error: This does not look like a batch script.

It is a long text file from windows that was transferred to linux but does not work because of the EOL characters. I tried other options to convert it so thought can subset the issue, and try it this way.

A: Using GNU awk for it:
$ gawk -v FPAT="([^ ]+)|('[^']+')" -v OFS="\n" '{$1=$1}1' file

Output
'ABC&\]D'
'DEFGH'
'QUEMKLEMEL'
'SSBJ|!KFFL'

A: Using gnu sed you can search for "' " and replace with \n:
sed "s/' /'\n/g" file

'ABC&\]D'
'DEFGH'
'QUEMKLEMEL'
'SSBJ|!KFFL'

Or using POSIX awk:
awk '{gsub(/\x27 /, "\x27\n")} 1' file

'ABC&\]D'
'DEFGH'
'QUEMKLEMEL'
'SSBJ|!KFFL'

or this one:
awk -F "' " -v OFS="'\n" '{$1=$1} 1' file

A: 1st solution: Using gsub function of awk.
awk '{gsub(/\x27 \x27/,"\x27\n\x27")} 1' Input_file

2nd solution: Could you please try following, written and tested with shown samples.
awk '{for(i=1;i<=NF;i++){print $i}}' Input_file