问:
Fatal error: Class not found in AppKernel.php
I have generated a new Bundle (ImgBundle) following the Symfony documentation, but when reloading the app in the browser it does not recognize the main class of the bundle.

Here is my ImgBundle.php:

```<code><?php

namespace ImgBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ImgBundle extends Bundle
{
}
</code>```

AppKernel.php:

```<code><?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\SecurityBundle\SecurityBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new AppBundle\AppBundle(),
        new ImgBundle\ImgBundle(),
    ];

    if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
        $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
        $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

        if ('dev' === $this->getEnvironment()) {
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
        }
    }

    return $bundles;
}

public function getRootDir()
{
    return __DIR__;
}

public function getCacheDir()
{
    return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}

public function getLogDir()
{
    return dirname(__DIR__).'/var/logs';
}

public function registerContainerConfiguration(LoaderInterface $loader)
{
    $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
</code>```

}

Here is the error:

Thanks in advance

答:
you need to change your composer.json I think with psr-4 autoload like this:

```<code>"autoload": {
        "psr-4": {
            "": "src/"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    }
</code>```

After you need to launch inside your console:

```<code>composer dump-autoload
</code>```

Body:
I have generated a new Bundle (ImgBundle) following the Symfony documentation, but when reloading the app in the browser it does not recognize the main class of the bundle.

Here is my ImgBundle.php:

<?php

namespace ImgBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ImgBundle extends Bundle
{
}

AppKernel.php:

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        new Symfony\Bundle\SecurityBundle\SecurityBundle(),
        new Symfony\Bundle\TwigBundle\TwigBundle(),
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        new AppBundle\AppBundle(),
        new ImgBundle\ImgBundle(),
    ];

    if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
        $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
        $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

        if ('dev' === $this->getEnvironment()) {
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
        }
    }

    return $bundles;
}

public function getRootDir()
{
    return __DIR__;
}

public function getCacheDir()
{
    return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}

public function getLogDir()
{
    return dirname(__DIR__).'/var/logs';
}

public function registerContainerConfiguration(LoaderInterface $loader)
{
    $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}

}

Here is the error:

Thanks in advance

Body:
you need to change your composer.json I think with psr-4 autoload like this:

"autoload": {
        "psr-4": {
            "": "src/"
        },
        "classmap": [
            "app/AppKernel.php",
            "app/AppCache.php"
        ]
    }

After you need to launch inside your console:

composer dump-autoload


来源: stackexchange

问:
Cleaning git repo of large files
I committed over 600 large(ish) jpgs to my git repo and can now see the error of my way. I have used the BFG to remove them and my local repository no longer shows them. My local git GUI doesn't show them. If I check the size of the repo in Finder then it shows 119Mb.

But...
The repo size on BitBucket still shows 1.6Gb. If I choose to download the repo from BB then I get a 119Mb file downloaded.
I also ran the following command:

while read -r largefile; do     echo $largefile | awk '{printf "%s %s ", $1, $3 ; system("git rev-list --all --objects | grep " $1 " | cut -d \" \" -f 2-")}'; done <<< "$(git rev-list --all --objects | awk '{print $1}' | git cat-file --batch-check | sort -k3nr | head -n 20)"

and that shows a whole load of large files that I thought had been cleared out by BFG.

Any ideas how I can resolve it.  I'm not fully versed with Git so please go easy on me! :-)

答:
You do not really need to worry about it. Make sure that there are no branches/tags in the remote which still have those files somewhere in their reference. If that is so, then their garbage collector should clean them up after some time.

I am not that familiar with BitBucket - try to find out if you can somehow force it to do a GC pass on their side, maybe that fixes the problem already.

ContentLicense: CC BY-SA 3.0

Title: Cleaning git repo of large files


问:
Creating dynamic bootstrap modals with php mysql and ajax
so I am working on a small ecommerce site and I've been stuck on this section of my site for quite a while now and can't really wrap my head around it.

I have divided the site into 3 columns with bootstrap's grid system, in the main section I have my featured products, however, I'd like everything to be dynamic, when I click on a modal with "View details" for the product the only code that works is the dynamic one, I'd like to know how to make it so that it pulls the data directly from my database, unfortunately out of frustration I deleted the little work I had done on it and can't show stick it on here so that anyone can correct it for me.

Could anyone please help me out?

Thanks!

答:
There are many ways you could go about doing this. Here is an approach you could use:

Get the id from data attribute of your product (make sure you load it into the html).

Send a $.get request with jquery for this id to the server.

Get the data needed from the db using this id.

Render the data server side

Return html

In the callback function of your get request put the HTML into your bootstrap modal body.

Show the modal to the user.


问:
Import wizard with subqueries
I want to import 100k+ rows on to a SQL Server table.

I have my insert like this (observe the 6th value that is a subquery):

```<code>INSERT INTO BD_S3I.dbo.AGENDA
(COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE, DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA, COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS, DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA, DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA, DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA, NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA, COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

VALUES

(1, 290, 2, 6, '2017-09-11 00:00:00.000', (SELECT CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL THEN 1 ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 END FROM AGENDA WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290 AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6 AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000'), '2017-09-17 00:00:00.000', NULL, 492, NULL, NULL, '2017-07-24 08:30:00.000', 'P', NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7, '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL);
</code>```

I put al the 100k inserts below each other and start the import. It is working fine, but thakes too much time to execute all the 100k+ rows.

I was thinking to use the import wizard (the time is better?).

The problem is that when I choose the excel file with my data, the import wizard do not understand the subquery on the value. It calls it a longtext.

答:
Simply convert your INSERT...VALUES to INSERT...SELECT which works since all other values are scalars and can be included inline with the subquery's SELECT statement:

```<code>INSERT INTO BD_S3I.dbo.AGENDA (COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE,
                               DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA,
                               COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS,
                               DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA,
                               DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA,
                               DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA,
                               NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA,
                               COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

SELECT 1, 290, 2, 6, '2017-09-11 00:00:00.000',
       CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL
            THEN 1
            ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1
       END,
       '2017-09-17 00:00:00.000', NULL, 492, NULL,
        NULL, '2017-07-24 08:30:00.000', 'P',
        NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7,
        '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL

FROM AGENDA
WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290
  AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6
  AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000')
</code>```

Title: Import wizard with subqueries

Body:
I want to import 100k+ rows on to a SQL Server table.

I have my insert like this (observe the 6th value that is a subquery):

INSERT INTO BD_S3I.dbo.AGENDA
(COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE, DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA, COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS, DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA, DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA, DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA, NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA, COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

VALUES

(1, 290, 2, 6, '2017-09-11 00:00:00.000', (SELECT CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL THEN 1 ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 END FROM AGENDA WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290 AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6 AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000'), '2017-09-17 00:00:00.000', NULL, 492, NULL, NULL, '2017-07-24 08:30:00.000', 'P', NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7, '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL);

I put al the 100k inserts below each other and start the import. It is working fine, but thakes too much time to execute all the 100k+ rows.

I was thinking to use the import wizard (the time is better?).

The problem is that when I choose the excel file with my data, the import wizard do not understand the subquery on the value. It calls it a longtext.

Body:
Simply convert your INSERT...VALUES to INSERT...SELECT which works since all other values are scalars and can be included inline with the subquery's SELECT statement:

INSERT INTO BD_S3I.dbo.AGENDA (COD_UNDFBR, COD_DCPLNA, COD_TECNCA, COD_ATVIDE,
                               DAT_PROGM_AGENDA, NUM_SQNCL_AGENDA, DAT_FINAL_AGENDA,
                               COD_OCORR, COD_ROTA, NUM_SEMAN_PRGINS, NUM_DIAIN_PRGINS,
                               DAT_INIC_PRGINS, MRC_SITUA_AGENDA, DAT_SUSPN_AGENDA,
                               DAT_CONCL_AGENDA, DAT_REPRG_AGENDA, DCR_SITUA_AGENDA,
                               DCR_AGENDA, MRC_AVISO_AGENDA, MRC_NEGLG_AGENDA,
                               NUM_PERIO_PRGINS, DAT_DIAIN_PRGINS, DAT_JUSTN_AGENDA,
                               COD_MTVNVS, MRC_ERP_AGENDA, COD_USUS3I_JUSTN)

SELECT 1, 290, 2, 6, '2017-09-11 00:00:00.000',
       CASE WHEN MAX(AGENDA.NUM_SQNCL_AGENDA) + 1 IS NULL
            THEN 1
            ELSE MAX(AGENDA.NUM_SQNCL_AGENDA) + 1
       END,
       '2017-09-17 00:00:00.000', NULL, 492, NULL,
        NULL, '2017-07-24 08:30:00.000', 'P',
        NULL, NULL, NULL, NULL, NULL, 'S', 'S', 7,
        '2017-07-24 00:00:00.000', NULL, NULL, 'N', NULL

FROM AGENDA
WHERE AGENDA.COD_UNDFBR = 1 AND AGENDA.COD_DCPLNA = 290
  AND AGENDA.COD_TECNCA = 2 AND AGENDA.COD_ATVIDE = 6
  AND AGENDA.DAT_PROGM_AGENDA = '2017-09-11 00:00:00.000')


问:
How to get file creation date on server for jQuery/uploadify?
I am using the jQuery Uploadify plugin on a web page to transfer files from the local computer to an ASP.NET MVC2 control action method. Is there a way to transfer the creation date/time of the file to the server?

I can get at the data in an Uploadify event on the client, but can not figure out how to "package" that data so it is moved to the server w/ the file.

Any thoughts appreciated.

答:
Try using onSelect event to add values to the scriptData object.

UPDATE: The following is an ad-hoc view to pass the data to the action. It appears that modificationDate returns a Unix timestamp in it's time field and you'll have to convert it on the server side. I wasn't able to find any documentation on modificationDate property.

```<code><%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Home</title><link href="/Scripts/uploadify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="/Scripts/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="/Scripts/swfobject.js"></script>
    <script type="text/javascript" src="/Scripts/jquery.uploadify.v2.1.4.min.js"></script>
    <script type="text/javascript">
        var myScriptData = {};
        $(document).ready(function () {
            $('#file_upload').uploadify({
                'uploader': '/Scripts/uploadify.swf',
                'script': '/Test/Upload',
                'cancelImg': '/Scripts/cancel.png',
                'folder': '/App_Data',
                'auto': true,
                'onSelect': function (event, ID, fileObj) {
                    $('#file_upload').uploadifySettings('scriptData', {
                        modifiedTimestamp: fileObj.modificationDate.time
                    });
                    return true;
                }
            });
            $('#file_upload').uploadifySettings('scriptData', myScriptData);
        });
    </script>
</head>
<body>
    <input id="file_upload" name="file_upload" type="file" />
</body>
</html>
</code>```

In your action method, you can grab timestamp through the Request.Form["modifiedTimestamp"]. Check here on how to convert timestamp to the DateTime object.

ContentLicense: CC BY-SA 2.5

Body:
Try using onSelect event to add values to the scriptData object.

UPDATE: The following is an ad-hoc view to pass the data to the action. It appears that modificationDate returns a Unix timestamp in it's time field and you'll have to convert it on the server side. I wasn't able to find any documentation on modificationDate property.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Home</title><link href="/Scripts/uploadify.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript" src="/Scripts/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="/Scripts/swfobject.js"></script>
    <script type="text/javascript" src="/Scripts/jquery.uploadify.v2.1.4.min.js"></script>
    <script type="text/javascript">
        var myScriptData = {};
        $(document).ready(function () {
            $('#file_upload').uploadify({
                'uploader': '/Scripts/uploadify.swf',
                'script': '/Test/Upload',
                'cancelImg': '/Scripts/cancel.png',
                'folder': '/App_Data',
                'auto': true,
                'onSelect': function (event, ID, fileObj) {
                    $('#file_upload').uploadifySettings('scriptData', {
                        modifiedTimestamp: fileObj.modificationDate.time
                    });
                    return true;
                }
            });
            $('#file_upload').uploadifySettings('scriptData', myScriptData);
        });
    </script>
</head>
<body>
    <input id="file_upload" name="file_upload" type="file" />
</body>
</html>

In your action method, you can grab timestamp through the Request.Form["modifiedTimestamp"]. Check here on how to convert timestamp to the DateTime object.


问:
I want to track user's real world activity on android ,which method is better ,GPS or activityRecognition?
I want to track user's real world activity on android  ,which method is better ,GPS or activityRecognition?
and one of the situation is when user suddenly running, i want to detect user's activity change immediately how can i do?</p>

答:
According to your basic requirements I'll suggest you to use ActivityRecogniserAPI, but ActivityRecogniserAPI doesn't give you the results immediately specially on the places where Location Services are not responding quickly.
But if you use GPS then you can speedup the process little bit, but you have to do a-lot or work to achieve this by running some process, doing calculations, handling events etc. It will be little bit fast as compared to ActivityRecogniserAPI but you will be having issue in this as well when Location Services are not responding quickly.

If the slow process works for you then I'll suggest you to use ActivityRecogniserAPI.


答:
You can use tickInterval in xAxis.

Here is a working fiddle with your data in it

Title: How to prevent cluttered date axis in Highcharts

Body:
How do you prevent Highcharts from showing a cluttered x-axis labels when using dates in Highcharts?

I'm generating my graph with:

and the JSON returned by get_data path looks like:

    {"yAxis": {}, "title": {"style": {}, "text": null}, "series": [{"name": "Apple", "data": [1.0, -3.0, 1.0, 4.0, -5.0, 4.0, -1.0, 4.0, 2.0, -1.7741935483871, 3.0, -5.0, 3.0, 2.0, 0.0, -3.0, 1.0, -2.0, 2.0, 4.0, 1.0, -5.0, 5.0, -4.0, 0.0, 4.0, 2.0, -2.0, 0.0, 1.0, -2.0, 4.0, 0.0, -5.0, -5.0, 0.0, -5.0, 3.0, -1.0, 1.0, 4.0, 2.0, -5.0, 4.0, 0.0, 2.0, 1.0, -3.0, 5.0, -1.0, 5.0, -2.0, -4.0, 4.0, -0.324324324324324, -1.0, 3.0, -1.0, 3.0, -3.0, 5.0, 4.0, -3.0, 0.0, 4.0, 0.0, -1.678456591639871, 4.324675324675325, 4.436681222707424, 5.291545189504373, -4.0, -1.0, 3.272479564032698, 3.0, -0.738219895287958, -5.0, -3.0, 4.0, 2.0, -0.719101123595506, -5.0, 5.0, -3.202127659574468, 4.0, 1.3597122302158269, -3.74055415617128, 1.32450331125828, 1.33003300330033, -2.358974358974359, 4.0, 3.0, 4.25391849529781, 4.02564102564103, -0.49622166246851396, 0.86335403726708, 0.628930817610063, -2.89227166276347, 0.08641975308642014, 6.09597523219814, 4.5294117647058805, 1.7272727272727302, 4.406326034063261, -1.2431077694235602, 2.49019607843137, 3.2, 6.06060606060606, 4.75, 7.66830466830467, 8.0952380952381, 12.07692307692308, 3.10628019323671, 8.24242424242424, 2.5853658536585398, 8.006006006006011, -1.9969969969969998, 7.571428571428569, 3.70570570570571, 3.37017994858612, 7.75229357798165, 9.01567398119122, 6.10772833723653, 4.84615384615385, 0.7151702786377698, -1.25, 4.73186119873817, 6.68098159509202, 3.50877192982456, 5.147699757869249, 6.68098159509202, 8.64077669902913, 3.71517027863777, -1.3414634146341502, 5.53012048192771, 9.08805031446541, 8.146341463414629, 2.7021943573667704, 7.77777777777778, 7.703703703703701, 5.97628458498024, 3.3824701195219102, 4.6, 10.11620795107034, 5.60663507109005, 5.21674876847291, 8.96341463414634, -2.5, 6.05882352941176, -1.2392638036809802, 1.8679706601466997, 11.306306306306311, 1.0752351097178696, 0.8929440389294401, 9.4380664652568, 5.10059171597633, 11.33333333333333, 9.882352941176471, 5.10059171597633, 1.9069069069069098, 6.69607843137255, 5.56716417910448, 3.05952380952381, 9.918032786885249, 6.51807228915663, 5.43137254901961, 6.42477876106195, 9.68384074941452, 2.98507462686567, 7.43786982248521, 7.25581395348837, 0.9215686274509798, 9.65116279069767, 2.1515151515151496, 7.71698113207547, 2.82352941176471, -1.1896955503512898, -0.48093841642229007, 4.71976401179941, 6.94117647058824, 10.56844547563805, 3.95626822157434, 6.6379821958457, 2.31400966183575, 7.33734939759036, 8.48837209302326, 6.62060889929742, 5.76368876080692, 10.341246290801191, 5.43735224586288, 3.5527065527065496, 1.4631828978622297, 2.25075528700906, 8.7463556851312, 8.84955752212389, 3.5268065268065296, 6.720823798627, 4.94296577946768, 3.08083140877598, 8.88235294117647, 2.89473684210526, 2.55555555555556, 8.7246376811594, 1.9767441860465098, 15.7558139534884, 10.64705882352941, 8.3053435114504, 5.48854961832061, 8.142857142857139, 2.85480093676815, 10.387205387205391, 9.0, 3.94117647058824], "showInLegend": true}, {"name": "Orange", "data": [2.0, 2.0, 4.0, -4.0, 3.0, -1.0, 0.0, 2.0, 4.0, 3.0, -4.0, 2.0, -2.0, 1.0, 2.0, 3.0, 0.0, -1.0, 0.0, -2.0, 4.0, 1.0, 5.0, 4.0, -1.0, -3.0, -5.0, -3.0, -3.0, 3.0, -2.0, -2.0, 0.0, 3.0, -3.0, -1.0, 0.0, 5.0, 4.0, -3.0, -2.0, 0.0, 0.0, 4.0, 0.0, 0.0, -4.0, 0.0, -3.0, 2.0, -1.0, 4.0, -2.0, -3.0, -5.0, 1.0, -5.0, -1.0, -1.0, 1.0, 1.0, -3.0, 5.0, -4.0, -3.0, -3.0, -4.0, -4.0, -5.0, 1.0, 5.0, 1.0, -1.0, 0.0, 2.0, -2.5555555555555562, -1.0, 0.0, -1.0, 5.0, 5.467289719626168, 0.0, -2.0, 1.0, 1.0, 0.0, -1.0, -2.0, 4.0, 5.0, 3.0, 3.0, -3.0, 5.0, -3.0, 0.0, 1.0, -4.0, -5.0, 1.0, -3.0, 3.0, 5.0, 3.0, 5.0, -5.0, 5.0, 5.0, 0.0, -2.0, -3.0, 4.0, 3.0, -5.0, -5.0, 1.0, 3.0, -4.74293059125964, -5.0, 0.313479623824451, 5.0, 3.0, 4.0, 1.0, -2.0, -1.0, 2.0, -3.757869249394673, 4.0, 5.0, 0.0, 0.48780487804878, 1.0, -4.0, 2.0, 5.0, 4.3086419753086425, 0.0, -5.0, 1.0, 4.0, -3.0, -4.0, 3.0, 1.0, -5.0, 1.0, -1.0, 3.0, -1.0, 3.0, 1.0, 1.0, 4.0, -3.702380952380952, 1.0, 5.0, 0.0, 5.0, -1.0, 3.0, 1.0, -3.0, 1.0, -2.0, 2.234192037470726, -5.0, -2.0, -3.0, -2.0, 2.0, 2.0, 4.0, 1.294117647058824, -5.0, -2.0, 0.0, 5.0, -3.0, 1.0, 4.0, -2.758454106280193, 5.0, 4.0, 4.17096018735363, -3.84726224783862, -3.0, -2.0543735224586293, 4.854700854700855, -1.33729216152019, 0.906344410876133, 3.8746355685131197, 1.17994100294985, 7.29370629370629, 1.03432494279176, 0.8022813688212902, 8.00461893764434, 9.705882352941181, 4.39097744360902, 2.00925925925926, 4.869565217391304, 3.232558139534884, 2.8720930232558137, -2.117647058823529, 2.954198473282443, -2.236641221374046, 1.0, 4.702576112412178, 3.0, 5.680851063829787, -3.0], "showInLegend": true}, {"name": "Pear", "data": [4.0, 1.0, -2.0, 1.0, 1.0, -4.0, -1.0, -5.0, -1.0, 0.0, -2.0, 1.0, 1.0, -2.0, -4.0, -4.0, 3.0, 2.0, -5.0, 1.0, 1.0, -1.0, -4.0, 5.0, -5.0, 0.0, 5.0, 4.0, -2.0, 5.0, -1.0, -2.0, 4.0, -1.0, -5.0, 4.0, -3.0, 4.0, 5.0, 5.0, -1.0, 0.0, 3.0, 3.50375939849624, -2.0, 5.0, -5.0, -5.0, -3.0, 1.0, -4.0, 3.0, -2.0, 2.980392156862745, 5.0, 3.0, 0.0, -4.0, 0.0, -3.0, -2.0, -1.0, 4.0, 5.0, 3.24330900243309, 3.0, 3.643086816720257, -4.675324675324675, 3.31004366812227, -3.7084548104956268, 4.0, 0.51150895140665, 5.544959128065395, -4.553571428571429, 0.0, 5.0, 1.0, 4.248756218905473, 0.0, 4.561797752808989, 3.467289719626168, -1.74025974025974, 3.265957446808511, -2.326599326599327, 3.359712230215827, 2.0, 0.0, 1.33003300330033, -5.0, -1.757281553398058, -4.696048632218845, 4.0, 4.256410256410256, 5.251889168765743, 2.0, 0.628930817610063, -2.0, -0.691358024691358, 0.0, 0.294117647058824, 5.303030303030303, 0.24330900243309, 3.0, 3.0, -1.4, -5.0, -1.583333333333333, -2.017199017199017, 3.297619047619048, 5.0, 3.241545893719807, -5.0, -3.0, -0.6996996996997, -4.0, 4.255102040816327, -2.6996996996997, 2.7712082262210798, -5.0, 2.0, 2.0, -4.408284023668639, -0.690402476780186, -2.75, 3.315457413249211, -0.386503067484663, -3.707602339181287, 2.0, 2.920245398773006, -4.0, -4.0, -0.51219512195122, -1.698795180722892, 3.0, 1.24390243902439, 0.5673981191222599, 2.617283950617284, 0.493827160493827, 2.395256916996047, 2.398406374501992, -3.0, -4.388379204892966, -5.0, 2.246305418719212, 1.6097560975609762, -2.0, 1.0, 2.0, -4.755501222493888, -1.7987987987988, -2.0595611285266457, -0.75669099756691, 1.302114803625378, 2.4792899408283997, -5.0, 0.235294117647059, -2.0, -1.0, 1.0, 0.597014925373134, -3.404761904761905, 1.7025761124121779, -2.0, -3.264705882352941, 3.294985250737463, 5.234192037470726, 2.5970149253731343, 5.29585798816568, -1.767441860465116, 5.0, 5.465116279069767, 0.303030303030303, 4.471698113207547, 4.882352941176471, -3.297423887587822, 0.586510263929619, -1.705014749262537, 0.0, -3.535962877030162, -2.7084548104956268, 4.29673590504451, 2.241545893719807, -4.759036144578313, -4.0, -1.0, 0.5936599423631099, 2.18694362017804, 1.0189125295508301, 4.12820512820513, 6.37529691211401, 2.02114803625378, 3.08163265306122, 7.71976401179941, 8.4219114219114, 17.6453089244851, 3.22433460076046, 17.2401847575058, 15.8235294117647, 16.3007518796992, 19.75, 14.681159420289902, 22.2325581395349, 40.5697674418605, 40.3529411764706, 51.618320610687, 47.6564885496183, 33.7142857142857, 39.0023419203747, 40.026936026936, 26.2127659574468, 24.9019607843137], "showInLegend": true}, {"name": "Banana", "data": [0.0, 2.0, -5.0, 4.0, 0.0, 1.0, -1.0, 5.0, 4.0, 8.2258064516129, 2.0, -5.0, 2.0, 4.0, 3.0, -3.0, -5.0, 7.526315789473699, 5.0, 2.0, 3.0, 3.0, -3.0, 4.0, -1.0, 6.61290322580645, -3.0, 3.0, 5.0, 0.0, -5.0, -3.0, 0.0, 0.0, -5.0, -1.0, -3.0, 3.0, -3.0, 2.0, 4.0, -2.9010989010988997, 3.0, -2.0, 2.0, 3.0, 0.934579439252336, 2.0, -2.0, -5.0, 0.0, 5.0, -1.0, -3.0, -5.0, -1.159663865546218, 4.0, 5.0, -1.3103448275862069, -2.0, -0.25373134328358204, -4.0, 5.0, 4.0, 2.0, 1.0, -0.678456591639871, 5.0, 4.0, -2.7084548104956268, -4.0, 0.255754475703325, 2.272479564032698, -2.553571428571429, 5.261780104712042, -3.0, -4.0, -0.7512437810945269, -0.367088607594937, 2.561797752808989, 5.0, -4.0, -2.0, -2.663299663299663, -0.640287769784173, 2.755667506297229, 1.993377483443709, -1.33993399339934, -1.358974358974359, -2.514563106796116, 1.60790273556231, 5.0, -3.230769230769231, 2.503778337531486, 0.86335403726708, 4.943396226415094, 5.512880562060889, 5.703703703703701, 1.4767801857585101, 5.6470588235294095, -1.5757575757575801, 1.4330900243309, 1.00250626566416, 1.96078431372549, -4.2, 1.51515151515152, 4.25, 3.47420147420147, 2.8928571428571432, 2.0, 0.483091787439614, 4.303030303030303, -2.0, 3.0, 0.3003003003003, 0.53061224489796, -4.099099099099099, 2.51413881748072, -3.694189602446483, 0.940438871473354, -0.06323185011709598, -1.5207100591716, 1.619195046439629, 5.0, 0.946372239747634, -2.386503067484663, 3.0, 5.0, 0.613496932515337, -4.271844660194175, 4.928792569659443, 1.24390243902439, -3.698795180722892, -0.371069182389937, -1.04878048780488, -0.373040752351097, -0.07407407407407396, 1.4938271604938271, -2.604743083003953, -2.800796812749004, -3.2, -3.7767584097859297, -3.052132701421801, 0.492610837438424, 5.304878048780488, 1.3125, 1.470588235294118, 0.920245398773006, 3.488997555012225, -4.399399399399399, 3.626959247648903, -2.75669099756691, 3.7190332326284, -4.0, 4.892857142857143, -0.8235294117647101, 3.4792899408283997, -2.099099099099099, 3.0, -3.0, -2.0, -1.0, -0.39759036144578297, 2.0, 3.294985250737463, -4.297423887587822, 0.597014925373134, 4.887573964497041, 4.465116279069767, -2.607843137254902, 4.930232558139535, 3.606060606060606, 2.0, -4.117647058823529, -2.0, 1.0, 3.589970501474926, 5.0, -2.0, 3.0, 3.0, -0.5507246376811601, -2.34939759036145, 0.6511627906976702, -2.42388758782201, -2.84726224783862, 3.18694362017804, -0.9267139479905402, 7.279202279202281, 8.03800475059382, -2.88519637462236, -0.9591836734693899, 2.65486725663717, 11.09090909090909, 2.32265446224256, 0.7034220532319404, 6.2378752886836, 7.823529411764699, 18.5338345864662, 13.3518518518519, 18.6231884057971, 23.6046511627907, 20.3139534883721, 12.23529411764706, 11.10687022900763, 5.81679389312977, 2.71428571428571, -0.36065573770492, 1.1986531986531999, 1.70212765957447, 3.96078431372549], "showInLegend": true}], "chart": {}, "colorAxis": {}, "xAxis": {"categories": ["2000-01-01", "2000-02-01", "2000-03-01", "2000-04-01", "2000-05-01", "2000-06-01", "2000-07-01", "2000-08-01", "2000-09-01", "2000-10-01", "2000-11-01", "2000-12-01", "2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01", "2001-07-01", "2001-08-01", "2001-09-01", "2001-10-01", "2001-11-01", "2001-12-01", "2002-01-01", "2002-02-01", "2002-03-01", "2002-04-01", "2002-05-01", "2002-06-01", "2002-07-01", "2002-08-01", "2002-09-01", "2002-10-01", "2002-11-01", "2002-12-01", "2003-01-01", "2003-02-01", "2003-03-01", "2003-04-01", "2003-05-01", "2003-06-01", "2003-07-01", "2003-08-01", "2003-09-01", "2003-10-01", "2003-11-01", "2003-12-01", "2004-01-01", "2004-02-01", "2004-03-01", "2004-04-01", "2004-05-01", "2004-06-01", "2004-07-01", "2004-08-01", "2004-09-01", "2004-10-01", "2004-11-01", "2004-12-01", "2005-01-01", "2005-02-01", "2005-03-01", "2005-04-01", "2005-05-01", "2005-06-01", "2005-07-01", "2005-08-01", "2005-09-01", "2005-10-01", "2005-11-01", "2005-12-01", "2006-01-01", "2006-02-01", "2006-03-01", "2006-04-01", "2006-05-01", "2006-06-01", "2006-07-01", "2006-08-01", "2006-09-01", "2006-10-01", "2006-11-01", "2006-12-01", "2007-01-01", "2007-02-01", "2007-03-01", "2007-04-01", "2007-05-01", "2007-06-01", "2007-07-01", "2007-08-01", "2007-09-01", "2007-10-01", "2007-11-01", "2007-12-01", "2008-01-01", "2008-02-01", "2008-03-01", "2008-04-01", "2008-05-01", "2008-06-01", "2008-07-01", "2008-08-01", "2008-09-01", "2008-10-01", "2008-11-01", "2008-12-01", "2009-01-01", "2009-02-01", "2009-03-01", "2009-04-01", "2009-05-01", "2009-06-01", "2009-07-01", "2009-08-01", "2009-09-01", "2009-10-01", "2009-11-01", "2009-12-01", "2010-01-01", "2010-02-01", "2010-03-01", "2010-04-01", "2010-05-01", "2010-06-01", "2010-07-01", "2010-08-01", "2010-09-01", "2010-10-01", "2010-11-01", "2010-12-01", "2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-08-01", "2011-09-01", "2011-10-01", "2011-11-01", "2011-12-01", "2012-01-01", "2012-02-01", "2012-03-01", "2012-04-01", "2012-05-01", "2012-06-01", "2012-07-01", "2012-08-01", "2012-09-01", "2012-10-01", "2012-11-01", "2012-12-01", "2013-01-01", "2013-02-01", "2013-03-01", "2013-04-01", "2013-05-01", "2013-06-01", "2013-07-01", "2013-08-01", "2013-09-01", "2013-10-01", "2013-11-01", "2013-12-01", "2014-01-01", "2014-02-01", "2014-03-01", "2014-04-01", "2014-05-01", "2014-06-01", "2014-07-01", "2014-08-01", "2014-09-01", "2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-06-01", "2015-07-01", "2015-08-01", "2015-09-01", "2015-10-01", "2015-11-01", "2015-12-01", "2016-01-01", "2016-02-01", "2016-03-01", "2016-04-01", "2016-05-01", "2016-06-01", "2016-07-01", "2016-08-01", "2016-09-01", "2016-10-01", "2016-11-01", "2016-12-01", "2017-01-01", "2017-02-01", "2017-03-01", "2017-04-01", "2017-05-01", "2017-06-01", "2017-07-01"]}, "credits": {"enabled": false}, "exporting": {"chartOptions": {"subtitle": null}, "sourceHeight": 900, "sourceWidth": 1600}, "legend": true}

Yet Highcharts renders this like:

Why does it display every single date instead of only showing some like in this example?

I tried changing the format of the dates being returned into a timestamp, used by Javascript's native Date.UTC, but that only makes it look worse:


问:
Is there a way to backup my docker environment
I am using Ubuntu 14.04 and running some docker containers and images with a python script.Now i have to reinstall that into another Ubuntu machine.

```<code>Ex: that machine is not even having docker installed
</code>```

Is there a way to backup complete docker engine from my configured machine to another machine

答:
At minimum, you has to install Docker (the same version if possible) on the new Ubuntu machine.

On your original machine, you can gracefully shutdown your containers. Backup /var/lib/docker (by default), and then restore on your new machine.

I do this with AWS EC2 spot instance. Not guarantee if this works with different version Docker.

Body:
I am using Ubuntu 14.04 and running some docker containers and images with a python script.Now i have to reinstall that into another Ubuntu machine.

Ex: that machine is not even having docker installed

Is there a way to backup complete docker engine from my configured machine to another machine


问:
Python switch statement with aliases
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

```<code>def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]
</code>```

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

```<code>def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value
</code>```

But this approach has worse than linear access time.

It can be made constant, by using

```<code>def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]
</code>```

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

答:
I would simply use an aliases dictionary without identity aliases besides your original case dictionary and check for potential aliases using get:

```<code>def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    aliases = {'telephone': 'phone', 'number': 'phone', 'site': 'website'}
    return case[aliases.get(s, s)]  # check if it's an alias or use the input as-is
</code>```

That way you don't need to duplicate the values (not in case and not in alias).

Title: Python switch statement with aliases

Body:
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value

But this approach has worse than linear access time.

It can be made constant, by using

def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

Body:
I would simply use an aliases dictionary without identity aliases besides your original case dictionary and check for potential aliases using get:

def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    aliases = {'telephone': 'phone', 'number': 'phone', 'site': 'website'}
    return case[aliases.get(s, s)]  # check if it's an alias or use the input as-is

That way you don't need to duplicate the values (not in case and not in alias).


问:
Select with a lot of tables
I'm trying to make a query for the sales report in which will be displayed the sales' code, the date, the amount of produts (only), the amount of tickets, the total sale value as well as the employee's name.
Click here to see the connection between the tables
Query I'm using which doesnt return an error but only return a row even if there is nothing on the Sales table or even if it's full of them

```<code>select sales.codv
, customers.name as customers
, concat(day(datav),'/',month(datav),'/',year(datav)) as date
, sum(prod_sal.amount) as 'products'
, count(tickets.codb) as 'tickets'
, sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) +
ifnull(tickets.price,0)) as 'total/€'
, employees.nome as employee
from sales
LEFT JOIN customers ON customers.codc=sales.codc
INNER JOIN employees ON employees.codf=sales.codf
LEFT JOIN prod_sal ON prod_sal.codv=sales.codv
LEFT JOIN products ON products.codp=prod_sal.codp
LEFT JOIN tickets ON tickets.codv=sales.codv
</code>```

NOTE: datav is the Sales' date

答:
If you don't use a group by clause MySQL will assume that you want to aggregate all rows that match your where clause. Since you don't have a where clause, that's everything in your db.

```<code>select
  sales.codv
  , customers.name as customers
  , concat(day(datav),'/',month(datav),'/',year(datav)) as date
  , sum(prod_sal.amount) as 'products'
  , count(tickets.codb) as 'tickets'
  , sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) + ifnull(tickets.price,0)) as 'total/€'
  , employees.nome as employee
from
  sales
  LEFT JOIN customers
    ON customers.codc=sales.codc
  INNER JOIN employees
    ON employees.codf=sales.codf
  LEFT JOIN prod_sal
    ON prod_sal.codv=sales.codv
  LEFT JOIN products
    ON products.codp=prod_sal.codp
  LEFT JOIN tickets
    ON tickets.codv=sales.codv
group by
  sales.codv
  , customers.name
  ,  concat(day(datav),'/',month(datav),'/',year(datav)) as date
</code>```

Title: Select with a lot of tables

Body:
I'm trying to make a query for the sales report in which will be displayed the sales' code, the date, the amount of produts (only), the amount of tickets, the total sale value as well as the employee's name.
Click here to see the connection between the tables
Query I'm using which doesnt return an error but only return a row even if there is nothing on the Sales table or even if it's full of them

select sales.codv
, customers.name as customers
, concat(day(datav),'/',month(datav),'/',year(datav)) as date
, sum(prod_sal.amount) as 'products'
, count(tickets.codb) as 'tickets'
, sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) +
ifnull(tickets.price,0)) as 'total/€'
, employees.nome as employee
from sales
LEFT JOIN customers ON customers.codc=sales.codc
INNER JOIN employees ON employees.codf=sales.codf
LEFT JOIN prod_sal ON prod_sal.codv=sales.codv
LEFT JOIN products ON products.codp=prod_sal.codp
LEFT JOIN tickets ON tickets.codv=sales.codv

NOTE: datav is the Sales' date

Body:
If you don't use a group by clause MySQL will assume that you want to aggregate all rows that match your where clause. Since you don't have a where clause, that's everything in your db.

select
  sales.codv
  , customers.name as customers
  , concat(day(datav),'/',month(datav),'/',year(datav)) as date
  , sum(prod_sal.amount) as 'products'
  , count(tickets.codb) as 'tickets'
  , sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) + ifnull(tickets.price,0)) as 'total/€'
  , employees.nome as employee
from
  sales
  LEFT JOIN customers
    ON customers.codc=sales.codc
  INNER JOIN employees
    ON employees.codf=sales.codf
  LEFT JOIN prod_sal
    ON prod_sal.codv=sales.codv
  LEFT JOIN products
    ON products.codp=prod_sal.codp
  LEFT JOIN tickets
    ON tickets.codv=sales.codv
group by
  sales.codv
  , customers.name
  ,  concat(day(datav),'/',month(datav),'/',year(datav)) as date


问:
Trying to hide again line with code of string in Android Studio
my question is hard to explain in text, but easy in screenshot :)
When i click on lane, which value in string.xml Android Studio show to user what is there. Something like this:

My question is: how to hide again this text in Anrdoid Studio ?

Thanks for your answers.

答:
That is called Folding and is by default set to shortcuts:

for expanding use  ctrl+"+"

for collapsing use ctrl+"-"

you can change these shortcuts in File -> Settings -> Keymap -> folding

this can also be done with the arrows on the side.

Hope this was helpful.


问:
Creating instance in CoreData
I'm using swift and I have a problem with CoreData.
What I'm trying to achieve is to create textfields(the number is up to the user) and store them in core data, and show this results at a second view. Is this possible?
I had a tip that I can make an entity for textfields and create and store instance and of this entry whenever a new textfield is created but how can I do this?

My app basically goes like,
firstView -> tableView -> secondView
and at the firstView user can add as much textfield they want. And I want to save the text of these made textfields and show it on the tableView. And when the user selects the cell it calls the secondView which basically the detail view and it needs to have the same number of textfields as the firstView. Is this possible?

Thank you vary much.

答:
What you need is called a segue. In iOS, CoreData is used to stored some data that can be reused after user shut down the app. So in your case, if you just want your table view to display the user inputs in the first view, simply use a segue. You can then pass data in this prepare for segue method.

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationViewController = segue.destination as? YourTableViewController {

        destinationViewController.texts = self.texts
        //...
    }
}
</code>```

Say you have 10 text fields and you want to store texts in them into Core Data. You need to first get all the texts and put them into an array of String. In future, when you get your array of string out, you will know how many text fields are there by doing a count on the array.

To save an array into CoreData, you must first convert the array into Data because CoreData cannot take the array type. So the code to convert to NSData and then save to CoreData will be

```<code>let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity =  NSEntityDescription.entityForName("Device", inManagedObjectContext:managedContext)
let device = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
let data = NSKeyedArchiver.archivedDataWithRootObject(array)
device.setValue(data, forKey: "dataOfArray")
do {
    try managedContext.save()
    devices.append(device)
} catch let error as NSError  {
    print("Could not save \(error), \(error.userInfo)")
}
</code>```

When you want to get the data out and convert back into array

```<code>let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Device")

do {
    let results = try managedContext.executeFetchRequest(fetchRequest)
    if results.count != 0 {
        for result in results {
                let data = result.valueForKey("dataOfArray") as! NSData
                let unarchiveObject = NSKeyedUnarchiver.unarchiveObjectWithData(data)
                let arrayObject = unarchiveObject as AnyObject! as! [[String: String]]
                let array = arrayObject
        }
    }
} catch let error as NSError {
    print("Could not fetch \(error), \(error.userInfo)")
}
</code>```

Title: Creating instance in CoreData

Body:
What you need is called a segue. In iOS, CoreData is used to stored some data that can be reused after user shut down the app. So in your case, if you just want your table view to display the user inputs in the first view, simply use a segue. You can then pass data in this prepare for segue method.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationViewController = segue.destination as? YourTableViewController {

        destinationViewController.texts = self.texts
        //...
    }
}

Say you have 10 text fields and you want to store texts in them into Core Data. You need to first get all the texts and put them into an array of String. In future, when you get your array of string out, you will know how many text fields are there by doing a count on the array.

To save an array into CoreData, you must first convert the array into Data because CoreData cannot take the array type. So the code to convert to NSData and then save to CoreData will be

let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity =  NSEntityDescription.entityForName("Device", inManagedObjectContext:managedContext)
let device = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
let data = NSKeyedArchiver.archivedDataWithRootObject(array)
device.setValue(data, forKey: "dataOfArray")
do {
    try managedContext.save()
    devices.append(device)
} catch let error as NSError  {
    print("Could not save \(error), \(error.userInfo)")
}

When you want to get the data out and convert back into array

let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Device")

do {
    let results = try managedContext.executeFetchRequest(fetchRequest)
    if results.count != 0 {
        for result in results {
                let data = result.valueForKey("dataOfArray") as! NSData
                let unarchiveObject = NSKeyedUnarchiver.unarchiveObjectWithData(data)
                let arrayObject = unarchiveObject as AnyObject! as! [[String: String]]
                let array = arrayObject
        }
    }
} catch let error as NSError {
    print("Could not fetch \(error), \(error.userInfo)")
}


问:
Can't pass global variables inside a function
I'm trying to run a FOR loop with variables that need to re-run again in another function and I need to code them out of the first function,
But the function receive them as "undefined".

When the variables are local inside the collectionChecking function except of ledTypes2 the variable of hostIndx2 is undefined when the function of handleResponse2 is trying to call him. This function should render the response as an icon from the method of ledTypes2 inside the HTML page.

```<code>var fetch = require('node-fetch');

var ledTypes = {
    green: "<img id='logo' src='green.png' height='30' width='30'>",
    red: "<img id='logo' src='red.png' height='30' width='30'>",
    yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};

var hosts2 = ['http://host1.com','host2.com','host3.com','host4.com'];
var hostIndx2 = 0;

var lengthVal = hosts2.length;
var token = '1213232431';
    function collectionChecking() {

        console.log("im inside the func" + hostIndx2 + "---" + lengthVal);
        for (; hostIndx2 < lengthVal; hostIndx2++) {
            console.log(hostIndx2);
            let url = hosts2[hostIndx2];
            // sendReq();
            fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}
            ).then(function (res, hostIndx2) {
                    console.log(res.status, hostIndx2);
                    handleLedResponse2(res, hostIndx2);

                });
        }
    }

function handleLedResponse2(res, hostIndx2) {
    var curSpan = document.getElementById('col_host_' + hostIndx2);
    console.log("IM HERE" + res.status + "---" + hostIndx2);
    if (res.status === 200 || res.status === 204) {
        curSpan.innerHTML = ledTypes.green;
    } else if (res.status === 500 || res.status === 404) {
        curSpan.innerHTML = ledTypes.red;
    } else if (res.status === 300 || res.status === 301 || res.status === 302) {
        curSpan.innerHTML = ledTypes.yellow;
    }
}
</code>```

答:
There are multiple things wrong in this code.

For starters, you can't use a for loop index variable like that in an asynchronous response.  The for loop will have completely finished before handleLedResponse2() is called and thus it will not have the desired value.

Secondly, you're declaring a .then() handler to have two arguments on this line:

```<code>.then(function (res, hostIndx2) {
</code>```

By specification a .then() handler is passed only one argument.  Thus you're defining an argument named hostIndx2 that will always be undefined and it will "hide" the higher scoped variable of the same name so you cannot access it.

 That is why you are seeing the value always be undefined.  The first thing to fix is to change the above code to just this:

```<code>.then(function (res) {
</code>```

That will give you access to the higher scoped hostIndx2 variable (it will no longer be undefine).  But, it probably won't have the desired value because of the mixing of a synchronous for loop and asynchronous fetch() calls as the for loop will have run to completion before any fetch().then() handlers get called.

I think that explains what is wrong with this part of the code, but I can't quite recommend the complete fix because I don't know for sure what you're trying to do.  I would theorize that hostIndx2 should not be a higher scoped variable at all as this just causes problems and makes opportunities for other things to trounce it.  It should likely be a local variable and then you should pass it as an argument to whatever you want to have access to it.

To fix the problem accessing it asynchronously, there are multiple options.  You can switch to defining it in the for loop itself with let and each invocation of the loop will get its own separate version of the variable (solving the async access issue).  Or, you could change your loop to use forEach which will create a new unique scope for each invocation of the loop.

With a few guesses about what you're trying to do, here's a cleaned up version:

```<code>const fetch = require('node-fetch');

const ledTypes = {
    green: "<img id='logo' src='green.png' height='30' width='30'>",
    red: "<img id='logo' src='red.png' height='30' width='30'>",
    yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};

const hosts2 = ['http://host1.com','http://host2.com','http://host3.com','http://host4.com'];
const token = '1213232431';

function collectionChecking() {
    hosts2.forEach(function(url, index) {
        console.log("im inside the func" + index);
        fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}).then(function (res) {
            console.log(res.status, index);
            handleLedResponse2(res, index);
        });
    }
}

function handleLedResponse2(res, hostIndx2) {
    let curSpan = document.getElementById('col_host_' + hostIndx2);
    console.log("IM HERE" + res.status + "---" + hostIndx2);
    if (res.status === 200 || res.status === 204) {
        curSpan.innerHTML = ledTypes.green;
    } else if (res.status === 500 || res.status === 404) {
        curSpan.innerHTML = ledTypes.red;
    } else if (res.status === 300 || res.status === 301 || res.status === 302) {
        curSpan.innerHTML = ledTypes.yellow;
    }
}
</code>```

P.S. I'm a bit confused here because your question is tagged as node.js and it appears you're using node-fetch (which implies a node.js environment), but then you show document.getElementById() which is not something you can use in node.js - that would normally be code that would run in a browser.

Body:
I'm trying to run a FOR loop with variables that need to re-run again in another function and I need to code them out of the first function,
But the function receive them as "undefined".

When the variables are local inside the collectionChecking function except of ledTypes2 the variable of hostIndx2 is undefined when the function of handleResponse2 is trying to call him. This function should render the response as an icon from the method of ledTypes2 inside the HTML page.

var fetch = require('node-fetch');

var ledTypes = {
    green: "",
    red: "",
    yellow: ""
};

var hosts2 = ['http://host1.com','host2.com','host3.com','host4.com'];
var hostIndx2 = 0;

var lengthVal = hosts2.length;
var token = '1213232431';
    function collectionChecking() {

        console.log("im inside the func" + hostIndx2 + "---" + lengthVal);
        for (; hostIndx2 < lengthVal; hostIndx2++) {
            console.log(hostIndx2);
            let url = hosts2[hostIndx2];
            // sendReq();
            fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}
            ).then(function (res, hostIndx2) {
                    console.log(res.status, hostIndx2);
                    handleLedResponse2(res, hostIndx2);

                });
        }
    }

function handleLedResponse2(res, hostIndx2) {
    var curSpan = document.getElementById('col_host_' + hostIndx2);
    console.log("IM HERE" + res.status + "---" + hostIndx2);
    if (res.status === 200 || res.status === 204) {
        curSpan.innerHTML = ledTypes.green;
    } else if (res.status === 500 || res.status === 404) {
        curSpan.innerHTML = ledTypes.red;
    } else if (res.status === 300 || res.status === 301 || res.status === 302) {
        curSpan.innerHTML = ledTypes.yellow;
    }
}

Body:
There are multiple things wrong in this code.

For starters, you can't use a for loop index variable like that in an asynchronous response.  The for loop will have completely finished before handleLedResponse2() is called and thus it will not have the desired value.

Secondly, you're declaring a .then() handler to have two arguments on this line:

.then(function (res, hostIndx2) {

By specification a .then() handler is passed only one argument.  Thus you're defining an argument named hostIndx2 that will always be undefined and it will "hide" the higher scoped variable of the same name so you cannot access it.

 That is why you are seeing the value always be undefined.  The first thing to fix is to change the above code to just this:

.then(function (res) {

That will give you access to the higher scoped hostIndx2 variable (it will no longer be undefine).  But, it probably won't have the desired value because of the mixing of a synchronous for loop and asynchronous fetch() calls as the for loop will have run to completion before any fetch().then() handlers get called.

I think that explains what is wrong with this part of the code, but I can't quite recommend the complete fix because I don't know for sure what you're trying to do.  I would theorize that hostIndx2 should not be a higher scoped variable at all as this just causes problems and makes opportunities for other things to trounce it.  It should likely be a local variable and then you should pass it as an argument to whatever you want to have access to it.

To fix the problem accessing it asynchronously, there are multiple options.  You can switch to defining it in the for loop itself with let and each invocation of the loop will get its own separate version of the variable (solving the async access issue).  Or, you could change your loop to use forEach which will create a new unique scope for each invocation of the loop.

With a few guesses about what you're trying to do, here's a cleaned up version:

const fetch = require('node-fetch');

const ledTypes = {
    green: "<img id='logo' src='green.png' height='30' width='30'>",
    red: "<img id='logo' src='red.png' height='30' width='30'>",
    yellow: "<img id='logo' src='yellow.png' height='30' width='30'>"
};

const hosts2 = ['http://host1.com','http://host2.com','http://host3.com','http://host4.com'];
const token = '1213232431';

function collectionChecking() {
    hosts2.forEach(function(url, index) {
        console.log("im inside the func" + index);
        fetch(url , {method: 'GET', headers:{"X-AUTH-TOKEN": token, "Content-Type": "text/plain"}, timeout: 30000}).then(function (res) {
            console.log(res.status, index);
            handleLedResponse2(res, index);
        });
    }
}

function handleLedResponse2(res, hostIndx2) {
    let curSpan = document.getElementById('col_host_' + hostIndx2);
    console.log("IM HERE" + res.status + "---" + hostIndx2);
    if (res.status === 200 || res.status === 204) {
        curSpan.innerHTML = ledTypes.green;
    } else if (res.status === 500 || res.status === 404) {
        curSpan.innerHTML = ledTypes.red;
    } else if (res.status === 300 || res.status === 301 || res.status === 302) {
        curSpan.innerHTML = ledTypes.yellow;
    }
}

P.S. I'm a bit confused here because your question is tagged as node.js and it appears you're using node-fetch (which implies a node.js environment), but then you show document.getElementById() which is not something you can use in node.js - that would normally be code that would run in a browser.


问:
Semantic UI change sidebar settings after initialization
My problem here is that it seems everytime I need to change some settings of my sidebar, I have to initiate it again, which causes it to change its context(reset settings to default).

How can I change a settings without initiating it?

Reference Doc : https://semantic-ui.com/modules/sidebar.html

For example :

```<code>var sidebar = $('#sidebar').sidebar({context : '#context_div'}); //Initiating

$('#button1').click(function(){
    //sidebar({closeable : false}) this doesn't work
    sidebar.sidebar({closeable : false}) //this initiates it again, reseting the context
})

$('#button2').click(function(){
    sidebar.sidebar({closeable : true})
})
</code>```

答:
Have you tried this?</p>

```<code>sidebar.sidebar('setting', 'closable', false)
</code>```

Body:
My problem here is that it seems everytime I need to change some settings of my sidebar, I have to initiate it again, which causes it to change its context(reset settings to default).

How can I change a settings without initiating it?

Reference Doc : https://semantic-ui.com/modules/sidebar.html

For example :

var sidebar = $('#sidebar').sidebar({context : '#context_div'}); //Initiating

$('#button1').click(function(){
    //sidebar({closeable : false}) this doesn't work
    sidebar.sidebar({closeable : false}) //this initiates it again, reseting the context
})

$('#button2').click(function(){
    sidebar.sidebar({closeable : true})
})

Body:
Have you tried this?

sidebar.sidebar('setting', 'closable', false)


问:
Angular 4 getting values from checkboxes
I am new to angular and am stuck at this pretty simple problem. I am getting data from a webservice to show a couple of checkboxes. I need a way to get the value of all of the checkboxes selected by the user. I am using material theme. </p>

```<code><span *ngFor="let x of maintainanceTypeList">
    <md-checkbox
       name="{{x.maintenancetype}}"
       value="{{x.maintenancetype}}"
       [formControl]="CreateSocietyForm.controls['checkMaintainanceType']">
         {{x.maintenancetype}}
    </md-checkbox>
</span>
</code>```

答:
You can add a change event to md-checkbox and pass the object to a function. Maintain an array that keep track of which ones got checked and unchecked and update the array according to that.

html:

```<code><span *ngFor="let x of maintainanceTypeList">
    <md-checkbox
       name="{{x.maintenancetype}}"
       value="{{x.maintenancetype}}"
       (change)="change($event, x)">
         {{x.maintenancetype}}
    </md-checkbox>
</span>

<p> Selected value: {{selectedValue | json}} </p>
</code>```

component.ts:

```<code>export class SelectFormExample {
  selectedValue = [];

  maintainanceTypeList = [
    {maintenancetype: 'Steak'},
    {maintenancetype: 'Pizza'},
    {maintenancetype: 'Tacos'}
  ];

  change(e, type){
    console.log(e.checked);
    console.log(type);
    if(e.checked){
      this.selectedValue.push(type);
    }
    else{
     let updateItem = this.selectedValue.find(this.findIndexToUpdate, type.maintenancetype));

     let index = this.selectedValue.indexOf(updateItem);

     this.selectedValue.splice(index, 1);
    }

  }

  findIndexToUpdate(type) {
        return type.maintenancetype === this;
    }
}
</code>```

Plunker demo

Body:
I am new to angular and am stuck at this pretty simple problem. I am getting data from a webservice to show a couple of checkboxes. I need a way to get the value of all of the checkboxes selected by the user. I am using material theme.

    <md-checkbox
       name="{{x.maintenancetype}}"
       value="{{x.maintenancetype}}"
       [formControl]="CreateSocietyForm.controls['checkMaintainanceType']">
         {{x.maintenancetype}}
    </md-checkbox>

Body:
You can add a change event to md-checkbox and pass the object to a function. Maintain an array that keep track of which ones got checked and unchecked and update the array according to that.

html:

<span *ngFor="let x of maintainanceTypeList">
    <md-checkbox
       name="{{x.maintenancetype}}"
       value="{{x.maintenancetype}}"
       (change)="change($event, x)">
         {{x.maintenancetype}}
    </md-checkbox>
</span>

<p> Selected value: {{selectedValue | json}} </p>

component.ts:

export class SelectFormExample {
  selectedValue = [];

  maintainanceTypeList = [
    {maintenancetype: 'Steak'},
    {maintenancetype: 'Pizza'},
    {maintenancetype: 'Tacos'}
  ];

  change(e, type){
    console.log(e.checked);
    console.log(type);
    if(e.checked){
      this.selectedValue.push(type);
    }
    else{
     let updateItem = this.selectedValue.find(this.findIndexToUpdate, type.maintenancetype));

     let index = this.selectedValue.indexOf(updateItem);

     this.selectedValue.splice(index, 1);
    }

  }

  findIndexToUpdate(type) {
        return type.maintenancetype === this;
    }
}

Plunker demo


问:
Java Swing - How to sound beep before any JOptionPane?
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

```<code>Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );
</code>```

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?

答: You could create your own class which has a static method showMessageDialogAndBeep() which calls JOptionPane.showMessageDialog and beeps before.

Body:
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?


问:
Group data frame columns by their dates (which comprise column titles) and summarize instances of 1s and 0s in R
I have a bit of annoying coding problem, about which I'd appreciate your assistance.

Here are some sample data:

```<code>ID     "2013-03-20"    "2013-04-09"    "2013-04-11"    "2013-04-17"
5167f            0               0               0               1
1214m            0               0               0               0
1844f            0               1               1               0
2113m            0               0               1               1
</code>```

Here's the rub: notice how the column names of the sample data frame comprise dates, and some dates can be close to one another. The ID column is a simple unique identifier for the observations.

Here are my goals:

(1) I'd like to be able to first group the columns by whether or not they each fall within a 2-week (or 14-day) range (i.e. that is defined by 2-week increments starting on "2013-03-20" until "2016-12-20"); thus, if they do fall within the same range, they'd receive the same identifier (for a new data frame; e.g., Period1 for any dates that fall between "2013-03-20" and "2013-04-03").

(2) Once all of the date columns are assigned to a particular period, I then want to summarize the cell data (of 0s and 1s) per period in the following way: if any 1 appears in a particular period for an individual (at all) then that individual would receive a 1 for the whole period (also, if the individual only has 0s for that period, then it would receive a 0 for that single period).

(3) Once this workflow is defined, I then want to group the dates by seasons and years based on their month codes (e.g., WinterYYYY = December, January, February; SpringYYYY = March, April, May; SummerYYYY = June, July, August; and FallYYYY = September, October, November) to produce a new data frame.

In summary, to demonstrate the products manually:

(End Product for Goals 1 and 2; i.e. for just first two columns in the sample data [date ranges in parentheses are just for a guide])

```<code>ID     Period1 ("2013-03-20" - "2013-04-03")        Period2 ("2013-04-04" - "2013-04-18")
5167f                                    0                                 1
1214m                                    0                                 0
1844f                                    0                                 1
2113m                                    0                                 1
</code>```

(End Product for Goals 2 and 3; i.e. for all columns in the sample data [month ranges in parentheses are just for a guide])

```<code>ID                Spring2013  (March - May)
5167f                                    1
1214m                                    0
1844f                                    1
2113m                                    1
</code>```

Perhaps, something from the dplyr package could be useful, but I'm not quite sure.

Thank you for any help, in advance. Please feel free to ask any follow-up questions for clarifications.

-AD-

答:
Here is a solution using functions from tidyverse.

```<code># Load packages
library(tidyverse)
library(data.table)
library(lubridate)

# Create example data frames
dt <- fread("ID     '2013-03-20'    '2013-04-09'    '2013-04-11'    '2013-04-17'
5167f            0               0               0               1
                 1214m            0               0               0               0
                 1844f            0               1               1               0
                 2113m            0               0               1               1")
</code>```

The key is to prepare a table showing the association between date and grouping variable, such as period, month, or season. In this example, dt_merge is such table.

```<code>dt_merge <- data_frame(
  # Create a column showing the beginning date
  Date1 = seq(from = ymd("2013-03-20"), to = ymd("2016-12-20"), by = "2 weeks")) %>%
  # Create  a column showing the end date of each period
  mutate(Date2 = lead(Date1)) %>%
  # Adjust Date1
  mutate(Date1 = if_else(Date1 == ymd("2013-03-20"), Date1, Date1 + 1)) %>%
  # Remove the last row
  drop_na(Date2) %>%
  # Create date list
  mutate(Dates = map2(Date1, Date2, function(x, y){ seq(x, y, by = "day") })) %>%
  unnest() %>%
  # Create Group ID
  mutate(RunID = group_indices_(., dots. = c("Date1", "Date2"))) %>%
  # Create Period ID
  mutate(Period = paste0("Period", RunID)) %>%
  # Add a column showing Month
  mutate(Month = month(Dates)) %>%
  # Add a column showing Year
  mutate(Year = year(Dates)) %>%
  # Add a column showing season
  mutate(Season = case_when(
    Month %in% 3:5            ~ "Spring",
    Month %in% 6:8            ~ "Summer",
    Month %in% 9:11           ~ "Fall",
    Month %in% c(12, 1, 2)    ~ "Winter",
    TRUE                      ~ NA_character_
  )) %>%
  # Combine Season and Year
  mutate(SeasonYear = paste0(Season, Year)) %>%
  select(-Date1, -Date2, -RunID)
</code>```

After this step, it becomes easy to generate the output you want to. In this example, dt3 is the first end product. dt4 is the second product.

```<code>dt2 <- dt %>%
  # Reshape the data frame
  gather(Date, Value, -ID) %>%
  # Convert Date to date class
  mutate(Date = ymd(Date)) %>%
  # Join dt_merge
  left_join(dt_merge, by = c("Date" = "Dates"))

# Product 1
dt3 <- dt2 %>%
  group_by(ID, Period) %>%
  summarise(Value = max(Value)) %>%
  spread(Period, Value)

# Product 2
dt4 <- dt2
  group_by(ID, SeasonYear) %>%
  summarise(Value = max(Value)) %>%
  spread(SeasonYear, Value)
</code>```

Body:
I have a bit of annoying coding problem, about which I'd appreciate your assistance.

Here are some sample data:

ID     "2013-03-20"    "2013-04-09"    "2013-04-11"    "2013-04-17"
5167f            0               0               0               1
1214m            0               0               0               0
1844f            0               1               1               0
2113m            0               0               1               1

Here's the rub: notice how the column names of the sample data frame comprise dates, and some dates can be close to one another. The ID column is a simple unique identifier for the observations.

Here are my goals:

(1) I'd like to be able to first group the columns by whether or not they each fall within a 2-week (or 14-day) range (i.e. that is defined by 2-week increments starting on "2013-03-20" until "2016-12-20"); thus, if they do fall within the same range, they'd receive the same identifier (for a new data frame; e.g., Period1 for any dates that fall between "2013-03-20" and "2013-04-03").

(2) Once all of the date columns are assigned to a particular period, I then want to summarize the cell data (of 0s and 1s) per period in the following way: if any 1 appears in a particular period for an individual (at all) then that individual would receive a 1 for the whole period (also, if the individual only has 0s for that period, then it would receive a 0 for that single period).

(3) Once this workflow is defined, I then want to group the dates by seasons and years based on their month codes (e.g., WinterYYYY = December, January, February; SpringYYYY = March, April, May; SummerYYYY = June, July, August; and FallYYYY = September, October, November) to produce a new data frame.

In summary, to demonstrate the products manually:

(End Product for Goals 1 and 2; i.e. for just first two columns in the sample data [date ranges in parentheses are just for a guide])

ID     Period1 ("2013-03-20" - "2013-04-03")        Period2 ("2013-04-04" - "2013-04-18")
5167f                                    0                                 1
1214m                                    0                                 0
1844f                                    0                                 1
2113m                                    0                                 1

(End Product for Goals 2 and 3; i.e. for all columns in the sample data [month ranges in parentheses are just for a guide])

ID                Spring2013  (March - May)
5167f                                    1
1214m                                    0
1844f                                    1
2113m                                    1

Perhaps, something from the dplyr package could be useful, but I'm not quite sure.

Thank you for any help, in advance. Please feel free to ask any follow-up questions for clarifications.

-AD-

Body:
Here is a solution using functions from tidyverse.

# Load packages
library(tidyverse)
library(data.table)
library(lubridate)

# Create example data frames
dt <- fread("ID     '2013-03-20'    '2013-04-09'    '2013-04-11'    '2013-04-17'
5167f            0               0               0               1
                 1214m            0               0               0               0
                 1844f            0               1               1               0
                 2113m            0               0               1               1")

The key is to prepare a table showing the association between date and grouping variable, such as period, month, or season. In this example, dt_merge is such table.

dt_merge <- data_frame(
  # Create a column showing the beginning date
  Date1 = seq(from = ymd("2013-03-20"), to = ymd("2016-12-20"), by = "2 weeks")) %>%
  # Create  a column showing the end date of each period
  mutate(Date2 = lead(Date1)) %>%
  # Adjust Date1
  mutate(Date1 = if_else(Date1 == ymd("2013-03-20"), Date1, Date1 + 1)) %>%
  # Remove the last row
  drop_na(Date2) %>%
  # Create date list
  mutate(Dates = map2(Date1, Date2, function(x, y){ seq(x, y, by = "day") })) %>%
  unnest() %>%
  # Create Group ID
  mutate(RunID = group_indices_(., dots. = c("Date1", "Date2"))) %>%
  # Create Period ID
  mutate(Period = paste0("Period", RunID)) %>%
  # Add a column showing Month
  mutate(Month = month(Dates)) %>%
  # Add a column showing Year
  mutate(Year = year(Dates)) %>%
  # Add a column showing season
  mutate(Season = case_when(
    Month %in% 3:5            ~ "Spring",
    Month %in% 6:8            ~ "Summer",
    Month %in% 9:11           ~ "Fall",
    Month %in% c(12, 1, 2)    ~ "Winter",
    TRUE                      ~ NA_character_
  )) %>%
  # Combine Season and Year
  mutate(SeasonYear = paste0(Season, Year)) %>%
  select(-Date1, -Date2, -RunID)

After this step, it becomes easy to generate the output you want to. In this example, dt3 is the first end product. dt4 is the second product.

dt2 <- dt %>%
  # Reshape the data frame
  gather(Date, Value, -ID) %>%
  # Convert Date to date class
  mutate(Date = ymd(Date)) %>%
  # Join dt_merge
  left_join(dt_merge, by = c("Date" = "Dates"))

# Product 1
dt3 <- dt2 %>%
  group_by(ID, Period) %>%
  summarise(Value = max(Value)) %>%
  spread(Period, Value)

# Product 2
dt4 <- dt2
  group_by(ID, SeasonYear) %>%
  summarise(Value = max(Value)) %>%
  spread(SeasonYear, Value)


问:
Atom node-debugger gives two errors on startup
With Node 8, I install Node Debugger into Atom, and set the path to Node.  Then I try to run a simple script with F5.  I get the errors:

Connection attempt 1 to node process on 127.0.0.1:5858 failed
(node:77739) [DEP0062] DeprecationWarning: node --debug and node --debug-brk are invalid. Please use node --inspect or node --inspect-brk

How do I fix this?

答: It seems that there is already an issue open on the repo for this deprecation problem. The package needs to be updated, however it seems like there hasn't been much activity in the last few months.</p>


问:
jQuery Mobile not working in WebView when loading from local assets
I am trying to render in my Android app a page created using jQueryMobile, but I need to do it in a webView, in an offline state.

For that purpose, I started copying the index.html of my page and taking all the required assets straight to the internal storage of my device. I then loaded it up typing file:///sdcard/index.html in both the internal browser of my device and the Chrome app, and the website showed up just fine, with jQuery styles and all.

Then I move in to my app, where I have a webView, and that's where I actually need to render the aforementioned page. I load the page using loadDataWithBaseURL() (because that's what I ultimately need to do) like this:

```<code>loadDataWithBaseURL("file:///android_asset/web/", html, "text/html", "UTF-8", null);
</code>```

I keep all my assets in the web directory of my assets folder.

The problem is, if I load the page without the assets reference (just normally calling loadUrl) it loads but obviously without styling or functionality. When I put the assets reference calling loadDataWithBaseURL it IS indeed reading the asset reference properly but the rendering is stuck with jqueryMobile's spinning wheel and the page never actually loads. This is what I see:

So to sum it up:

I have created a website using jQuery Mobile. It's just a simple html
page with jQuery's styling.

I have prepared it for offline loading. I packed the required assets
into a folder and in the index.html I reference these assets relatively (e.g. href="web/styles.css").

If I load this page in my desktop browser, without connectivity, it
works.

If I load this page in my mobile browser (Chrome or the internal

one), it works.

If I load this page without the assets references in my webview,
it works (without styling or images, etc.)

If I load this page with the assets reference in my webview, it

does not work, it's stuck with the spinning wheel. Connectivity does not affect the issue.

If I remove the line that references the jQM stylesheet, then the page is
loaded without its styling, but images are loaded properly (so the
reference to the assets is correct)

Note that the spinning wheel shouldn't even be appearing in the first place since I completely disabled AJAX in jQM using:

```<code><script>
$.mobile.ajaxEnabled = false;
</script>
</code>```

The odd thing is that AFAIK the internal Android web browser and webviews share the same renderer, so I'm lost as to what could be happening here, and since it works okay with regular browsers, I can debug what's happening.

For reference, this is how I define my webView:

```<code>    mWebView = (WebView) findViewById(R.id.webView);
    WebSettings s = mWebView.getSettings();
    s.setJavaScriptEnabled(true);
</code>```

I had a bunch of other settings but for the sake of simplifying the problem I removed them and the issue persists.

Any suggestions?

PD. As requested, posting the index.html file. This is the simplest example, just an empty index. The problem persists:

```<code><!doctype html>
<html lang=es>
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="format-detection" content="telephone=no" />
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="320" />
<head>
<title>
    My title
</title>

<script>
$.mobile.ajaxEnabled = false;
</script>

<script src="script/jquery/jquery-1.9.1.min.js"></script>
<script src="script/jquery/jquery.mobile-1.3.2.min.js"></script>
<link href="css/jquery.mobile-1.3.2.min.css" rel="stylesheet" media="screen" type="text/css"  />

</head>

<body>

</body>
</html>
</code>```

答:
A big thanks to Gabriel Sanmartin. I had a similar situation but I was using the regular jQuery, not mobile, and calling the .load() function to load a local partial html file into a div, like so:

```<code>var divNew = document.createElement('div');
var $divNew = $(divNew);
var sFilePath = sSubfolder + '/' + 'Index.html';
$divNew.load(sFilePath, function (response, status, xhr) {
    if (status == "error") {

    }
});
</code>```

I spent almost half a day going thru & debugging the JS code until I came upon this thread. Finding those two settings was fantastic. It made all the difference. My C# code is below:

```<code>if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
{
      wbView.Settings.AllowUniversalAccessFromFileURLs = true;
      wbView.Settings.AllowFileAccessFromFileURLs = true;
}
</code>```

Fyi:
Android.OS.BuildVersionCodes.JellyBean was recommended as Android.OS.Build.VERSION_CODES.JellyBean is obsolete and will be removed in future versions.

Body:
I am trying to render in my Android app a page created using jQueryMobile, but I need to do it in a webView, in an offline state.

For that purpose, I started copying the index.html of my page and taking all the required assets straight to the internal storage of my device. I then loaded it up typing file:///sdcard/index.html in both the internal browser of my device and the Chrome app, and the website showed up just fine, with jQuery styles and all.

Then I move in to my app, where I have a webView, and that's where I actually need to render the aforementioned page. I load the page using loadDataWithBaseURL() (because that's what I ultimately need to do) like this:

loadDataWithBaseURL("file:///android_asset/web/", html, "text/html", "UTF-8", null);

I keep all my assets in the web directory of my assets folder.

The problem is, if I load the page without the assets reference (just normally calling loadUrl) it loads but obviously without styling or functionality. When I put the assets reference calling loadDataWithBaseURL it IS indeed reading the asset reference properly but the rendering is stuck with jqueryMobile's spinning wheel and the page never actually loads. This is what I see:

So to sum it up:

I have created a website using jQuery Mobile. It's just a simple html
page with jQuery's styling.

I have prepared it for offline loading. I packed the required assets
into a folder and in the index.html I reference these assets relatively (e.g. href="web/styles.css").

If I load this page in my desktop browser, without connectivity, it
works.

If I load this page in my mobile browser (Chrome or the internal

one), it works.

If I load this page without the assets references in my webview,
it works (without styling or images, etc.)

If I load this page with the assets reference in my webview, it

does not work, it's stuck with the spinning wheel. Connectivity does not affect the issue.

If I remove the line that references the jQM stylesheet, then the page is
loaded without its styling, but images are loaded properly (so the
reference to the assets is correct)

Note that the spinning wheel shouldn't even be appearing in the first place since I completely disabled AJAX in jQM using:

The odd thing is that AFAIK the internal Android web browser and webviews share the same renderer, so I'm lost as to what could be happening here, and since it works okay with regular browsers, I can debug what's happening.

For reference, this is how I define my webView:

    mWebView = (WebView) findViewById(R.id.webView);
    WebSettings s = mWebView.getSettings();
    s.setJavaScriptEnabled(true);

I had a bunch of other settings but for the sake of simplifying the problem I removed them and the issue persists.

Any suggestions?

PD. As requested, posting the index.html file. This is the simplest example, just an empty index. The problem persists:

<!doctype html>

<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="format-detection" content="telephone=no" />
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="320" />

<title>
    My title
</title>

<link href="css/jquery.mobile-1.3.2.min.css" rel="stylesheet" media="screen" type="text/css"  />

Body:
A big thanks to Gabriel Sanmartin. I had a similar situation but I was using the regular jQuery, not mobile, and calling the .load() function to load a local partial html file into a div, like so:

var divNew = document.createElement('div');
var $divNew = $(divNew);
var sFilePath = sSubfolder + '/' + 'Index.html';
$divNew.load(sFilePath, function (response, status, xhr) {
    if (status == "error") {

    }
});

I spent almost half a day going thru & debugging the JS code until I came upon this thread. Finding those two settings was fantastic. It made all the difference. My C# code is below:

if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
{
      wbView.Settings.AllowUniversalAccessFromFileURLs = true;
      wbView.Settings.AllowFileAccessFromFileURLs = true;
}

Fyi:
Android.OS.BuildVersionCodes.JellyBean was recommended as Android.OS.Build.VERSION_CODES.JellyBean is obsolete and will be removed in future versions.


问:
How can I add the current date to my database table using php
The user will adds information into a textbox. when they click send the information is added to the database table using this php code:

```<code>$sql = "INSERT INTO mytable (id, number, date)
VALUES ('', '$_POST[number]', 'date(1)')";
</code>```

The 'id' is auto-id from phpmyadmin settings so its left blank. I want the current date to also display in the table as well.

I though by putting in date(1) to get the date would work but it doesn't seem to.
Any ideas?

I set the date column in phpmyadmin to receive a date. So when I set the code to:

```<code>$sql = "INSERT INTO mytable (id, number, date)
VALUES ('', '$_POST[number]', '')";
</code>```

it just gives me 0000-00-00 in my table.
Any ideas how to fix this? so I can get the current date?

答:
By enclosing it in single quotes, you are actually passing a string value.  You can either use MYSQL now() or set a default value for the column to supply a date automatically if one is not supplied.

```<code>$sql = "INSERT INTO mytable (number, date)
VALUES ('". $_POST['number'] ."', NOW())";
</code>```

Take note of the quotes around the $_POST['number'] as this also goes back to the issue stated above.  You want to make sure that you are escaping the values properly, otherwise, strings will be passed instead of the desired values.

Body:
The user will adds information into a textbox. when they click send the information is added to the database table using this php code:

$sql = "INSERT INTO mytable (id, number, date)
VALUES ('', '$_POST[number]', 'date(1)')";

The 'id' is auto-id from phpmyadmin settings so its left blank. I want the current date to also display in the table as well.

I though by putting in date(1) to get the date would work but it doesn't seem to.
Any ideas?

I set the date column in phpmyadmin to receive a date. So when I set the code to:

$sql = "INSERT INTO mytable (id, number, date)
VALUES ('', '$_POST[number]', '')";

it just gives me 0000-00-00 in my table.
Any ideas how to fix this? so I can get the current date?

Body:
By enclosing it in single quotes, you are actually passing a string value.  You can either use MYSQL now() or set a default value for the column to supply a date automatically if one is not supplied.

$sql = "INSERT INTO mytable (number, date)
VALUES ('". $_POST['number'] ."', NOW())";

Take note of the quotes around the $_POST['number'] as this also goes back to the issue stated above.  You want to make sure that you are escaping the values properly, otherwise, strings will be passed instead of the desired values.


答:
Use Mysql NOW():-

```<code>$sql = "INSERT INTO mytable (number, date) VALUES ('".$_POST['number']."', NOW())";//check the quotes too
</code>```

Note:-

1.I hope id is PRIMARY AUTO-INCREMENTED value so no need to pass it.

2.Also this code is vulnerable to SQL-injection.Read PHP mysqli_* or PDO along with prepared statements to prevent from it.

Title: How can I add the current date to my database table using php

Body:
Use Mysql NOW():-

$sql = "INSERT INTO mytable (number, date) VALUES ('".$_POST['number']."', NOW())";//check the quotes too

Note:-

1.I hope id is PRIMARY AUTO-INCREMENTED value so no need to pass it.

2.Also this code is vulnerable to SQL-injection.Read PHP mysqli_* or PDO along with prepared statements to prevent from it.


问:
Can we write independent of machine(i.e. independent of OS) code in asp.net?
As i have read MSIL manages the code to make it independent of machine;but i have also read that DOT NET just provide windows independence not Plateform.
Please Explain if </p>

答:
Answer is 50:50. IL code is equivalent to Java byte code. Byte code is understood by JVM whereas IL code is understood by CLR. At present there are JVM versions available for almost every OS, almost every processor architecture and what not. However this is not the case for CLR. Microsoft version of CLR is exclusively available for Windows only. Hence you are "virtually" tied up to platform.

Flip side of story is that Mono is another version of CLR which is being backed by Novell and it is capable of running Windows Forms application as well as ASP.Net application. But their version is usually 1 version behind MS version. HTH


问:
How to access protected properties in gtmetrix API
I am using GTMATRIX api to fetch pagespeedscore and other data. and I am using this library https://github.com/entrecore/php-gtmetrix. so far I created index.php file and get the results as:

```<code><?php
require_once('vendor/autoload.php');
use Entrecore\GTMetrixClient\GTMetrixClient;
use Entrecore\GTMetrixClient\GTMetrixTest;

$client = new GTMetrixClient();
$client->setUsername('shahroze.nawaz@cloudways.com');
$client->setAPIKey('e16345e33e9d3371b2d64bb93dc56189');

$client->getLocations();
$client->getBrowsers();
$test = $client->startTest('https://www.cloudways.com/en/');

//Wait for result
while ($test->getState() != GTMetrixTest::STATE_COMPLETED &&
    $test->getState() != GTMetrixTest::STATE_ERROR) {
    $final = $client->getTestStatus($test);
}

echo '```';
var_dump($final);
echo '```';
</code>```

This will giving the following output:

The problem is I can't able to access the protected properties and the file URL's any help would be appreciated.

Thanks.

答:
It is because you got returned an object GTMetrixTest

if you will have a look at source code of this class you will realize that all protected things have public getters.

So, reading the class, you will find this public function:

```<code>/**
 * @return array
 */
public function getResources() {
    return $this->resources;
}
</code>```

So in your code, you will later on call

```<code>$resources = $final->getResources();
var_dump($resources); //should return accessible array
</code>```

Body:
I am using GTMATRIX api to fetch pagespeedscore and other data. and I am using this library https://github.com/entrecore/php-gtmetrix. so far I created index.php file and get the results as:

<?php
require_once('vendor/autoload.php');
use Entrecore\GTMetrixClient\GTMetrixClient;
use Entrecore\GTMetrixClient\GTMetrixTest;

$client = new GTMetrixClient();
$client->setUsername('shahroze.nawaz@cloudways.com');
$client->setAPIKey('e16345e33e9d3371b2d64bb93dc56189');

$client->getLocations();
$client->getBrowsers();
$test = $client->startTest('https://www.cloudways.com/en/');

//Wait for result
while ($test->getState() != GTMetrixTest::STATE_COMPLETED &&
    $test->getState() != GTMetrixTest::STATE_ERROR) {
    $final = $client->getTestStatus($test);
}

echo '
';
var_dump($final);
echo '
';

This will giving the following output:

The problem is I can't able to access the protected properties and the file URL's any help would be appreciated.

Thanks.

Body:
It is because you got returned an object GTMetrixTest

if you will have a look at source code of this class you will realize that all protected things have public getters.

So, reading the class, you will find this public function:

/**
 * @return array
 */
public function getResources() {
    return $this->resources;
}

So in your code, you will later on call

$resources = $final->getResources();
var_dump($resources); //should return accessible array


问:
Check for an empty map
I'm having an interesting issue that I'm sure is easily explained, but the explanation is eluding me.

An undefined or null object in javascript is equal to false.

```<code>var x;
alert(!x); //returns true
alert(x==true); //returns false
</code>```

What about an empty array object? Is that the equivalent of true or false?

```<code>var x = [];
alert (x==true); //returns false
alert (!x); //returns false
</code>```

If it is equivalent to true, how do I check if it's non-empty? I was hoping to do

```<code>if (!x) {
    //do stuff
}
</code>```

I tried checking x.length, but I'm using this object as a map:

```<code>var x = [];
alert(x.length); //returns 0
x.prop = "hello";
alert(x.length); //still returns 0
</code>```

How can I check if my map is empty?

答:
If you're using a Proper JS Map<K, V> Object, you can simply use the Map API on Mozilla Docs.

Specifically there is a Map.prototype.size property, as well as Map.prototype.entries() method, which I believe returns an Array [] of keys. If that is length 0 then the map is empty.

Title: Check for an empty map

Body:
I'm having an interesting issue that I'm sure is easily explained, but the explanation is eluding me.

An undefined or null object in javascript is equal to false.

var x;
alert(!x); //returns true
alert(x==true); //returns false

What about an empty array object? Is that the equivalent of true or false?

var x = [];
alert (x==true); //returns false
alert (!x); //returns false

If it is equivalent to true, how do I check if it's non-empty? I was hoping to do

if (!x) {
    //do stuff
}

I tried checking x.length, but I'm using this object as a map:

var x = [];
alert(x.length); //returns 0
x.prop = "hello";
alert(x.length); //still returns 0

How can I check if my map is empty?


问:
Is it possible that mutliproccessing causes stream lag?
I have a server that receives audio stream data from a client and then sends it to all other connected clients (via sockets). Since the data stream makes the code stuck on a loop , I decided that I should create processes for each stream (client essentially). I noticed that even with one connected client , the process makes the audio lag. Why is that ? That also happens if I try to use threads.

Code:

```<code>p_r = Process(target=playback_f,
              args=(pass_record, soc, client, port_a, data, c)).start()
</code>```

Where soc is the socket connection of the client in question, data is the initial data and c is the result of:

```<code>c, addr1 = s.accept()
</code>```

The process calls:

```<code>def playback_f(pass_record, soc, client, port_a, data, c):
    try:
        stop_recording = False
        try :
            soc.sendto('playback'.encode('utf-8'),(client,port_a))
        except Exception as e:
            print (e)

        while stop_recording == False:
            if data !=  b'stop_rec':
                try:
                    data = c.recv(1024)
                    soc.sendto(data,(client,port_a))
                except Exception as e:
                    print (e)
            else:
                stop_recording = True

        print('ended')

    except Exception as e:
        print(e)
</code>```

答:
It's really hard to debug without a code or any sorts of specifications. However, I do have a possible idea why this lag might be occurring.
When you use multiprocessing, you are creating multiple processes with each process trying to connect to the same external socket at the same time. Multiple simultaneous connections can get laggy on a bad internet. Moreover, if you don't use locks, you'll get an erroneous output and if you use them, it'll lead to further possible lag. Hence it is better to avoid multiprocessing in this case.
As for threading, this might occur due to a built-in locking system called GIL.</p>

Body:
I have a server that receives audio stream data from a client and then sends it to all other connected clients (via sockets). Since the data stream makes the code stuck on a loop , I decided that I should create processes for each stream (client essentially). I noticed that even with one connected client , the process makes the audio lag. Why is that ? That also happens if I try to use threads.

Code:

p_r = Process(target=playback_f,
              args=(pass_record, soc, client, port_a, data, c)).start()

Where soc is the socket connection of the client in question, data is the initial data and c is the result of:

c, addr1 = s.accept()

The process calls:

def playback_f(pass_record, soc, client, port_a, data, c):
    try:
        stop_recording = False
        try :
            soc.sendto('playback'.encode('utf-8'),(client,port_a))
        except Exception as e:
            print (e)

        while stop_recording == False:
            if data !=  b'stop_rec':
                try:
                    data = c.recv(1024)
                    soc.sendto(data,(client,port_a))
                except Exception as e:
                    print (e)
            else:
                stop_recording = True

        print('ended')

    except Exception as e:
        print(e)


问:
Why do I get "An internal error occurred (eid 8410529)" when I try to Create An App on Yahoo Weather API?
Yahoo weather API at https://developer.yahoo.com/weather/#get-started has a link under 'Get your API Keys' there is a button named 'Creat an App' that points to https://developer.yahoo.com/apps/create/.

Both in Chrome and IE11 when I click on it I get "An internal error occurred (eid 3030034)."

Yahoo forum requests that user us SO with tag #yahoo-weather-api

Thanks!

答: Same here. Seems to be a problem at Yahoo's service. Guess we'll have to just wait until it's fixed.</p>