text:
Q: Mysql single column table --> insert in other table I have two tables: t1 and t2
- t2 has only 1 column named stuff (60.000 entries).
- t1 has 15 columns, including stuff (empty). t1 has about 650.000 entries.
How can I import the data from t2.stuff in t1.stuff when I have nothing to match it against? (I just want to populate empty fields of t1.stuff with data from t2.stuff and don't care about matching ids or anything.)
The best case (i think) would be, that if I run this query about 11 times, all fields of t1.stuff would be populated, because no empty field in t1.stuff is left over.
Here is an example what the tables look like:
t1:
|__a___|_b_|_c_|stuff|...|
|___308|foo|bar|_____|baz|
|___312|foo|bar|_____|baz|
...
|655578|foo|bar|_____|baz|
t2:
|___stuff___|
|some_info_1|
|some_info_2|
...
|some_info_n|
Maybe there are multiple steps required...
UPDATE
Here is the SOLUTION I went with in case someone has a similar problem - All credits go to user nurdglaw for pointing me in the right direction. So here we go:

*

*Add a new column to your table in question populated with autoincrementing numbers (I set alter table t1 auto_increment = 1 and temporary disabled autoincrementing on my primary key, to avoid an error with this code) ALTER TABLE t1 ADD COLUMN new_column INTEGER UNIQUE AUTO_INCREMENT;

*Did the same thing for t2. If you don't already have a second table, you can do something like this:
CREATE TABLE t2 (id INTEGER PRIMARY KEY AUTO_INCREMENT,t2_data_column VARCHAR(255)); <-- adjust number to your needs
and import your data with:
LOAD DATA LOCAL INFILE 'path_on_your_server/data_file.csv'
INTO TABLE t2
LINES TERMINATED BY '\r\n' <-- adjust to your linebreak needs
(t2_data_column)

*Now that you have something to match against, you can INNER JOIN t1 with t2 by doing the following: Add the data from t2 to t1
UPDATE t1 AS s
JOIN t2 AS t ON t.id=s.new_column
SET s.stuff=t.t2_data_column; <-- stuff was the column in t1 I wanted to import the data to.

*Tidy up the mess
DROP TABLE t2;
ALTER TABLE t1 DROP COLUMN new_column;
Enable autoincrement on your primary key again and set it to the number you need for new rows, if you used one before.

That is it, you're done!
One further note: I decided to adjust my data offline and import the 650.000 entries needed with this method in one go, rather than doing it with only the 60.000 I put in the initial question. But you'll get the idea of doing it with any number of data and match it with whatever you need.

A: INSERT statements create new rows in your table.
You need an UPDATE on the already existing rows
An easy way to do that is using an extern scripting language
; here is a rebol example
; assumming you use the mysql library from softinnov
; and a_ is the name of the unique key to a row in t1

db: open mysql://user:pass@mysql
insert db {select * from t1}
t1rows: copy db
insert db {select * from t2}
t2rows: copy db
foreach row t1rows [

insert db [ {update t1 set t1.stuff = ? where t1.a_ =  ?} t2rows/1/1  row/1]
either tail? next t2rows [

  t2rows: head t2rows

] [

  t2rows: next t2rows

]

]

sorry, I still have difficulties with the formatting and the variables in your example

A: Try this
     INSERT INTO t1 (stuff)
     SELECT DISTINCT stuff FROM t2

I hope it helps


text:
Q: How to convert hms time format to plain string wth ms (minute:second) format I have the following data frame:
library(tidyverse)
dat <- structure(list(cuml = structure(c(109200, 214980, 325560), class = c("hms",
"difftime"), units = "secs")), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))

It looks like this:
> dat
# A tibble: 3 x 1
  cuml
  <time>
1 30:20
2 59:43
3 90:26

Not they are in minute:second format. What I want to do is to print them like this:
(30:20)
(59:43)
(90:26)

But when I do this,
   dat %>%
      mutate(cuml = paste0("(", format(cuml, "%s"),")"))

I get this, which is not exactly what I want:
(30:20:00)
(59:43:00)
(90:26:00)

What's the right way to do it?

A: Although we don't see them in the tibble format but dat$cuml has 3 components in them.
dat$cuml

#30:20:00
#59:43:00
#90:26:00

We can use regex to extract the first two :
library(dplyr)

dat %>%
  mutate(cuml = sprintf('(%s)', sub('(\\d+:\\d+).*', '\\1', cuml)))

#   cuml
#  <chr>
#1 (30:20)
#2 (59:43)
#3 (90:26)

A: We can use
dat$cuml <-  paste0("(", substr(dat$cuml, 1, 5), ")")

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA HTML Scraping - '.innertext' from complex table All,
I've created the following Module to scrape a single value (1m % change in London house prices) from the below address:
https://www.hometrack.com/uk/insight/uk-cities-house-price-index/
The specific value is nested within the following code:

The below VBA code is my attempt at scraping.  I, perhaps wrongly, feel that I am very close to capturing the value - but the code will not work.
Does anyone know where I am going wrong here?  It doesn't show an error message but also doesn't output any values.
 Sub HousePriceData()
        Dim wb As Workbook
        Dim ws As Worksheet
        Dim TxtRng As Range
        Dim ie As Object
        Dim V As Variant
        Dim myValue As Variant

        Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")
        ie.NAVIGATE "https://www.hometrack.com/uk/insight/uk-cities-house-price-index/"
        ie.Visible = False

        While ie.ReadyState <> 4
            DoEvents
        Wend

        Set wb = ActiveWorkbook
        Set ws = wb.Sheets("Input")
        Set TxtRng = ws.Range("C15")

        Set myValue = ie.document.getElementById("cities-index-table").getElementsByTagName("tr")(7).getElementsByTagName("td")(5)

        TxtRng = myValue.innerText
        End Sub

A: Try to use XHR and primitive parsing instead of awkward IE:
Sub Test()

    Dim strUrl As String
    Dim strTmp As String
    Dim arrTmp As Variant

    strUrl = "https://www.hometrack.com/uk/insight/uk-cities-house-price-index/"
    With CreateObject("MSXML2.XMLHttp")
        .Open "GET", strUrl, False
        .Send ""
        strTmp = .ResponseText
    End With
    arrTmp = Split(strTmp, ">London	", 2)
    strTmp = arrTmp(1)
    arrTmp = Split(strTmp, "", 7)
    strTmp = arrTmp(6)
    arrTmp = Split(strTmp, "	", 2)
    strTmp = arrTmp(0)

    ThisWorkbook.Sheets("Input").Range("C15").Value = strTmp

End Sub

A: try use this
Dim Engmt As String

Engmt = "ERRORHERE"
On Error Resume Next
Engmt = Trim(ie.document.getElementById("cities-index-   table").getElementsByTagName("tr")(12).getElementsByTagName("td")(4).innerText)
On Error GoTo 0
If Engmt = "ERRORHERE" Then
TxtRng.Value = "ERROR"
Else
TxtRng.Value = Engmt
End If


text:
Q: fusedLocationClient.getLastLocation always returns NULL i implemented the method used in Lib android this, see:
  fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null) {
                    localidade = location;
                    Toast.makeText(getApplicationContext(), "Local correto", Toast.LENGTH_LONG).show();
                }

                    Toast.makeText(getApplicationContext(), "Localidade vazia", Toast.LENGTH_LONG).show();
            }
        });

However, within OnSuccess the result is ALWAYS null, I am testing on my mobile (9.0 android) with LOCAL(gps) mode on and still returns null, my manisfest has the necessary permissions: <uses-permission android: name = "android.permission .ACCESS_FINE_LOCATION "/>
In my view nothing is wrong, so why ALWAYS null?

A: Last known location is registered known location by the user. If you read on the location page it states that last known location can be null in certain situations; in those scenarios it is advised you request location updates. Following is taken from the page:

The location object can be nullin the following situations:
Location is disabled in the device settings. The result may nulleven
  be that the last location was retrieved earlier, because disabling the
  location also clears the cache. The device never recorded its own
  location, which happens when the device is new or when it has been
  restored to factory settings. The Google Play Services platform on the
  device has been restarted and no active Fused Location Provider API
  clients have requested location after services have been restarted. To
  avoid this situation, create a new customer and request location
  updates.


text:
Q: Magento 2.1 - Custom Category Image attribute is not saved I have created a custom category thumbnail attribute according to the post (Magento 2 create category attribute thumbnail and upload image using File Uploader Component).
The image gets saved in the "tmp" directory but is not saved when I save the category.
what is the issue for that?

A: This is quite a big answer.
In Magento 2.1.0 you need to apply a patch to create a additional file upload attribute for category.
As they are using hardcoded values for image attribute on many places. for more details have a look at link1 and link2
Steps to apply a patch.
1) Edit composer.json file located at root directory as follows.
{
    "name": "magento/project-community-edition",
    "description": "eCommerce Platform for Growth (Community Edition)",
    "type": "project",
    "version": "2.1.0",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://repo.magento.com/"
        }
    ],
    "require": {
        "magento/product-community-edition": "2.1.0",
        "cweagans/composer-patches": "~1.4.0",
        "composer/composer": "@alpha"
    },
    "require-dev": {
        "phpunit/phpunit": "4.1.0",
        "squizlabs/php_codesniffer": "1.5.3",
        "phpmd/phpmd": "2.3.*",
        "pdepend/pdepend": "2.2.2",
        "sjparkinson/static-review": "~4.1",
        "fabpot/php-cs-fixer": "~1.2",
        "lusitanian/oauth": "~0.3 <=0.7.0"
    },
    "config": {
        "use-include-path": true
    },
    "autoload": {
        "psr-4": {
            "Magento\\Framework\\": "lib/internal/Magento/Framework/",
            "Magento\\Setup\\": "setup/src/Magento/Setup/",
            "Magento\\": "app/code/Magento/"
        },
        "psr-0": {
            "": "app/code/"
        },
        "files": [
            "app/etc/NonComposerComponentRegistration.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Magento\\Sniffs\\": "dev/tests/static/framework/Magento/Sniffs/",
            "Magento\\Tools\\": "dev/tools/Magento/Tools/",
            "Magento\\Tools\\Sanity\\": "dev/build/publication/sanity/Magento/Tools/Sanity/",
            "Magento\\TestFramework\\Inspection\\": "dev/tests/static/framework/Magento/TestFramework/Inspection/",
            "Magento\\TestFramework\\Utility\\": "dev/tests/static/framework/Magento/TestFramework/Utility/"
        }
    },
    "minimum-stability": "alpha",
    "prefer-stable": true,
    "extra": {
        "patches": {
            "magento/module-catalog": {
                "Fix: https://github.com/magento/magento2/issues/5438": "patches/Patch-Magento_Catalog-M2.1.0-image-attribute-backend-model-hardcoded-attribute-code-removal.patch"
            },
            "magento/module-ui": {
                "Fix: https://github.com/magento/magento2/issues/5438": "patches/Patch-Magento_Ui-M2.1.0-allow-backend-to-know-the-origin-input-of-the-upload-request.patch"
            }
        },
        "magento-force": "override"
    }
}

As mentioned on link2 above newly added code is in extra and require.
2) Create a patches folder on root directory.
3) Create file Patch-Magento_Catalog-M2.1.0-image-attribute-backend-model-hardcoded-attribute-code-removal.patch under patches folder with following contains.
--- Controller/Adminhtml/Category/Save.php.org  2016-08-03 21:35:33.772109252 +0200
+++ Controller/Adminhtml/Category/Save.php  2016-08-03 21:36:33.982229407 +0200
@@ -6,6 +6,7 @@
 namespace Magento\Catalog\Controller\Adminhtml\Category;

 use Magento\Store\Model\StoreManagerInterface;
+use \Magento\Catalog\Api\Data\CategoryAttributeInterface;

 /**
  * Class Save
@@ -49,6 +50,11 @@
     private $storeManager;

     /**
+     * @var \Magento\Eav\Model\Config
+     */
+    private $eavConfig;
+
+    /**
      * Constructor
      *
      * @param \Magento\Backend\App\Action\Context $context
@@ -62,37 +68,15 @@
         \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
         \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
         \Magento\Framework\View\LayoutFactory $layoutFactory,
-        StoreManagerInterface $storeManager
+        StoreManagerInterface $storeManager,
+        \Magento\Eav\Model\Config $eavConfig
     ) {
         parent::__construct($context);
         $this->resultRawFactory = $resultRawFactory;
         $this->resultJsonFactory = $resultJsonFactory;
         $this->layoutFactory = $layoutFactory;
         $this->storeManager = $storeManager;
-    }
-
-    /**
-     * Filter category data
-     *
-     * @param array $rawData
-     * @return array
-     */
-    protected function _filterCategoryPostData(array $rawData)
-    {
-        $data = $rawData;
-        // @todo It is a workaround to prevent saving this data in category model and it has to be refactored in future
-        if (isset($data['image']) && is_array($data['image'])) {
-            if (!empty($data['image']['delete'])) {
-                $data['image'] = null;
-            } else {
-                if (isset($data['image'][0]['name']) && isset($data['image'][0]['tmp_name'])) {
-                    $data['image'] = $data['image'][0]['name'];
-                } else {
-                    unset($data['image']);
-                }
-            }
-        }
-        return $data;
+        $this->eavConfig = $eavConfig;
     }

     /**
@@ -126,7 +110,7 @@
         $this->storeManager->setCurrentStore($store->getCode());
         $parentId = isset($categoryPostData['parent']) ? $categoryPostData['parent'] : null;
         if ($categoryPostData) {
-            $category->addData($this->_filterCategoryPostData($categoryPostData));
+            $category->addData($categoryPostData);
             if ($isNewCategory) {
                 $parentCategory = $this->getParentCategory($parentId, $storeId);
                 $category->setPath($parentCategory->getPath());
@@ -247,22 +231,29 @@
         );
     }

-    /**
-     * Image data preprocessing
-     *
-     * @param array $data
-     *
-     * @return array
-     */
     public function imagePreprocessing($data)
     {
-        if (empty($data['image'])) {
-            unset($data['image']);
-            $data['image']['delete'] = true;
+        $entityType = $this->eavConfig->getEntityType(CategoryAttributeInterface::ENTITY_TYPE_CODE);
+
+        foreach ($entityType->getAttributeCollection() as $attributeModel) {
+            $attributeCode = $attributeModel->getAttributeCode();
+            $backendModel = $attributeModel->getBackend();
+
+            if (isset($data[$attributeCode])) {
+                continue;
+            }
+
+            if (!$backendModel instanceof \Magento\Catalog\Model\Category\Attribute\Backend\Image) {
+                continue;
+            }
+
+            $data[$attributeCode] = false;
         }
+
         return $data;
     }

+
     /**
      * Converting inputs from string to boolean
      *
--- Controller/Adminhtml/Category/Image/Upload.php.org  2016-08-01 20:36:22.014237780 +0200
+++ Controller/Adminhtml/Category/Image/Upload.php  2016-08-01 20:36:25.292475257 +0200
@@ -50,8 +50,10 @@
      */
     public function execute()
     {
+        $imageId = $this->_request->getParam('param_name', 'image');
+
         try {
-            $result = $this->imageUploader->saveFileToTmpDir('image');
+            $result = $this->imageUploader->saveFileToTmpDir($imageId);

             $result['cookie'] = [
                 'name' => $this->_getSession()->getName(),
--- Model/Category/Attribute/Backend/Image.php.org  2016-08-03 21:36:05.695112561 +0200
+++ Model/Category/Attribute/Backend/Image.php  2016-08-03 21:36:46.829828298 +0200
@@ -13,6 +13,8 @@

 class Image extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
 {
+    const ADDITIONAL_DATA_SUFFIX = '_additional_data';
+
     /**
      * @var \Magento\MediaStorage\Model\File\UploaderFactory
      *
@@ -21,8 +23,6 @@
     protected $_uploaderFactory;

     /**
-     * Filesystem facade
-     *
      * @var \Magento\Framework\Filesystem
      *
      * @deprecated
@@ -30,8 +30,6 @@
     protected $_filesystem;

     /**
-     * File Uploader factory
-     *
      * @var \Magento\MediaStorage\Model\File\UploaderFactory
      *
      * @deprecated
@@ -46,15 +44,11 @@
     protected $_logger;

     /**
-     * Image uploader
-     *
      * @var \Magento\Catalog\Model\ImageUploader
      */
     private $imageUploader;

     /**
-     * Image constructor.
-     *
      * @param \Psr\Log\LoggerInterface $logger
      * @param \Magento\Framework\Filesystem $filesystem
      * @param \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
@@ -70,8 +64,50 @@
     }

     /**
-     * Get image uploader
+     * @param $value
+     * @return string|bool
+     */
+    protected function getUploadedImageName($value)
+    {
+        if (!is_array($value)) {
+            return false;
+        }
+
+        if (!count($value)) {
+            return false;
+        }
+
+        $imageData = reset($value);
+
+        if (!isset($imageData['name'])) {
+            return false;
+        }
+
+        return $imageData['name'];
+    }
+
+    /**
+     * Avoiding saving potential upload data to DB
      *
+     * @param \Magento\Framework\DataObject $object
+     * @return $this
+     */
+    public function beforeSave($object)
+    {
+        $attributeName = $this->getAttribute()->getName();
+        $value = $object->getData($attributeName);
+
+        if ($value === false || (is_array($value) && isset($value['delete']) && $value['delete'] === true)) {
+            $object->setData($attributeName, '');
+        } else if ($imageName = $this->getUploadedImageName($value)) {
+            $object->setData($attributeName . self::ADDITIONAL_DATA_SUFFIX, $value);
+            $object->setData($attributeName, $imageName);
+        }
+
+        return parent::beforeSave($object);
+    }
+
+    /**
      * @return \Magento\Catalog\Model\ImageUploader
      *
      * @deprecated
@@ -80,9 +116,10 @@
     {
         if ($this->imageUploader === null) {
             $this->imageUploader = \Magento\Framework\App\ObjectManager::getInstance()->get(
-                'Magento\Catalog\CategoryImageUpload'
+                \Magento\Catalog\CategoryImageUpload::class
             );
         }
+
         return $this->imageUploader;
     }

@@ -94,15 +131,18 @@
      */
     public function afterSave($object)
     {
-        $image = $object->getData($this->getAttribute()->getName(), null);
+        $value = $object->getData($this->getAttribute()->getName() . self::ADDITIONAL_DATA_SUFFIX);

-        if ($image !== null) {
-            try {
-                $this->getImageUploader()->moveFileFromTmp($image);
-            } catch (\Exception $e) {
-                $this->_logger->critical($e);
-            }
+        if (!$imageName = $this->getUploadedImageName($value)) {
+            return $this;
         }
+
+        try {
+            $this->getImageUploader()->moveFileFromTmp($imageName);
+        } catch (\Exception $e) {
+            $this->_logger->critical($e);
+        }
+
         return $this;
     }
 }
--- Model/Category/DataProvider.php.org 2016-08-01 21:35:43.567609510 +0200
+++ Model/Category/DataProvider.php 2016-08-01 21:43:07.800993338 +0200
@@ -203,14 +203,24 @@
         $category = $this->getCurrentCategory();
         if ($category) {
             $categoryData = $category->getData();
+
             $categoryData = $this->addUseDefaultSettings($category, $categoryData);
             $categoryData = $this->addUseConfigSettings($categoryData);
             $categoryData = $this->filterFields($categoryData);
-            if (isset($categoryData['image'])) {
-                unset($categoryData['image']);
-                $categoryData['image'][0]['name'] = $category->getData('image');
-                $categoryData['image'][0]['url'] = $category->getImageUrl();
+
+            foreach ($category->getAttributes() as $attributeCode => $attribute) {
+                $backendModel = $attribute->getBackend();
+
+                if ($backendModel instanceof \Magento\Catalog\Model\Category\Attribute\Backend\Image) {
+                    if (isset($categoryData[$attributeCode])) {
+                        unset($categoryData[$attributeCode]);
+
+                        $categoryData[$attributeCode][0]['name'] = $category->getData($attributeCode);
+                        $categoryData[$attributeCode][0]['url'] = $category->getImageUrl($attributeCode);
+                    }
+                }
             }
+
             $this->loadedData[$category->getId()] = $categoryData;
         }
         return $this->loadedData;
--- Model/Category.php.org  2016-08-01 21:41:47.535876208 +0200
+++ Model/Category.php  2016-08-01 21:42:57.916422400 +0200
@@ -652,14 +652,15 @@
     }

     /**
-     * Retrieve image URL
+     * @param $attributeCode
      *
-     * @return string
+     * @return bool|string
+     * @throws \Magento\Framework\Exception\LocalizedException
      */
-    public function getImageUrl()
+    public function getImageUrl($attributeCode = 'image')
     {
         $url = false;
-        $image = $this->getImage();
+        $image = $this->getData($attributeCode);
         if ($image) {
             if (is_string($image)) {
                 $url = $this->_storeManager->getStore()->getBaseUrl(

4) Create file Patch-Magento_Ui-M2.1.0-allow-backend-to-know-the-origin-input-of-the-upload-request.patch under patches folder with following contains.
--- view/base/web/js/form/element/file-uploader.js.org  2016-08-01 20:33:22.866555339 +0200
+++ view/base/web/js/form/element/file-uploader.js  2016-08-01 20:33:42.384061881 +0200
@@ -302,7 +302,13 @@
                 allowed  = this.isFileAllowed(file);

             if (allowed.passed) {
-                $(e.target).fileupload('process', data).done(function () {
+                var $target = $(e.target);
+
+                $target.on('fileuploadsend', function(event, postData) {
+                    postData.data.set('param_name', this.paramName);
+                }.bind(data));
+
+                $target.fileupload('process', data).done(function () {
                     data.submit();
                 });
             } else {

5) Run following Commands

*

*composer validate composer.json (To Vallidate composer file).

*composer update

*php bin/magento setup:upgrade

6) Now its time to create your module for new file upload option.
Create a file

app\code\Vendor\Module\registration.php

\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        "Vendor_Module",
        __DIR__
    );

Create a file

app\code\Vendor\Module\etc\module.xml

<?xml version="1.0" encoding="UTF-8" ?>
    <config>
        <module name="Vendor_Module" setup_version="1.0" />
    </config>

Create a file

app\code\Vendor\Module\Setup\InstallData.php

<?php
    namespace Vendor\Module\Setup;
    use Magento\Framework\Module\Setup\Migration;
    use Magento\Framework\Setup\InstallDataInterface;
    use Magento\Framework\Setup\ModuleContextInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Catalog\Setup\CategorySetupFactory;
    class InstallData implements InstallDataInterface
    {
        public function __construct(CategorySetupFactory $categorySetupFactory)
        {
            $this->categorySetupFactory = $categorySetupFactory;
        }
        public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        {
            $installer = $setup;
            $installer->startSetup();
            $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
            $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
            $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
            $categorySetup->removeAttribute(
                \Magento\Catalog\Model\Category::ENTITY, 'featured_image' );
            $categorySetup->addAttribute(
                \Magento\Catalog\Model\Category::ENTITY, 'featured_image', [
                    'type' => 'varchar',
                    'label' => 'Featured Image',
                    'input' => 'image',
                    'backend' => 'Magento\Catalog\Model\Category\Attribute\Backend\Image',
                    'required' => false,
                    'sort_order' => 5,
                    'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                    'group' => 'General Information',
                ]
            );
            $installer->endSetup();
        }
    }

Create a file

app\code\Vendor\Module\view\adminhtml\ui_component\category_form.xml

<?xml version="1.0" encoding="UTF-8" ?>
    <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <fieldset name="content">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Content</item>
                    <item name="collapsible" xsi:type="boolean">true</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                </item>
            </argument>
            <field name="featured_image">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="dataType" xsi:type="string">string</item>
                        <item name="source" xsi:type="string">category</item>
                        <item name="label" xsi:type="string" translate="true">Featured Image</item>
                        <item name="visible" xsi:type="boolean">true</item>
                        <item name="formElement" xsi:type="string">fileUploader</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                        <item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
                        <item name="required" xsi:type="boolean">false</item>
                        <item name="sortOrder" xsi:type="number">40</item>
                        <item name="uploaderConfig" xsi:type="array">
                            <item name="url" xsi:type="url" path="catalog/category_image/upload"/>
                        </item>
                    </item>
                </argument>
            </field>
        </fieldset>
    </form>

Hope this helps you.


text:
Q: SQL shorten responds time using parallel or with clause I have a query that takes 20 min to executed... I remember in one project we used /*+ PARALLEL(T,8) / or we would use the with clause and  /+ materialize */ and it would make the query responds time really fast withing seconds. How can I do this to this query?
select count(*) from (
       select hdr.ACCESS_IND,
            hdr.SID,
             hdr.CLLI,
             hdr.DA,
             hdr.TAPER_CODE,
             hdr.CFG_TYPE  as CFG_TYPE,
             hdr.IP_ADDR,
             hdr.IOS_VERSION,
             hdr.ADMIN_STATE,
             hdr.WIRE_CENTER,
             substr(hdr.SID_IO_PRI, 1, 8)    PRI_IO_CLLI,
             substr(hdr.SID_IO_SEC, 1, 8)    SEC_IO_CLLI,
             hdr.VHO_CLLI ,
             hdr.CFG_TYPE ,
          --   dtl.MULTIPURPOSE_IND,
             lkup.code3 as shelf_type
     from      RPT_7330_HDR    hdr
     INNER JOIN   RPT_7330_DTL dtl on hdr.EID = dtl.EID
     INNER JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND
     where    LKUP.CATEGORY='ACCESS_MAPPING' and  hdr.DT_MODIFIED = (select DT_MODIFIED
                                from     LS_DT_MODIFIED
                                where NAME = 'RPT_7330_HDR')) n;

A: Try this, might be faster:
  select count(*)
  from RPT_7330_HDR hdr
  JOIN LS_DT_MODIFIED LS ON LS.NAME = 'RPT_7330_HDR' AND hdr.DT_MODIFIED = LS.DT_MODIFIED
  JOIN RPT_7330_DTL dtl on hdr.EID = dtl.EID
  JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND AND LKUP.CATEGORY='ACCESS_MAPPING'

The SQL engine can optimize JOINS to be parallel if you have the right indexes and such.  It is often able to optimize joins when it can't optimize sub-queries.

A: If you want data then
SELECT /*+ PARALLEL(DTL,4) */
            HDR.ACCESS_IND,
            HDR.SID,
            HDR.CLLI,
            HDR.DA,
            HDR.TAPER_CODE,
            HDR.CFG_TYPE AS CFG_TYPE,
            HDR.IP_ADDR,
            HDR.IOS_VERSION,
            HDR.ADMIN_STATE,
            HDR.WIRE_CENTER,
            SUBSTR ( HDR.SID_IO_PRI, 1, 8 ) PRI_IO_CLLI,
            SUBSTR ( HDR.SID_IO_SEC, 1, 8 ) SEC_IO_CLLI,
            HDR.VHO_CLLI,
            HDR.CFG_TYPE,
            LKUP.CODE3 AS SHELF_TYPE
       FROM
            RPT_7330_HDR HDR INNER JOIN RPT_7330_DTL DTL ON HDR.EID = DTL.EID
            INNER JOIN CODE_LKUP2 LKUP ON LKUP.CODE1 = HDR.ACCESS_IND
            INNER JOIN LS_DT_MODIFIED ON HDR.DT_MODIFIED = DT_MODIFIED
       WHERE
                LKUP.CATEGORY = 'ACCESS_MAPPING'
            AND NAME = 'RPT_7330_HDR';

If you want count then
SELECT /*+ PARALLEL(DTL,4) */
            COUNT (*)
       FROM
            RPT_7330_HDR HDR INNER JOIN RPT_7330_DTL DTL ON HDR.EID = DTL.EID
            INNER JOIN CODE_LKUP2 LKUP ON LKUP.CODE1 = HDR.ACCESS_IND
            INNER JOIN LS_DT_MODIFIED ON HDR.DT_MODIFIED = DT_MODIFIED
       WHERE
                LKUP.CATEGORY = 'ACCESS_MAPPING'
            AND NAME = 'RPT_7330_HDR';

Note: Hint used on DTL table which is taking more cost for FTS. Number 4 means query fired on 8 CPU's parallely. Identify your pain points from query plan and decide on your hints for parallel or any other. You can also use parallel hint on multiple tables /*+ PARALLEL(table1 4) PARALLEL(table2 4) PARALLEL(table3 4) PARALLEL(table4 4)*/ . Also This works only on Enterprise edition and not on standard edition.

A: SELECT /*+ PARALLEL */ ...

You do not want to use a magic number and you do not want to list any objects.
A degree of parallelism of 8 is probably too high on your laptop, yet too low on your production server.  If the query simply specifies PARALLEL, Oracle will automatically determine the DOP if it's configured for automatic parallelism.  Or it will default to the number of CPUs * threads per CPU * number of instances.  Judging by all the manuals, features, and whitepapers, Oracle has put a lot of thought into the degree of parallelism.  If you're not going to benchmark it you should trust the defaults.
In 11gR2, when you don't list any objects you use statement level parallelism instead of object level parallelism.  There's not need to try to determine exactly
which objects and access paths needs to be parallelized.  If you change the query or alias names later there's no chance of the hint not working.
Here's a quick introduction to the parallel hint.  There's also the
Using Parallel Execution chapter of the VLDB and Partitioning Guide.


text:
Q: is this the way to add string in infoplist file with expo bare workflow in sdk 39? #ReactNative {
  "expo": {
    "name": "Light",
    "slug": "Light",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "userInterfaceStyle": "automatic",
    "ios": {
      "userInterfaceStyle": "automatic",
      "bundleIdentifier": "com.ShivBaapYaadHai.Light",
      "buildNumber": "1.5.0",
      "infoPlist": {
        "NSCameraUsageDescription": "Enable Camera Acess so that you can record  Videos",
        "NSMicrophoneUsageDescription": "Enable Microphone Access so that you can start recording audio ",
        "NSPhotoLibraryUsageDescription": "Enable Camera Roll Access so that you can select Other Videos from Camera Roll"
      }
    },
    "android": {
      "userInterfaceStyle": "automatic",
      "package": "com.ShivBabaYaadHai.Light",
      "versionCode": 1
    },
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "web": {
      "favicon": "./assets/favicon.png"
    }
  }
}

this is my app.json file so is this the way to add infoplist file in expo bare workflow ya some other way because I need to add some string when system ask permissions from user.

A: Yes, you've got it. That is the same shape as my app.json that sets expo.ios.infoPlist and requests similar permissions.


text:
Q: Highcharts remove() Inconsistencies I have a highchart and I simply want to remove a bar from it.  Sounds simple, but the remove() method works differently depending on which data point I access.
Something like...
chart.series[0].data[0].remove();

...works nicely.  Removes the bar and the category associated with the bar.  Now a small change:
chart.series[0].data[1].remove();

and while the bar is removed the category is not.  Trying to modify the categories and use setCategory does not alleviate the issue.
Please see: http://jsfiddle.net/FxY63/2/
What kind of magic do I need to cast to so that pressing "Remove Point 2" properly cleans up the categories array and leaves the correct number of tics on the y-axis?

A: This appears to be the only solution I could come up with from my searching.  Storing your categories and data into arrays, and depending on the index you want to remove splice the data/category out of the arrays and re-set the category/data to the chart causing it to redraw with the new data.
Fiddle Demo:  http://jsfiddle.net/3dcbY/
var categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var data = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];

// button handler
$('#button1').click(function() {
    var series = chart.series[0];
    if (series.data.length) {
        categories.splice(0,1);
        data.splice(0,1);

        series.setData(data);
        chart.xAxis[0].setCategories(categories);
    }
});

// button handler
$('#button2').click(function() {
    var series = chart.series[0];
    if (series.data.length) {
        categories.splice(1,1);
        data.splice(1,1);

        series.setData(data);
        chart.xAxis[0].setCategories(categories);
    }
});


text:
Q: How can we access RLP encoded signed raw transaction in solidity? I know how to create a raw transaction for Ethereum because there are many articles like this.
But I don't know how to access the raw transactions in Solidity.
Msg object give us msg.data, msg.sender, msg.sig and msg.value.
These parameters are convenient but I want the RLP encoded signed raw transaction.
How can I access the raw data?
Is there any global variable like tx.raw?
Or Is it impossible?
Thanks in advance.

A: To my knowledge, the raw transaction is not exposed to Solidity.


text:
Q: How can we pass variable values at queue time to multi stage yaml build I want to allow users to override some values of variables used in multistage yaml pipelines.
I found this and tried but it didn't work , i'm not sure if i'm using it correctly. There is no example available in docs as well.

A: Don't specify the variable in the YAML file's variables section. Author the whole workflow and save it. Then open the Variables tab of the build definition (this is in the UI), create the variable there, set a default value and check the 'allow at queue time'.


text:
Q: Why can't I say "I have a brown hair"? Why can't I say, "I have a brown hair," to describe the colour of my hair?

A: When describing the hair on one's head, the noun hair takes on a collective sense, i.e. hair is treated as uncountable. Thus, the correct way to describe your hair (presumably that on your head) color is:

I have brown hair.

However, hair is also a countable noun, e.g. "Who knows the number of hairs on their head?" Hence,

I have a brown hair

is also perfectly valid, but it would usually imply that that a particular brown hair is special—perhaps one in a billion black hairs, or something of the sort.

A: ***Normally when you say one's hair you mean not just one but a mass, certainly thousands of hairs in one's head. That's why it should sound more appropriate to use hair as an uncountable noun without indefinite article. you can say: I have brown hair, but if you say I have a brown hair, the reader or listener is more likely to understand that you have one hair which is brown among a mass of black hairs.


text:
Q: Is it more performant to use a sprite or a BufferedGeometry in Three.js? I'm rewriting a legacy visualization built several years ago with an older version of Three.js. The visualization is ~20k 2D circles (nodes from a graph) drawn on a screen with positions and coloring already determined.
There's no animation involved other than when interaction occurs (zooming, clicking, etc). The previous author used sprites for the circles (nodes) to show different states (node selected: glowing effect, node hidden: transparent, etc)
I've been able to successfully reproduce much of the visualization using CircleBufferGeometry instead of a sprite.
I know this is potentially too vague a question, given it might be too specific to my use case, but I'm wondering if anyone has any insight into whether it's more performant to render ~20k sprites or ~20k CircleBufferGeometry with Three.js / webgl.
Thanks!

A: CircleBufferGeometry will have many more vertices per entity than a sprite would since sprites should be drawn with gl.POINTS ( one point == one vertex ). Your vertex shader would process more vertices with the circle than it would with a sprite.


text:
Q: Derive equations of all lines which are tangent to the graph of y= -7 - x^2 and passing through the point (3,0). (This point is not on the graph). I don't know how to start this.
So since the lines are tangent to the given equation, then the derivative will = 0, right?
So how do I find the correct x and y to put in the tangent line equation? I can't just plug in 3 for x in the original equation, can I?

A: Let's derive the equation of the tangent line at the point $(x_1,y_1)$.
The gradient is $\cfrac {dy}{dx}=-2x$. At $(x_1, y_1)$ this has the value $-2x_1$.
Now the line with gradient $m$ which passes through the point $(x_1,y_1)$ is best written as $y-y_1=m(x-x_1)$ [note below] $= -2x_1(x-x_1)$.
Now you have the equation of the line, you can find the condition for $(3,0)$ to lie on the line. You may be able to simplify it/modify it by using the condition that $(x_1,y_1)$ is on the curve.
Note: $\cfrac {dy}{dx}=\lim_{x\to x_1} \cfrac {y-y_1}{x-x_1}$ and this is directly related to the form of the tangent as $(x-x_1)\cfrac {dy}{dx}=y-y_1$ - the straight line which most closely approximates the curve.


text:
Q: Are there any good resources/best-practices to "industrialize" code in R for a data science project? I need to "industrialize" an R code for a data science project, because the project will be rerun several times in the future with fresh data. The new code should be really easy to follow even for people who have not worked on the project before and they should be able to redo the whole workflow quite quickly. Therefore I am looking for tips, suggestions, resources and best-practices on how to achieve this objective.
Thank you for your help in advance!

A: You can make an R package out of your project, because it has everything you need for a standalone project that you want to share with others :

*

*Easy to share, download and install

*R has a very efficient documentation system for your functions and objects when you work within R Studio. Combined with roxygen2, it enables you to document precisely every function, and makes the code clearer since you can avoid commenting with inline comments (but please do so anyway if needed)

*You can specify quite easily which dependancies your package will need, so that every one knows what to install for your project to work. You can also use packrat if you want to mimic python's virtualenv

*R also provide a long format documentation system, which are called vignettes and are similar to a printed notebook : you can display code, text, code results, etc. This is were you will write guidelines and methods on how to use the functions, provide detailed instructions for a certain method, etc. Once the package is installed they are automatically included and available for all users.

*The only downside is the following : since R is a functional programming language, a package consists of mainly functions, and some other relevant objects (data, for instance), but not really scripts.

More details about the last point if your project consists in a script that calls a set of functions to do something, it cannot directly appear within the package. Two options here : a) you make a dispatcher function that runs a set of functions to do the job, so that users just have to call one function to run the whole method (not really good for maintenance) ; b) you make the whole script appear in a vignette (see above). With this method, people just have to write a single R file (which can be copy-pasted from the vignette), which may look like this :
library(mydatascienceproject)
library(...)
...
dothis()
dothat()
finishwork()

That enables you to execute the whole work from a terminal or a distant machine with Rscript, with the following (using argparse to add arguments)
Rscript myautomatedtask.R --arg1 anargument --arg2 anotherargument

And finally if you write a bash file calling Rscript, you can automate everything !
Feel free to read Hadley Wickham's book about R packages, it is super clear, full of best practices and of great help in writing your packages.

A: One can get lost in the multiple files in the project's folder, so it should be structured properly: link
Naming conventions that I use: first, second.
Set up the random seed, so the outputs should be reproducible.
Documentation is important: you can use the Roxygen skeleton in rstudio (default ctrl+alt+shift+r).
I usually separate the code into smaller, logically cohesive scripts, and use a main.R script, that uses the others.
If you use a special set of libraries, you can consider using packrat. Once you set it up, you can manage the installed project-specific libraries.


text:
Q: Jquery UI Resizable with box-sizing: "border-box" issue I'm currently using Jquery resizable ( http://api.jqueryui.com/resizable/ )
and I have noticed that it does not work well with "box-sizing: border-box;".
I have googled it and couldn't get the solid answer.. (maybe I haven't spent enough time..)
Someone already posted an example of a problem exactly same as mine on js fiddle already:
(http://jsfiddle.net/muNjL/)

I'm not sure if solution to this issue is out yet...
If I have no option but to not use border-box, please let me know. I will be very appreciated.
Thank you for reading and happy coding!
-Danny C

A: Why are you border-boxing everything? Normalization?
Try JSFiddle's Normalize CSS under the Fiddle Options on the left. I assume it loads normalize.css. Then remove all your border-box declarations. Your resizable should now expand to the entire width and height of the parent container.
#container {
    width: 300px;
    height: 300px;
    background: #888;
}

#container #ohboxme {
    background: #FFF;
    border: 1px solid grey;
    padding: 10px;
    width: 200px;
    height: 100px;
    font-size: 10px;
}

A: This is a known bug with jqueryui resizable ... see http://bugs.jqueryui.com/ticket/8932
The best solution for now is to switch to using css 'outline' instead of 'border'.
Essentially if you set a border then it alters the value returned by jquery's width() function. This means that the resizeable widget thinks the box is smaller than it actually is.


text:
Q: MySql dynamic column name [major edit to make things clear]
I want to write a query that returns a dynamic column name like this:

    SELECT
        f2 AS
    (
        SELECT column_name
        FROM column_names_tbl
        WHERE column_name = "experience"
                limit 0,1
    )
    FROM some_table

so that would output the same as this:

    SELECT
        f2 AS experience
    FROM some_table

A: This is no correct SQL syntax, even because the two queries (the selected field and it's alias) are both subqueries and unrelated to each other. So, there's also no possibility for mysql to distinguish what name you want to connect to what value, even if the syntax was correct...
You already use a more or less normalized relational table, so I suggest the following solution:

*

*you select the revision ID and name in a separate query; store them in PHP and use them for whatever you want

*next, you evaluate the following query into a separated result set: SELECT ps.keyname, psv.keyvalue FROM page_setting_values AS psv INNER JOIN page_settings AS ps ON ps.id = psv.setting_id WHERE psv.page_revision_id = :revision with :revision representing your revision id

*you may now assemble an associated array from that result set:
$settings = [];
 $result = $db->executeQuery('...')->fetchAll();
 foreach($result as $setting)
 {
     $settings[$setting['keyname']] = $setting['keyvalue'];
 }
Hope that helps ;)


text:
Q: How to get data in past 30 days in MYSQL and Print Past 30 days inside a loop using a variable in php I need to get past 30 days sales records from MYSQL database to display in a bar chart how many items sold each day. Also I need to display past 30 days in my chart x axis in my php document. I tried run this code inside a for loop. because I am running some other codes to display some data using this loop. Take a look at the following code and help me how to achieve this.
This is the table I try to get data from

Date format (YYYY-MM-DD)

Products Table

product_id | sold_by | qty | added_date  | sold_date
-----------+---------+-----+-------------+-----------
3          | 12      | 7   | 2022-05-05  | 2022-07-28
3          | 12      | 7   | 2022-05-05  | 2022-07-29
3          | 12      | 7   | 2022-05-05  | 2022-07-30
3          | 12      | 1   | 2022-05-05  | 2022-07-30
3          | 12      | 2   | 2022-05-05  | 2022-07-30
6          | 22      | 4   | 2022-06-06  | 2022-07-31
8          | 11      | 6   | 2022-08-05  | 2022-07-31

Deleted Table

product_id | added_date  | delete_date
-----------+-------------+-----------
3          | 2022-05-05  | 2022-07-28
3          | 2022-05-05  | 2022-07-29
3          | 2022-05-05  | 2022-07-30
3          | 2022-05-05  | 2022-07-30
3          | 2022-05-05  | 2022-07-30
6          | 2022-06-06  | 2022-07-31
8          | 2022-08-05  | 2022-07-31

As you can see for some days I have multiple records.
<?php
//for loop to run 30 times to get 30 days results
for ($i = 30; $i >= 0; $i--) {
   $sold_products_count = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM products WHERE sold_date = CURRENT_DATE - $i"));
   $deleted_count = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM deleted WHERE delete_date = CURRENT_DATE - $i"));
?>
{
<?php
   $current_date = date("Y-m-d");
   $new_date = date_create($current_date);
   date_sub($new_date, date_interval_create_from_date_string("$i day"));
?>
   x: '<?php echo date_format($new_date, "Y-m-d"); ?>',
   a: <?php echo $deleted_count; ?>,
   s: <?php echo $sold_products_count; ?>,
},
<?php
}
?>

x- X axis data in the chart
a - number of products deleted in specific date
s - number of products sold in specific date
With the above code I was able to print the x axis data. I am not sure how to get past 30 days data from the SQL database. I think the problem is in the $i part in the SQL query.

A: In your query, if you use INTERVAL, you can use some days for adding/reducing from the current or specific date.
For example in your case, if you always want to get the last 30 days data, you can use your WHERE like this:
sold_date >= CURDATE() - INTERVAL 30 DAY


text:
Q: Polyline clear bug after 3 re-paint This is the all routes provided by my source and destination location:
image_1

This is the route 1 selected (black): image_2

This is the route 2 selected (black ): image_3

Now, when I select the route 1, latter the route 2, and latter the
route 1 again, and latter the route 2, this happens: the polyline is
not full black, what's happens her?: image_4

This is another bug, the polyline end not fully filled: image_5

code snippet:

var routes;
var polylines = [];
var indexSelected;

var map, directionsService;

var sourceLatLng = {lat: -3.0894037, lng: -59.9984166};
var destinationLatLng = {lat: -3.0944183, lng: -60.0231688};

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: sourceLatLng,
zoomControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
streetViewControl: false,
mapTypeControl: false,
//zoom: 16
});
directionsService = new google.maps.DirectionsService();

var source = new google.maps.Marker({
position: sourceLatLng,
map: map,
title: 'source'
});

var destination = new google.maps.Marker({
position: destinationLatLng,
map: map,
title: 'destination'
});

getRoutes();
}

function getRoutes(){
var requestOptions = {
origin: sourceLatLng,
destination: destinationLatLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true
};
directionsService.route(requestOptions, function(response, status) {

if (status == google.maps.DirectionsStatus.OK) {
routes = response.routes;
drawRoutes();
}else{
alert('error loading route request');
}
});
}

function drawRoutes(indexSelected = null) {
if(this.indexSelected  !== undefined && this.indexSelected == indexSelected){
return;
}

var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];

var bounds = new google.maps.LatLngBounds();
//clear map
for (var i = 0; i < polylines.length; i++) {
polylines[i].setMap(null);
}
polylines = [];

// Loop through each route
for (var i = 0; i < routes.length; i++) {
//draw own polilyne with event click
var color = colors[i];
if(indexSelected != null && i == indexSelected){
this.indexSelected = indexSelected;
continue;
}

var polylineOptions = {
strokeColor: color,
strokeWeight: 8
};
drawPolyline(routes[i], polylineOptions, listener, [i], polylines, bounds);
} // End route loop

if(indexSelected != null){
var polylineOptions = {
strokeColor: 'black',
strokeWeight: 8
};
drawPolyline(routes[indexSelected], polylineOptions, listener, [indexSelected], polylines, bounds);
}

//fitBounds
map.fitBounds(bounds);
}

function drawPolyline(route, polylineOptions, stepPolylineClickListener, stepPolylineClickListenerArguments, polylines = null, bounds = null){
for (i = 0; i < route.legs.length; i++) {
var steps = route.legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
var stepPolyline = new google.maps.Polyline(polylineOptions);
for (k = 0; k < nextSegment.length; k++) {
stepPolyline.getPath().push(nextSegment[k]);
if(bounds != null){
bounds.extend(nextSegment[k]);
}
}
if(polylines != null){
polylines.push(stepPolyline);
}
stepPolyline.setMap(map);
// route click listeners, different one on each step
google.maps.event.addListener(stepPolyline, 'click', function(event) {
with ({ newStepPolylineClickListener: stepPolylineClickListener }) {
newStepPolylineClickListener(event, this, stepPolylineClickListenerArguments);
}
});
}
}
}

function listener(event, stepPolyline, stepPolylineClickListenerArguments){
drawRoutes(stepPolylineClickListenerArguments[0]);
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}

<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">

A: You need to move the "selected" polyline to the top (above the unselected polylines).
var polylineOptions = {
  strokeColor: color,
  strokeWeight: 8,
  zIndex: 1             // 1 is below 10
};

// snip
if (indexSelected != null) {
  var polylineOptions = {
    strokeColor: 'black',
    strokeWeight: 8,
    zIndex: 10         // 10 is above 1
  };

updated code snippet:

var routes;
var polylines = [];
var indexSelected;

var map, directionsService;

var sourceLatLng = {
  lat: -3.0894037,
  lng: -59.9984166
};
var destinationLatLng = {
  lat: -3.0944183,
  lng: -60.0231688
};

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: sourceLatLng,
    zoomControl: false,
    scrollwheel: false,
    disableDoubleClickZoom: true,
    streetViewControl: false,
    mapTypeControl: false,
    //zoom: 16
  });
  directionsService = new google.maps.DirectionsService();

  var source = new google.maps.Marker({
    position: sourceLatLng,
    map: map,
    title: 'source'
  });

  var destination = new google.maps.Marker({
    position: destinationLatLng,
    map: map,
    title: 'destination'
  });

  getRoutes();
}

function getRoutes() {
  var requestOptions = {
    origin: sourceLatLng,
    destination: destinationLatLng,
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    provideRouteAlternatives: true
  };
  directionsService.route(requestOptions, function(response, status) {

    if (status == google.maps.DirectionsStatus.OK) {
      routes = response.routes;
      drawRoutes();
    } else {
      alert('error loading route request');
    }
  });
}

function drawRoutes(indexSelected = null) {
  if (this.indexSelected !== undefined && this.indexSelected == indexSelected) {
    return;
  }

  var colors = ['red', 'green', 'blue', 'orange', 'yellow', 'black'];

  var bounds = new google.maps.LatLngBounds();
  //clear map
  for (var i = 0; i < polylines.length; i++) {
    polylines[i].setMap(null);
  }
  polylines = [];

  // Loop through each route
  for (var i = 0; i < routes.length; i++) {
    //draw own polilyne with event click
    var color = colors[i];
    if (indexSelected != null && i == indexSelected) {
      this.indexSelected = indexSelected;
      continue;
    }

    var polylineOptions = {
      strokeColor: color,
      strokeWeight: 8,
      zIndex: 1
    };
    drawPolyline(routes[i], polylineOptions, listener, [i], polylines, bounds);
  } // End route loop

  if (indexSelected != null) {
    var polylineOptions = {
      strokeColor: 'black',
      strokeWeight: 8,
      zIndex: 10
    };
    drawPolyline(routes[indexSelected], polylineOptions, listener, [indexSelected], polylines, bounds);
  }

  //fitBounds
  map.fitBounds(bounds);
}

function drawPolyline(route, polylineOptions, stepPolylineClickListener, stepPolylineClickListenerArguments, polylines = null, bounds = null) {
  for (i = 0; i < route.legs.length; i++) {
    var steps = route.legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      var stepPolyline = new google.maps.Polyline(polylineOptions);
      for (k = 0; k < nextSegment.length; k++) {
        stepPolyline.getPath().push(nextSegment[k]);
        if (bounds != null) {
          bounds.extend(nextSegment[k]);
        }
      }
      if (polylines != null) {
        polylines.push(stepPolyline);
      }
      stepPolyline.setMap(map);
      // route click listeners, different one on each step
      google.maps.event.addListener(stepPolyline, 'click', function(event) {
        with({
          newStepPolylineClickListener: stepPolylineClickListener
        }) {
          newStepPolylineClickListener(event, this, stepPolylineClickListenerArguments);
        }
      });
    }
  }
}

function listener(event, stepPolyline, stepPolylineClickListenerArguments) {
  drawRoutes(stepPolylineClickListenerArguments[0]);
}
html,
body, #map {
  height: 100%;
  margin: 0;
  padding: 0;
}

  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">


text:
Q: how to convert an entire column's datatype from number to timestamp in snowflake This statement gives me  an error
      SELECT cast(FHEFTJ as Timestamp)

however this works for
          SELECT cast('108353' as Timestamp)

I wanted the entire columns datatype to timestamp so tried the above but it doesn't work
given entry 108353
wanted result as 1970-01-02 06:05:53.000

A: I assume you are trying to convert a table of values with FHEFTJ as the column name.  You need to reference the table, though.
SELECT FHEFTJ::timestamp
FROM tablename;

or
SELECT to_timestamp(FHEFTJ)
FROM tablename;

or
SELECT CAST(FHEFTJ as timestamp)
FROM tablename;

A: I am assuming that FHEFTJ is one of the row value you have and its throwing error converting it to timestamp. try_to_numeric function first checks if its a number that can be converted.
SELECT CAST(try_to_NUMERIC(FHEFTJ) as Timestamp)  FHEFTJ_datetimE FROM
(
SELECT '103353' FHEFTJ
union
SELECT '108353' FHEFTJ
union
SELECT 'Somevalue'  FHEFTJ
) ;


text:
Q: RectTransform.deltaSize not working in Unity I have a selection menu code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SelectionMenu : MonoBehaviour
{
    public List<MenuButton> buttons = new List<MenuButton>();
    public GameObject canvas;
    private Vector2 Mouseposition;
    private Vector2 fromVector2M = new Vector2(0.5f, 1.0f);
    private Vector2 centercircle = new Vector2(0.5f, 0.5f);
    private Vector2 toVector2M;

    public int menuItems;
    public int CurMenuItem;
    private int OldMenuItem;
    private bool isDone = false;
    // Start is called before the first frame update
    void Start()
    {
        canvas.SetActive(false);
        menuItems = buttons.Count;
        foreach (MenuButton button in buttons)
        {
            button.sceneImage.color = button.NormalColor;
        }
        CurMenuItem = 0;
    }

    // Update is called once per frame
    void Update()
    {
        GetCurrentMenuItem();
        if (Input.GetButtonDown("Fire1"))
            ButtonAction();
        if (Input.GetKey(KeyCode.Mouse1) && !isDone)
        {
            canvas.SetActive(true);
            CrossHair.ok = true;
        }
        else
        {
            canvas.SetActive(false);
            CrossHair.ok = false;
        }
        if (Input.GetKeyUp(KeyCode.Mouse1))
        {
            isDone = false;
        }
    }

    public void GetCurrentMenuItem()
    {
        Mouseposition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        toVector2M = new Vector2(Mouseposition.x / Screen.width, Mouseposition.y / Screen.height);
        float angle = (Mathf.Atan2(fromVector2M.y - centercircle.y, fromVector2M.x - centercircle.x) - Mathf.Atan2(toVector2M.y - centercircle.y, toVector2M.x - centercircle.x)) * Mathf.Rad2Deg;
        if (angle < 0)
            angle += 360;
        CurMenuItem = (int)(angle / (360 / menuItems));
        if(CurMenuItem != OldMenuItem)
        {
            buttons[OldMenuItem].sceneImage.color = buttons[OldMenuItem].NormalColor;
            RectTransform oldTrans = buttons[OldMenuItem].sceneImage.gameObject.GetComponent<RectTransform>();

            oldTrans.sizeDelta = new Vector3(250, 250);
            Debug.Log("Resized: " + buttons[OldMenuItem].name);
            OldMenuItem = CurMenuItem;

            buttons[CurMenuItem].sceneImage.color = buttons[CurMenuItem].HighlightedColor;
            RectTransform newTrans = buttons[CurMenuItem].sceneImage.gameObject.GetComponent<RectTransform>();
            oldTrans.sizeDelta = new Vector3(280, 280);
        }
    }

    public void ButtonAction()
    {
        buttons[CurMenuItem].sceneImage.color = buttons[CurMenuItem].PressedColor;
        if(CurMenuItem == 0)
        {
            SetColor.color = buttons[CurMenuItem].HighlightedColor;
        }
        isDone = true;
    }
}
[System.Serializable]
public class MenuButton
{
    public string name;
    public Image sceneImage;
    public Color NormalColor = Color.white;
    public Color HighlightedColor = Color.grey;
    public Color PressedColor = Color.gray;

}

Everything works as intended except one thing: the scaling does not work as intended. This line:
oldTrans.sizeDelta = new Vector3(280, 280);

this line runs only after I leave the highlighted selection (menuItem/Button)
and not when It starts highlighting. Its weird because one line before it I set the button to be highlighted and this line wont run until after its not highlighted anymore. also, this line:
oldTrans.sizeDelta = new Vector3(250, 250);

doesn't run at all. The Debug.Log that appears right after that line logs every time.

A: You can't modify sizeDelta directly
sizeDelta tells you how much bigger or smaller this RectTransform is relative to its parent. In order to change this, you have to modify the anchors. If you are trying to set the RectTransform to have a size based on its content, then maybe SetSizeWithCurrentAnchors() is what you're looking for.


text:
Q: Using dropdown as input template within PrimeNG turbotable I am using PrimeNG TurboTable and I want to integrate p-dropdown component inside the input template within PrimeNG Turbotable. The problem is when I use the following code, the selected element can not be assigned to the value table.
<ng-template pTemplate="body" let-rowData let-row="rowIndex">

        {{listRow[row]}}
        <ng-container *ngIf="edit">

              <ng-template pTemplate="input">

              </ng-template>
              <ng-template pTemplate="output">
                {{rowData[i]}}
              </ng-template>

        </ng-container>
        <ng-container *ngIf="!edit">
          {{rowData[i]}}
        </ng-container>

    </ng-template>

A: Here's a working example:
  <ng-template pTemplate="body" let-rowData let-columns="columns" let-rowIndex="rowIndex">

      {{rowIndex+1}}

            <ng-template pTemplate="input">

            </ng-template>
            <ng-template pTemplate="output">
              {{rowData[col.field]}}
            </ng-template>

            <ng-template pTemplate="input">
              <input type="text" [(ngModel)]="rowData[col.field]">
            </ng-template>
            <ng-template pTemplate="output">
              {{rowData[col.field]}}
            </ng-template>

  </ng-template>

Plunker example


text:
Q: Is there a way to specify a secret for all environments in secrets.yml from rails 4.1? Like the question states, is there a way to make a secret known to all 3 environments without copy and pasting like this?
secrets.yml
development:
  secret_key_base: ...
  my_global_secret: foo

test:
  secret_key_base: ...
  my_global_secret: foo

production:
  secret_key_base: ...
  my_global_secret: foo

A: You can define and share a common key using &label and <<: *label
common: &common
  secret_key_base: ...
  my_global_secret: foo

development:
  <<: *common
  something_specific_to_development: ...

test:
  <<: *common
  something_specific_to_test: ...

production:
  <<: *common
  something_specific_to_production: ...

Update: For Rails 5.1+
Rails 5.1 adds the shared key which is automatically applied to all environments:
shared: # Everything nested under this key is automatically shared
  secret_key_base: ...
  my_global_secret: "foo"

development:
  my_global_secret: "override value for dev"

test:
  ...

A: Using common: &common didn't work for me with Rails 5.1 - shared: did though.


text:
Q: Centering a  with a max-width, using Javascript/JQuery I've been looking for a way to center a div with a set max-width. I assumed I could do so by giving the div a max-width of 90% and an auto margin, then use jQuery to find and set a fixed width, which I hoped, the auto margin would then center for me.
Something like the following.
JQuery:
$(function(){
    $wrap = $('#wrap');

    $wrap.width($wrap.width());
});

CSS:
#wrap {
    max-width:90%;
    margin:auto;
}

HTML:

So basically, I wanna make a wrapper div that I can jam full of images, but will not exceed 90% screen width; take wrapper and center it. Is this possible? I understand my JQuery thinking is almost certainly wrong. I'm very new to it, but I assumed that Javascript is the way to go about this.

A: No Javascript needed, everything is fine.
http://jsfiddle.net/Kyle_Sevenoaks/RvLuE/

A: In case anyone else is curious, I figured out a JQuery way to do what I wanted.
I have a bunch of uniformly sized images that I want in a scale-able div which also has a 90% max-width. Here's what I came up with:
JQuery:
function divResize() {
var divWidth;
var extra;
divWidth = $(window).width() * .9;
extra  = divWidth % /*IMAGE SIZE IN PX*/;
divWidth = (divWidth - extra);
  $("#wrap").css({ width: divWidth });
}

$(document).ready(divResize);
$(window).resize(divResize);

CSS:
#wrap {
    margin:auto;
}

HTML:

I guess my real problem was that I couldn't adequately explain my problem. Thanks for the help everybody.

A: What isn't working here? This works fine for me, but I don't think you need javascript?

a a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa a
a

A: If you want to center a possibly short row, set wrap's text-align to center, or make it display:inline-block if you have a border you need to show.


text:
Q: Loop through columns and run frequency (count*) on each column in MySQL I'm trying to write a script that takes a simple query like this:
select col1, count(*)
from city
group by col1
order by 2 desc

And does it for every column. Ideally it'd be nice if the results were side-by-side (can you union columns?)
EDIT:
I figured it out. It took 3.5 hours but I got there. First time using stored procedures and dynamic SQL so it was a good learning experience.
---- This stored procedure takes the database name and table name and will run a frequency on each column.

DELIMITER $$
 DROP PROCEDURE IF EXISTS Data_Audit$$
 CREATE PROCEDURE Data_Audit(db_name varchar(100), tbl_name varchar(100))
       BEGIN
                -- set up variables
               DECLARE col_number  int;
                    DECLARE sql_code varchar(255);
               SET col_number =  0;
               SET @total_rows = 0;
               SET @col_count = 0;

               -- Set variable to number of columns. Used for number of loops
               SELECT COUNT(*)
               into @col_count
                    FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE table_schema = db_name
                    AND table_name = tbl_name;

                    -- Set variable to number of rows
                    set @row_count_code = concat ('set @row_count = (select count(*) FROM ',tbl_name,')');

                    PREPARE stmt FROM @row_count_code;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    set @drop_new_table = concat('
                    drop table if exists ',
                    db_name,
                    '.',
                    tbl_name,
                    '_frequency;');

                    PREPARE stmt FROM @drop_new_table;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    -- Create basic table structure

                    set @create_new_table = concat('
                    create table ',
                    db_name,
                    '.',
                    tbl_name,
                    '_frequency',
                    ' (Column_Value varchar(100), Frequency varchar(100),Frequency_percent varchar(50))'
                    ';');

                    -- select @create_new_table
                    PREPARE stmt FROM @create_new_table;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    -- Loop through columns
               WHILE col_number  < @col_count DO
                            SET  col_number = col_number + 1;
                           -- SET @sql = NULL;
                          --  set @col_num = col_number;
                                    SELECT column_name
                                     INTO @sql_code
                                      FROM INFORMATION_SCHEMA.COLUMNS
                                     WHERE table_schema = db_name
                                       AND table_name = tbl_name
                                       AND ordinal_position = col_number;

                                     -- This is the main query. Inserts each time into the new table
                                     SET @sql = CONCAT('insert into ',
                                                             db_name,
                                                              '.',
                                                              tbl_name,
                                                              '_frequency Select ''', upper(@sql_code), ''',''Frequency'',''Frequency_percent'' UNION ALL (SELECT `',
                                                             @sql_code,
                                                             '` , count(*), concat(truncate((count(*) / ',
                                                             @row_count,
                                                             ') *100,2),''%'') as Frequency FROM ',
                                                             tbl_name,
                                                             ' group by `',
                                                             @sql_code,
                                                             '` order by 2 desc limit 30) UNION ALL Select '''','''',''''');

                                    PREPARE stmt FROM @sql;
                                    EXECUTE stmt;
                                    DEALLOCATE PREPARE stmt;

              END WHILE;

     END$$
   DELIMITER ;

call Data_Audit('world','country');

A: I figured it out. It took 3.5 hours but I got there. First time using stored procedures and dynamic SQL so it was a good learning experience.
---- This stored procedure takes the database name and table name and will run a frequency on each column.

DELIMITER $$
 DROP PROCEDURE IF EXISTS Data_Audit$$
 CREATE PROCEDURE Data_Audit(db_name varchar(100), tbl_name varchar(100))
       BEGIN
                -- set up variables
               DECLARE col_number  int;
                    DECLARE sql_code varchar(255);
               SET col_number =  0;
               SET @total_rows = 0;
               SET @col_count = 0;

               -- Set variable to number of columns. Used for number of loops
               SELECT COUNT(*)
               into @col_count
                    FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE table_schema = db_name
                    AND table_name = tbl_name;

                    -- Set variable to number of rows
                    set @row_count_code = concat ('set @row_count = (select count(*) FROM ',tbl_name,')');

                    PREPARE stmt FROM @row_count_code;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    set @drop_new_table = concat('
                    drop table if exists ',
                    db_name,
                    '.',
                    tbl_name,
                    '_frequency;');

                    PREPARE stmt FROM @drop_new_table;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    -- Create basic table structure

                    set @create_new_table = concat('
                    create table ',
                    db_name,
                    '.',
                    tbl_name,
                    '_frequency',
                    ' (Column_Value varchar(100), Frequency varchar(100),Frequency_percent varchar(50))'
                    ';');

                    -- select @create_new_table
                    PREPARE stmt FROM @create_new_table;
                    EXECUTE stmt;
                    DEALLOCATE PREPARE stmt;

                    -- Loop through columns
               WHILE col_number  < @col_count DO
                            SET  col_number = col_number + 1;
                           -- SET @sql = NULL;
                          --  set @col_num = col_number;
                                    SELECT column_name
                                     INTO @sql_code
                                      FROM INFORMATION_SCHEMA.COLUMNS
                                     WHERE table_schema = db_name
                                       AND table_name = tbl_name
                                       AND ordinal_position = col_number;

                                     -- This is the main query. Inserts each time into the new table
                                     SET @sql = CONCAT('insert into ',
                                                             db_name,
                                                              '.',
                                                              tbl_name,
                                                              '_frequency Select ''', upper(@sql_code), ''',''Frequency'',''Frequency_percent'' UNION ALL (SELECT `',
                                                             @sql_code,
                                                             '` , count(*), concat(truncate((count(*) / ',
                                                             @row_count,
                                                             ') *100,2),''%'') as Frequency FROM ',
                                                             tbl_name,
                                                             ' group by `',
                                                             @sql_code,
                                                             '` order by 2 desc limit 30) UNION ALL Select '''','''',''''');

                                    PREPARE stmt FROM @sql;
                                    EXECUTE stmt;
                                    DEALLOCATE PREPARE stmt;

              END WHILE;

     END$$
   DELIMITER ;

call Data_Audit('world','country');


text:
Q: How we approach RLC circult from RLGC model? In the text, it introduces a practical model to investigate a transmission line (like BNC cable), it considers the transmission line has resistive $R$, inductance $L$, conductance $G$ and capacitance $C$. The model is illustrated as follow

It is easy to derive the (telegraph) equations and figure out the impedance Z to be
$$Z = \sqrt{\frac{R+iX_L}{G+i/X_C}}$$
where $i$ is the imaginary unit, $\omega$ is the angular frequency, $X_L$ is the inductive reactance and $X_C$ is the capacitive reactance.
And in other section, it introduce a RC circuit and RLC circuit, in which, the impedance are
$$Z_{RC} = \sqrt{R^2 + X_C^2}, \qquad Z_{RLC}=\sqrt{R^2 + (X_L - X_C)^2}$$
It is pretty confusing because from RLGC model, if we make the electrical conductance $G$ to zero and consider no inductance ($L=0$), so the circuit becomes RC circuit, but from the first equation for the impedance given by the RLGC model, the impedance should be
$$Z = \sqrt{-iRX_C}$$
Why are they not the same? How to approach RC and RLC case from RLGC model?

A: They are different because in a transmission line we have distributed resistance, capacitance, conductance and inductance (meaning that each tiny segment of transmission line has its own tiny resistance, capacitance, conductance and inductance) while in RLC circuits we have lumped resistance, inductance and capacitance. Also RLGC doesn't model a transmission line with the circuit you've shown above but with infinite number of them in series.
We know well how to deal with lumped elements and circuits containing them, but dealing with distributed elements and circuits (e.g transmission lines) is often much harder and we have to resort to solving Maxwell equations directly. So I think not only there's no point in approaching RLC circuits from RLGC model but also it's impractical.


text:
Q: How to insert static values in wpf datagrid comboBox column? Hi guys i am working with wpf Datagrid ,i need to have a datagridcomboBox column and i need to have some static values in that column .I have tried following way but the data inside column is not displaying.
              <DataGrid
                    Grid.Row="4"
                    Height="200"
                    Width="500"
                    Grid.ColumnSpan="2"
                    Margin="10,10,0,0"
                    HorizontalAlignment="Left"
                    AutoGenerateColumns="False"
                    ItemsSource="{Binding SSID}"
                    >

                    <DataGrid.Columns>
                        <DataGridTextColumn Width="100" Header="Network ID" Binding="{Binding _networkID}"/>
                        <DataGridTextColumn Width="100" Header="SSID" Binding="{Binding _ssid}"/>
                        <DataGridComboBoxColumn Width="100" Header="Profile/Groups" SelectedItemBinding="{Binding _apProfiles}" />
                    </DataGrid.Columns>
                </DataGrid>

public List<string> _apProfiles = new List<string>()
       {
            "21-ARC1000MAP , Indoor Radio b/g/n",
             "22-ARC2000MAP , Dual Radio a/n, b/g/n"
       };

Kindly guide me how to solve this issue.Any help would be greatly appreciable.

A: You need to bind the datagridcomboboxcolumn itemssource.
<DataGridComboBoxColumn Width="100" Header="Profile/Groups" ItemsSource="{Binding   _apProfiles}" />

A: If you set the data context for the datagrid, the columns within the datagrid will look for data within the data context of datagrid. If the value you are binding to datagridcomboBox column is not within the (SSID) the data context of datagrid, you should use,
<DataGridComboBoxColumn Width="100" Header="Profile/Groups" ItemsSource="{Binding _apProfiles,  RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />

or like this
<DataGridComboBoxColumn Width="100" Header="Profile/Groups" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext. _apProfiles}" />

hope this helps.


text:
Q: Ajax change button on PHP website I try to change without refresh status of my button on my PHP page.
I m new in JavaScript code and I see that solutions to my problem uses an AJAX request.
So I did this:
function accendi(str) {

  //controllo se id è vuoto
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
    //altrimenti invio la richiesta
  } else {
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
      console.log(xmlhttp);
    }

    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.responseText;
      }
    };
    //manda la stringa alla pagina accendi.php
    xmlhttp.open("GET","accendi.php?q="+str,true);
    xmlhttp.send();
  }
}

function spegni(str) {

  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  } else {
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
      console.log(xmlhttp);
    }

    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txtHint").innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET","spegni.php?q="+str,true);
    xmlhttp.send();
  }
}

 Gestione luci

 <?php

$fp=pfsockopen("192.168.1.100",23);
if (!$fp) {
  echo("");
  echo("");
}
else {
  for ($x = 0; $x < $numrows; $x++) {

    $resrow = mysqli_fetch_row($rest);
    $id= $resrow[0];
    $userT= $resrow[1];
    $statusT = $resrow[2];
  }

if($statusT==0){

  echo "<form method=\"post\" onSubmit=\"accendi($id)\">

 Stato luci : Spente
  <input type=\"submit\" name=\"invio\" value=\"Accendi\">

</form>";
}
else if($statusT==1){

  echo " <form method=\"post\" onSubmit=\"spegni($id)\">

Stato luci : Accese    <input type=\"submit\" name=\"invio\" value=\"Spegni\">

</form>";
}

And this (one for function), in two different PHP page:
require_once('connection.php');

$q = intval($_GET['q']);

$sql= "UPDATE luciajax SET stato=1 where id='".$q."'";

if ($connection->connect_error) {
  die("Connection failed: " . $connection ->connect_error);
}

//se connessione funziona accendo arduino

if ($connection ->query($sql) === TRUE) {
  $fp=pfsockopen("192.168.1.100",23);

  fputs($fp,"1");

  fclose($fp);

}

else {
 echo "Error updating record: " . $connection ->error;
}

$connection ->close();

But my button often don't work well. Sometimes status do not change, but the database and other PHP code are working fine.

A: You defined an onsubmit inline handler to your form... Which is correct.
But the "normal behavior" of a form submiting is to submit to the ressource provided in the action attribute. When it's missing, the form submit to "self".
You obviously don't want this "normal behavior" to occur... Since you defined some ajax functions to replace it.
So you have to "prevent" it, using preventDefault().
Add this within the  tags:
document.querySelector("form").addEventListener("submit", function(event){
  event.preventDefault();
}


text:
Q: Как запретить редакторам двигать листы в Гугл Таблице? Есть гугл таблица с листами: лист 1, лист 2, лист 3 и тд.
Редакторы таблицы могут двигать эти листы, перемещая между собой.
Например, Теперь "лист 1" - на последнем месте, "лист 2" на первом и тд.
Чтобы избавиться от этого хаоса - было принято решение: запретить редакторам двигать листы между собой.
Либо упорядочить листы с помощью скрипта, чтобы они всегда были в одной последовательности ( лист1, лист 2, лист 3 и тд).
Вопрос: Как это сделать?
заранее большое Спасибо=)

A: Создайте отдельный проект Apps Script, чтобы другие пользователи не могли изменять код, от имени владельца Таблицы.
Добавьте код
/**
 * User action
 */
function userActionSortBookByListNames() {
  const sheetsIdts = ['л5', 'л2', 'л4'];
  const counter = (() => {
    let next = 999;
    const self = {};
    return {
      items: self,
      getId: (prop) => {
        if (!Object.prototype.hasOwnProperty.call(self, prop))
          self[prop] = ++next;
        return self[prop];
      },
    };
  })();
  const sortcb = (a, b) => {
    const nameA = a.getSheetName();
    const nameB = b.getSheetName();
    let idtA = sheetsIdts.indexOf(nameA);
    let idtB = sheetsIdts.indexOf(nameB);
    if (idtA === -1) idtA = counter.getId(nameA);
    if (idtB === -1) idtB = counter.getId(nameB);
    if (idtA > idtB) return 1;
    if (idtA < idtB) return -1;
    return 0;
  };
  const book = SpreadsheetApp.getActive();
  sortBookBySheetsList_(book, sortcb);
}

/**
 *
 * @param {GoogleAppsScript.Spreadsheet.Spreadsheet} book
 * @param {sortCallback} sortfn
 */
function sortBookBySheetsList_(book, sortfn = sortDefault_) {
  const sheets = book.getSheets();
  const sorted = [...sheets].sort(sortfn);
  if (!sheets.every((value, index) => value === sorted[index]))
    sorted
      .map((sheet, i) => {
        return {
          sheet,
          i,
          current: sheets.indexOf(sheet),
        };
      })
      .forEach((item, i, arr) => {
        if (item.i !== item.current) {
          item.sheet.activate();
          book.moveActiveSheet(item.i + 1);
          const prev = item.current;
          item.current = item.i;
          arr.forEach((item_, j) => {
            if (j > item.i && j <= prev) item_.current = item_.current + 1;
          });
        }
      });
}

/**
 * Sort callback
 * @callback sortCallback
 * @param {GoogleAppsScript.Spreadsheet.Sheet} sheetA
 * @param {GoogleAppsScript.Spreadsheet.Sheet} sheetB
 * @returns {(-1|0|1)}
 */

const sortDefault_ = (a, b) => {
  const sA = a.getSheetName().toLowerCase();
  const sB = b.getSheetName().toLowerCase();
  if (sA < sB) return -1;
  if (sA > sB) return 1;
  return 0;
};

Замените
const book = SpreadsheetApp.getActive();

на
const book = SpreadsheetApp.openById('<ТУТ_ID_ТАБЛИЦЫ>');

Замените список имен листов на ваш
const sheetsIdts = ['л5', 'л2', 'л4'];

Добавьте userActionSortBookByListNames в вызов триггера по времени. Например, каждые 5 мин. Если листы на своих местах, то сортировки не произойдет. В противном случае листы книги будут отсортированы сначала как вам надо, а потом все остальные листы в прежнем порядке, если они будут.
Если вам захочется сортировать по алфавиту, то
/**
 * User action
 */
function userActionSortBookByABC() {
  const book = SpreadsheetApp.getActive();
  sortBookBySheetsList_(book);
}

причем, не зависит от userActionSortBookByListNames.


text:
Q: xp_cmdshell proxy account disabled Automatically when i want to execute xp_cmdshell sp is sql server
it give me error that I don't have permission to run xp_cmdshell.
when i check in security tab in Property window of instance,in the service Proxy Account section
enable service account Proxy check box is set.
after deselecting this check box and select it again and set user name and password,
I can execute xp_cmdshell.
My question is why this happen ...?what action can disable service account Proxy.
is a normal behavior what is your idea.
it happen recently and it happne multile time.

A: Does this happen frequently or has it only happened the once?
It could be that some configuration changes did not take place initially.


text:
Q: SQL query doesn't give the right result I have a form where people can search the database for four values:
Location, Period, Day and Service. I always do not get the results that I want.
If I use AND, people need to fill in everything. If I use OR I get the complete database. I want to be able to search the database for those one to 4 things. Is there a way how I can do this?
Is there maybe a way to check which fields are filled in, and that the query is automatically changed with the filled in fields?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd">

<title>Zoeken</title>

 |    |

<form action="" method="post">

Locatie: 	<input type="text" name="Locatie" value="" />

Periode: 	<input type="text" name="Periode" value="" />

Dag: 	<input type="text" name="Dag" value="" />

Dienst: 	 <input type="text" name="Dienst" value="" />

	<input type="submit" name="zoeken" value="Zoeken">

 </form>

 |  |

<?php

if (isset($_POST['zoeken']))
 {
include('connect-db.php');
$Locatie =  $_POST['Locatie'];
$Periode =  $_POST['Periode'];
$Dag =  $_POST['Dag'];
$Dienst =  $_POST['Dienst'];

// get results from database
$result = mysql_query("SELECT * FROM WMC_DeLijn WHERE Locatie='$Locatie' ANY Periode='$Periode' ANY Dag='$Dag'ANY Dienst='$Dienst' ")
    or die(mysql_error());
// display data in table
echo "
Resultaten:

";
echo "
";
echo "

ID	Locatie	Periode	Dag	Dienst	Delen	Geleed	Start 1	Eind 1	Start 2	Eind 2	Lijnen
";

// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {

    // echo out the contents of each row into a table
    echo "
";
    echo '' . $row['id'] . '	';
    echo '' . $row['Locatie'] . '	';
    echo '' . $row['Periode'] . '	';
    echo '' . $row['Dag'] . '	';
    echo '' . $row['Dienst'] . '	';
    echo '' . $row['Delen'] . '	';
    echo '' . $row['Geleed'] . '	';
    echo '' . $row['Start1'] . '	';
    echo '' . $row['Eind1'] . '	';
    echo '' . $row['Start2'] . '	';
    echo '' . $row['Eind2'] . '	';
    echo '' . $row['Lijnen'] . '	';
    //Link to edit record
    echo '	';
    // Link to delete record
    echo '	';
     //Link to Add Event to Google Calendar
    echo '	';
    echo "
";
}}
// close table>
echo "
";

?>

A: You can either build the query string dynamically, only adding WHERE clause statements if the parameter is not falsy, or add conditions in the SQL itself like so: WHERE (col = ? OR '' = ?) AND (col2 = ? OR '' = ?).

A: Change your query to have either a AND condition or a OR condition like
SELECT * FROM WMC_DeLijn
WHERE Locatie='$Locatie'
AND Periode='$Periode'
AND Dag='$Dag'
AND ienst='$Dienst';

(OR)
SELECT * FROM WMC_DeLijn
WHERE Locatie='$Locatie'
OR Periode='$Periode'
OR Dag='$Dag'
OR ienst='$Dienst';


text:
Q: Integral with substitution, how they get to next step
$$2\int\frac{u^2}{u^2-4}\,du = 2\int\left(1+\frac{4}{u^2-4}\right)\,du$$

Source.
Can someone please explain how they get from step on the left to the one on the right?

A: Hint: add and substract $4$ in the numerator.

A: Notice that $\frac{u^2-4}{u^2-4} =1$ so then $1 +\frac{4}{u^2-4} = \frac{u^2-4}{u^2-4} + \frac{4}{u^2-4} = \frac{u^2}{u^2-4}$.


text:
Q: How does RStudio 'lm' know my data is a polynomial equation? I'm following along with a "learn R" course, and we ran the following multiple linear regression:
regressor = lm(formula = Profit ~ ., data = training_set)

Then a bit later, we added some columns to a different data set:
dataset$Level2 = dataset$Level^2
dataset$Level3 = dataset$Level^3
dataset$Level4 = dataset$Level^4

And ran identical line...
regressor = lm(formula = Profit ~ ., data = training_set)

And somehow now lm knows not to fit a multiple regression linear line?
It's modifying the original data set before it's even passed into lm, so unless lm is somehow trying to interpret my data to figure out which actual model to use, I don't see how it's knowing to do this...?


text:
Q: CollapsingToolbarLayout cannot be instantiated I want to implement a CollapsingToolbarLayout in my app (I want it to be like play store's parallax effect)
I have seen many questions on stackOverflow itself as well as Android's developer site.
The problem is, I always get an error in the IDE (Android Studio)
The following classes could not be instantiated:
- android.support.design.widget.CollapsingToolbarLayout
If I run the activity on my phone anyway, the app crashes with error
Caused by: java.lang.NoSuchMethodError: No static method setLayoutDirection(Landroid/graphics/drawable/Drawable;I)V in class Landroid/support/v4/graphics/drawable/DrawableCompat; or its super classes (declaration of 'android.support.v4.graphics.drawable.DrawableCompat' appears in /data/data/com.hemal.eventhub2/files/instant-run/dex/slice-com.android.support-support-v4-24.0.0_b8d850cc5f06d621d9211f2cbc20e32dfc36ae82-classes.dex)
                                                                       at android.support.design.widget.CollapsingToolbarLayout.setStatusBarScrim(CollapsingToolbarLayout.java:663)

I am pretty sure this has something to do with conflicting imports or dependencies.
My app module gradle script is
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.hemal.eventhub2"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:design:23.2.1'
    compile 'com.google.android.gms:play-services-auth:9.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-messaging:9.6.1'
}

apply plugin: 'com.google.gms.google-services'

Following are some of the imports in my app's MainAcitivity
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

Are the above imports or dependencies conflicting which are causing the trouble.
I have also updated my Android Studio to 2.2.1 from 1.5.1 hoping it might solve the problem
Can you please guide me which SDKs, imports and dependencies I should remove, keep or download to get the CollapingToolbarLayout work.


text:
Q: JAXB: Separating the implementation of an element from the marshalling I have an XML structure which looks like this:
<root>
  <user></user>
  <data></data>
  <things-map>
    <item>
      <key>one</key>
      <value>Eins</key>
    </item>
    <item>
      <key>two</key>
      <value>Zwei</key>
    </item>
    <item>
      <key>three</key>
      <value>Drei</key>
    </item>
  </things-map>
</root>

I would like to unmarshall this into the following structure:
public class Root {
  // These are unimportant.
  private String user;
  private String data;

  private ThingsMap thingsMap;
}

Where the ThingsMap class is essentially a wrapper for the map given by things-map.
public class ThingsMap {
  private Map<String, String> items;

  @XmlElement(name = "item")
  public void setItems(List<Item> items) {
    this.items = new Hashmap();
    for (List item : items) {
      this.items.put(items.key(), items.value());
    }
  }

  public List<Item> getItems() {
  List items = new ArrayList();
  for (Map.Entry<String, String> entry : this.items.entrySet()) {
    items.add(new Item(entry.getKey(), entry.getValue()));
  }
  return items;
}

The Item class can be inferred from there. It's a basic Element.
It is a similar issue to here.
The issue with this is, JAXB prefers to call the getter to get the list of items and then deal with it directly (is this not ridiculous...?). Unless the list returned is null. I.e.
if (this.items == null) {
  return null;
}

However, trying this, the items passed to setItems is empty.
I do not want a regular Map, which I'm aware could be done with an Adapter. And as far as I can see, using an Adapter for this case requires a wrapper (which I do not want).


text:
Q: https on subdomain redirects to main domain; subdomain works without https I have a website, https://www.example.com and subdomain, https://sub.example.com.
My problem is that whenever I try to visit https://sub.example.com I am redirected to https://www.example.com. But, when I visit http://sub.example.com, I am not redirected.
I have a wildcard SSL cert which should allow me to visit my subdomain with https://. Both sites run WordPress and are hosted with Bluehost. I have tried many solutions as well as contacting Bluehost customer support twice to no avail. I would like to be able to visit both my main domain and subdomain with SSL active.
I have edited the .htaccess file according to the following solutions found here: htaccess redirect domain to https, subdomain to http and www to non-www
# for main domain
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L,NE]

# for sub domain
RewriteCond %{HTTP_HOST} ^(www\.)?sub\.example\.com$ [NC]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ http://sub.example.com%{REQUEST_URI} [R=301,L,NE]

https://my.bluehost.com/hosting/help/766
# Custom subdomain .htaccess SSL + WordPress
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain.maindomain.com$
RewriteCond %{REQUEST_URI} !^/subfolder/
RewriteRule ^(.*)$ /subfolder/$1
RewriteCond %{HTTP_HOST} ^subdomain.maindomain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]
# End custom subdomain .htaccess

# Custom maindomain .htaccess WordPress
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www.)?maindomain.com$
RewriteRule ^index\.php$ - [L]
RewriteCond %{HTTP_HOST} ^(www.)?maindomain.com$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# End custom maindomain .htaccess

http://www.wpbeginner.com/wp-tutorials/how-to-add-ssl-and-https-in-wordpress/
I have also tried fresh WordPress installs of both the main domain and subdomain with no luck. I'm not sure what else to try. Any help and suggestions would be much appreciated.

A: Several things to try:

*

*First, when you're making changes, use a tool like Webconfs HTTP Header Checker. This way, if your web browser has redirects cached and you make a change that fixes the redirects, the Header Checker won't be fooled. Your web browser, on the other hand, will keep redirecting even after things are fixed, until you clear the cache. Alternatively, you can try a Chrome Incognito window.

*Instead of using just the one .htaccess file, use one for each site. Assuming example.com is your primary domain, you can set rules for the "root" WP site in the root folder, and you'll set rules for the "subdomain" WP site in the folder where that separate WP install sits - /subdomain.com/.htaccess.

*Make sure your "root" WP site URL and home URL are both set to the https version. You can do this in a couple of places: in wp-admin of the "root" WP site, go to Settings > General. The "WordPress Address (URL)" and "Site Address (URL)" both need the https. If they are set to http, it will log you out when you click save. Alternatively, you can do this in phpMyAdmin - in the wp_options table, look for the 'siteurl' and 'home' options and make sure they're https rather than http.

*It sounds like your "root" WP was installed when the site was insecure, running on http. Sometimes it takes more than just updating the site URL and home URL. Try using WP Migrate DB which will do a search-and-replace to convert all instances of your http URLs to https URLs.

*Once all that is done, if the "root" site still redirects to the non-secure version, you can install a plugin such as WordPress Force HTTPS.