问:
Pandas: groupby some data
I have dataframe

```<code>datetime    city    state   country shape   duration (seconds)  duration (hours/min)    comments    date posted latitude    longitude
10/10/1949 20:30    san marcos  tx  us  cylinder    2700    45 minutes  This event took place in early fall around 1949-50. It occurred after a Boy Scout meeting in the Baptist Church. The Baptist Church sit 4/27/2004   29.8830556  -97.9411111
10/10/1949 21:00    lackland afb    tx      light   7200    1-2 hrs 1949 Lackland AFB&#44 TX. Lights racing across the sky & making 90 degree turns on a dime.  12/16/2005  29.38421    -98.581082
10/10/1955 17:00    chester (uk/england)        gb  circle  20  20 seconds  Green/Orange circular disc over Chester&#44 England 1/21/2008   53.2    -2.916667
10/10/1956 21:00    edna    tx  us  circle  20  1/2 hour    My older brother and twin sister were leaving the only Edna theater at about 9 PM&#44...we had our bikes and I took a different route home  1/17/2004   28.9783333  -96.6458333
10/10/1960 20:00    kaneohe hi  us  light   900 15 minutes  AS a Marine 1st Lt. flying an FJ4B fighter/attack aircraft on a solo night exercise&#44 I was at 50&#44000&#39 in a "clean" aircraft (no ordinan  1/22/2004   21.4180556  -157.8036111
</code>```

I try do group by state
I use

```<code>result = df.groupby("state").\
    agg({"state": pd.Series.nunique, "duration (seconds)": np.sum}).\
    rename(columns={"state": "frequency", "duration (seconds)": "whole time"}).\
    reset_index()
</code>```

But it returns error TypeError: must be str, not float.
I try to convert duration (seconds) but it returns
duration (seconds).
How can I check this problem?

答:
do something like:

```<code># Group df by df.state, then apply a sum lambda function to df.duration(seconds)
df.groupby('state')['duration (seconds)'].apply(lambda x:x.mean())
</code>```

Or if you want a rolling sum:

```<code>df.groupby('state')['duration (seconds)'].apply(lambda x:x.rolling(center=False,window=2).sum())
</code>```

Title: Pandas: groupby some data

Body:
I have dataframe

datetime    city    state   country shape   duration (seconds)  duration (hours/min)    comments    date posted latitude    longitude
10/10/1949 20:30    san marcos  tx  us  cylinder    2700    45 minutes  This event took place in early fall around 1949-50. It occurred after a Boy Scout meeting in the Baptist Church. The Baptist Church sit 4/27/2004   29.8830556  -97.9411111
10/10/1949 21:00    lackland afb    tx      light   7200    1-2 hrs 1949 Lackland AFB&#44 TX. Lights racing across the sky & making 90 degree turns on a dime.  12/16/2005  29.38421    -98.581082
10/10/1955 17:00    chester (uk/england)        gb  circle  20  20 seconds  Green/Orange circular disc over Chester&#44 England 1/21/2008   53.2    -2.916667
10/10/1956 21:00    edna    tx  us  circle  20  1/2 hour    My older brother and twin sister were leaving the only Edna theater at about 9 PM&#44...we had our bikes and I took a different route home  1/17/2004   28.9783333  -96.6458333
10/10/1960 20:00    kaneohe hi  us  light   900 15 minutes  AS a Marine 1st Lt. flying an FJ4B fighter/attack aircraft on a solo night exercise&#44 I was at 50&#44000&#39 in a "clean" aircraft (no ordinan  1/22/2004   21.4180556  -157.8036111

I try do group by state
I use

result = df.groupby("state").\
    agg({"state": pd.Series.nunique, "duration (seconds)": np.sum}).\
    rename(columns={"state": "frequency", "duration (seconds)": "whole time"}).\
    reset_index()

But it returns error TypeError: must be str, not float.
I try to convert duration (seconds) but it returns
duration (seconds).
How can I check this problem?

Body:
do something like:

# Group df by df.state, then apply a sum lambda function to df.duration(seconds)
df.groupby('state')['duration (seconds)'].apply(lambda x:x.mean())

Or if you want a rolling sum:

df.groupby('state')['duration (seconds)'].apply(lambda x:x.rolling(center=False,window=2).sum())


来源: stackexchange

问:
Why does my D2XX application not work when forked?
I'm writing a simple application in C, running on a Raspberry Pi, that makes use of the D2XX drivers to communicate with a serial port device. I've followed a number of online tutorials and reference guides to get it working, and have taken steps such as setting up custom udev rules to ensure the drivers can load properly, I followed FTDI's build instructions to install the shared library, I use the -l argument of gcc to link in the library when compiling, and I run my C program with sudo to ensure the drivers have proper access. And that has been a success! The program works as intended.

Now I am trying to convert my simple program into a daemon process that can be controlled with an init.d script (a la service start), and have run into trouble.

For simplicity's sake, here is a watered down version of my C program which does work:

myprog.c:

```<code>#include <stdlib.h>
#include "ftd2xx.h"

int main(int argc, char *argv[])
{
    DWORD i, iNumDevs = 0;
    char *serialNumber = malloc(64);
    FT_STATUS ftStatus = FT_CreateDeviceInfoList(&iNumDevs);
    for (i = 0; i < iNumDevs; i++) {
        ftStatus = FT_ListDevices((PVOID)i, serialNumber, FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER);
        if (FT_OK == ftStatus) {
            break;
        }
    }

    // more code here...

    return EXIT_SUCCESS;
}
</code>```

I compile that with gcc -lftd2xx -o myprog myprog.c and then run it with sudo ./myprog, and take my word for it that it does everything that it's supposed to do. But now that I am trying to re-work this same code into a daemon, I've been following some other online tutorials, and the code above has been transformed into something that looks more like this. Currently, this does not work:

mydaemon.c:

```<code>#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include "ftd2xx.h"

int main(int argc, char *argv[])
{
    pid_t pid, sid;
    pid = fork();
    if (pid < 0) {
        return EXIT_FAILURE;
    }

    if (pid > 0) {
        return EXIT_SUCCESS;
    }

    umask(0);
    openlog("mydaemon", LOG_PID|LOG_CONS, LOG_USER);

    sid = setsid();
    if (sid < 0) {
        syslog(LOG_ERR, "Failed to set session ID on child process");
        return EXIT_FAILURE;
    }

    if ((chdir("/")) < 0) {
        syslog(LOG_ERR, "Failed to change working directory");
        return EXIT_FAILURE;
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    while (1) {

        DWORD i, iNumDevs = 0;
        char *serialNumber = malloc(64);

        syslog(LOG_INFO, "I get to this line");
        FT_STATUS ftStatus = FT_CreateDeviceInfoList(&iNumDevs);
        syslog(LOG_INFO, "I do not get to this line :( ");

        // more code here...

        sleep(10);
    }

    return EXIT_SUCCESS;
}
</code>```

I compile that program in the exact same way: gcc -lftd2xx -o mydaemon mydaemon.c; I run it the same way: sudo ./mydaemon, but unfortunately it does not work. In a separate console window I'm tailing the /var/log/messages file, and I can clearly see it reach my first log message (i.e. "I can get to this line"), but immediately after that it is dead in the water. I never see the second log message, and indeed, at that point the program becomes totally unresponsive. I have to find its process ID and kill it.

In other words, as soon as it tries to make a call to the D2XX drivers in the forked process, it fails. What am I doing wrong? I've already demonstrated with the first example that the code does work, so what is it about running as a daemon that causes it to completely break down? As far as I can tell it doesn't even get a chance to execute the D2XX method in question; it's as if it simply can't find the method in the first place, while running in the forked process.

答:
Probably because it uses libusb... and they appear to do it badly.

See my question here: libusb-1.0 hotplug events stop working in parent after fork(), when child calls libusb_exit()

And the discussion here: https://github.com/libusb/libusb/issues/268

My specific problem was related to hotplug events, but I expect that other things will go wrong for you too.

The reason that this is less obvious in your scenario is because they are probably doing some setup / init when the library loads (how kind of them), rather than when you start to use it.

As pointed out by @duskwuff, there is another answer here: https://stackoverflow.com/a/35186414/149341

I've just done some playing, follow along below:

cd $(mktemp -d)
curl http://www.ftdichip.com/Drivers/D2XX/Linux/libftd2xx-x86_64-1.3.6.tgz | tar -xvz
```

<p>Put this in <code>test.c</code>:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include "ftd2xx.h"

int main(void) {
    int num_devs;

    fprintf(stderr, "in to main()\n");

    FT_STATUS ft_status = FT_CreateDeviceInfoList(&num_devs);
    fprintf(stderr, "FT_CreateDeviceInfoList() returned: %d\n", ft_status);

    fprintf(stderr, "out of main()\n");

    return 0;
}
</code>```

Compile:

gcc test.c -o test -g -I release -L release/build -lftd2xx -ldl -lpthread
```

<p>Now in <code>gdb</code>:</p>

<pre class="lang-none prettyprint-override"><code>[...]
Reading symbols from test...done.
(gdb) b libusb_init
Breakpoint 1 at 0x40cd20
(gdb) start
Temporary breakpoint 2 at 0x401d75: file test.c, line 7.
Starting program: /tmp/tmp.jJpBNywVzB/test
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, 0x000000000040cd20 in libusb_init ()
(gdb) bt
#0  0x000000000040cd20 in libusb_init ()
#1  0x0000000000401f36 in my_init ()
#2  0x000000000041a05d in __libc_csu_init ()
#3  0x00007ffff7614ed5 in __libc_start_main (main=0x401d6d <main>, argc=1, argv=0x7fffffffe228, init=0x41a010 <__libc_csu_init>, fini=<optimised out>, rtld_fini=<optimised out>, stack_end=0x7fffffffe218)
    at libc-start.c:246
#4  0x0000000000401ca9 in _start ()
(gdb)
</code>```

It hit the breakpoint on libusb_init() before even getting to main(), called from their my_init().

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a simple application in C, running on a Raspberry Pi, that makes use of the D2XX drivers to communicate with a serial port device. I've followed a number of online tutorials and reference guides to get it working, and have taken steps such as setting up custom udev rules to ensure the drivers can load properly, I followed FTDI's build instructions to install the shared library, I use the -l argument of gcc to link in the library when compiling, and I run my C program with sudo to ensure the drivers have proper access. And that has been a success! The program works as intended.

Now I am trying to convert my simple program into a daemon process that can be controlled with an init.d script (a la service start), and have run into trouble.

For simplicity's sake, here is a watered down version of my C program which does work:

myprog.c:

#include <stdlib.h>
#include "ftd2xx.h"

int main(int argc, char *argv[])
{
    DWORD i, iNumDevs = 0;
    char *serialNumber = malloc(64);
    FT_STATUS ftStatus = FT_CreateDeviceInfoList(&iNumDevs);
    for (i = 0; i < iNumDevs; i++) {
        ftStatus = FT_ListDevices((PVOID)i, serialNumber, FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER);
        if (FT_OK == ftStatus) {
            break;
        }
    }

    // more code here...

    return EXIT_SUCCESS;
}

I compile that with gcc -lftd2xx -o myprog myprog.c and then run it with sudo ./myprog, and take my word for it that it does everything that it's supposed to do. But now that I am trying to re-work this same code into a daemon, I've been following some other online tutorials, and the code above has been transformed into something that looks more like this. Currently, this does not work:

mydaemon.c:

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include "ftd2xx.h"

int main(int argc, char *argv[])
{
    pid_t pid, sid;
    pid = fork();
    if (pid < 0) {
        return EXIT_FAILURE;
    }

    if (pid > 0) {
        return EXIT_SUCCESS;
    }

    umask(0);
    openlog("mydaemon", LOG_PID|LOG_CONS, LOG_USER);

    sid = setsid();
    if (sid < 0) {
        syslog(LOG_ERR, "Failed to set session ID on child process");
        return EXIT_FAILURE;
    }

    if ((chdir("/")) < 0) {
        syslog(LOG_ERR, "Failed to change working directory");
        return EXIT_FAILURE;
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    while (1) {

        DWORD i, iNumDevs = 0;
        char *serialNumber = malloc(64);

        syslog(LOG_INFO, "I get to this line");
        FT_STATUS ftStatus = FT_CreateDeviceInfoList(&iNumDevs);
        syslog(LOG_INFO, "I do not get to this line :( ");

        // more code here...

        sleep(10);
    }

    return EXIT_SUCCESS;
}

I compile that program in the exact same way: gcc -lftd2xx -o mydaemon mydaemon.c; I run it the same way: sudo ./mydaemon, but unfortunately it does not work. In a separate console window I'm tailing the /var/log/messages file, and I can clearly see it reach my first log message (i.e. "I can get to this line"), but immediately after that it is dead in the water. I never see the second log message, and indeed, at that point the program becomes totally unresponsive. I have to find its process ID and kill it.

In other words, as soon as it tries to make a call to the D2XX drivers in the forked process, it fails. What am I doing wrong? I've already demonstrated with the first example that the code does work, so what is it about running as a daemon that causes it to completely break down? As far as I can tell it doesn't even get a chance to execute the D2XX method in question; it's as if it simply can't find the method in the first place, while running in the forked process.

Body:
Probably because it uses libusb... and they appear to do it badly.

See my question here: libusb-1.0 hotplug events stop working in parent after fork(), when child calls libusb_exit()

And the discussion here: https://github.com/libusb/libusb/issues/268

My specific problem was related to hotplug events, but I expect that other things will go wrong for you too.

The reason that this is less obvious in your scenario is because they are probably doing some setup / init when the library loads (how kind of them), rather than when you start to use it.

As pointed out by @duskwuff, there is another answer here: https://stackoverflow.com/a/35186414/149341

I've just done some playing, follow along below:

cd $(mktemp -d)
curl http://www.ftdichip.com/Drivers/D2XX/Linux/libftd2xx-x86_64-1.3.6.tgz | tar -xvz

Put this in test.c:

#include <stdio.h>
#include "ftd2xx.h"

int main(void) {
    int num_devs;

    fprintf(stderr, "in to main()\n");

    FT_STATUS ft_status = FT_CreateDeviceInfoList(&num_devs);
    fprintf(stderr, "FT_CreateDeviceInfoList() returned: %d\n", ft_status);

    fprintf(stderr, "out of main()\n");

    return 0;
}

Compile:

gcc test.c -o test -g -I release -L release/build -lftd2xx -ldl -lpthread

Now in gdb:

[...]
Reading symbols from test...done.
(gdb) b libusb_init
Breakpoint 1 at 0x40cd20
(gdb) start
Temporary breakpoint 2 at 0x401d75: file test.c, line 7.
Starting program: /tmp/tmp.jJpBNywVzB/test
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, 0x000000000040cd20 in libusb_init ()
(gdb) bt
#0  0x000000000040cd20 in libusb_init ()
#1  0x0000000000401f36 in my_init ()
#2  0x000000000041a05d in __libc_csu_init ()
#3  0x00007ffff7614ed5 in __libc_start_main (main=0x401d6d <main>, argc=1, argv=0x7fffffffe228, init=0x41a010 <__libc_csu_init>, fini=<optimised out>, rtld_fini=<optimised out>, stack_end=0x7fffffffe218)
    at libc-start.c:246
#4  0x0000000000401ca9 in _start ()
(gdb)

It hit the breakpoint on libusb_init() before even getting to main(), called from their my_init().


问:
Wildfly Security Manager : Permission failed for javax.management.MBeanPermission
I have My JBOSS Wildfly10 set up. I am enabling SECMGR flag in standlone.conf.bat file to true for enabling java security manager and as my war is deployed in wildfy 10 ,I am giving following permission set in standalone.xml as below and getting following error:

14:49:56,804 INFO  [stdout] (ServerService Thread Pool -- 58)
  2017-03-28 14:49:56,804 ServerService Thread Pool -- 58 ERROR Could
  not unregister MBeans for org.apac
  he.logging.log4j2:type=2483b420,component=Loggers,name=*,subtype=RingBuffer
  java.security.AccessControlException: WFSM000001: Permission check
  failed (permission "( "javax.management.MBeanPermission" "-#-[-]"
  "queryNames")" in code source
  "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySample.war/WEB-INF/lib/log4j-core-2.5.
  jar )" of "null")

My Standalone.xml configuration is as below so please can anyone help me out here where I am doing wrong ?

```<code> <subsystem xmlns="urn:jboss:domain:security-manager:1.0">
                <deployment-permissions>
                    <minimum-set>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="java.util.PropertyPermission" name="*" actions="read"/>
                        <permission class="java.lang.RuntimePermission" name="createClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="getClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="javax.management.MBeanServerPermission" name="createMBeanServer"/>
                        <permission class="java.lang.reflect.ReflectPermission" name="suppressAccessChecks"/>
                        <permission class="javax.management.MBeanPermission" name="registerMBean"/>
                        <permission class="javax.management.MBeanPermission" name="queryNames"/>
                    </minimum-set>
                </deployment-permissions>
            </subsystem>
</code>```

答:
The queryNames and registerMBean permissions aren't quite right. The name attribute should be the name of the MBean. The registerMBeanand queryNames are actions.

It should probably look something like:

```<code><permission class="javax.management.MBeanPermission" name="*" actions="registerMBean"/>
<permission class="javax.management.MBeanPermission" name="*" actions="queryNames"/>
</code>```

You can specify the specific names or just use * as a wildcard. Have a look at the MBeanPermission for more details.

Body:
I have My JBOSS Wildfly10 set up. I am enabling SECMGR flag in standlone.conf.bat file to true for enabling java security manager and as my war is deployed in wildfy 10 ,I am giving following permission set in standalone.xml as below and getting following error:

14:49:56,804 INFO  [stdout] (ServerService Thread Pool -- 58)
  2017-03-28 14:49:56,804 ServerService Thread Pool -- 58 ERROR Could
  not unregister MBeans for org.apac
  he.logging.log4j2:type=2483b420,component=Loggers,name=*,subtype=RingBuffer
  java.security.AccessControlException: WFSM000001: Permission check
  failed (permission "( "javax.management.MBeanPermission" "-#-[-]"
  "queryNames")" in code source
  "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySample.war/WEB-INF/lib/log4j-core-2.5.
  jar )" of "null")

My Standalone.xml configuration is as below so please can anyone help me out here where I am doing wrong ?

 <subsystem xmlns="urn:jboss:domain:security-manager:1.0">
                <deployment-permissions>
                    <minimum-set>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="java.util.PropertyPermission" name="*" actions="read"/>
                        <permission class="java.lang.RuntimePermission" name="createClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="getClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="javax.management.MBeanServerPermission" name="createMBeanServer"/>
                        <permission class="java.lang.reflect.ReflectPermission" name="suppressAccessChecks"/>
                        <permission class="javax.management.MBeanPermission" name="registerMBean"/>
                        <permission class="javax.management.MBeanPermission" name="queryNames"/>
                    </minimum-set>
                </deployment-permissions>
            </subsystem>

Body:
The queryNames and registerMBean permissions aren't quite right. The name attribute should be the name of the MBean. The registerMBeanand queryNames are actions.

It should probably look something like:

<permission class="javax.management.MBeanPermission" name="*" actions="registerMBean"/>
<permission class="javax.management.MBeanPermission" name="*" actions="queryNames"/>

You can specify the specific names or just use * as a wildcard. Have a look at the MBeanPermission for more details.


问:
How to output a PDF buffer to browser using NodeJS?
So I am using html-pdf to convert my html and here is my code:

```<code>var pdf = require('html-pdf')
var html = 'somehtmlfile.html'

pdf.create(html).toBuffer(function (err, buffer) {
        if (err) {
          console.log(err)
        } else {
          console.log(buffer)
          var pdfBuffer = new Buffer(buffer)
          res.setHeader('Content-disposition', 'inline; filename="test.pdf"');
          res.setHeader('Content-type', 'application/pdf');
          res.send(pdfBuffer)
        }
}
</code>```

I am not getting any PDF file to be downloader nor any output of a pdf file in the browser. The console.log(buffer) is this:

```<code><Buffer 25 50 44 46 2d 31 2e 34 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 69 74 6c 65 20 28 fe ff 29 0a 2f 43 72 65 61 74 6f 72 20 28 fe ff 29 0a 2f 50 72 6f ... >
</code>```

Is there a simple way of doing this? Or am I doing it wrong?

I just want to output the buffer in a pdf form in the browser.

答:
Change to:</p>

```<code>pdf.create(html).toStream(function(err, stream) {
    if (err) {
        console.log(err)
    } else {
        res.set('Content-type', 'application/pdf');
        stream.pipe(res)
    }
});
</code>```

Body:
So I am using html-pdf to convert my html and here is my code:

var pdf = require('html-pdf')
var html = 'somehtmlfile.html'

pdf.create(html).toBuffer(function (err, buffer) {
        if (err) {
          console.log(err)
        } else {
          console.log(buffer)
          var pdfBuffer = new Buffer(buffer)
          res.setHeader('Content-disposition', 'inline; filename="test.pdf"');
          res.setHeader('Content-type', 'application/pdf');
          res.send(pdfBuffer)
        }
}

I am not getting any PDF file to be downloader nor any output of a pdf file in the browser. The console.log(buffer) is this:

<Buffer 25 50 44 46 2d 31 2e 34 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 69 74 6c 65 20 28 fe ff 29 0a 2f 43 72 65 61 74 6f 72 20 28 fe ff 29 0a 2f 50 72 6f ... >

Is there a simple way of doing this? Or am I doing it wrong?

I just want to output the buffer in a pdf form in the browser.

Body:
Change to:

pdf.create(html).toStream(function(err, stream) {
    if (err) {
        console.log(err)
    } else {
        res.set('Content-type', 'application/pdf');
        stream.pipe(res)
    }
});


问:
Scaling down image
Guys how to make this kind of things in creating a website

This is the full picture:

When I scale down the browser it will turn out like this

答:
What you're looking for are @media rules. With @media rules you can not only apply different designs for different output devices (screen, printer, braille, ...), you can also specify different designs for different screen sizes.

Example:

```<code>p {
    font-size: 120%;
}

@media (max-width: 1000px) {
    p {
        font-size: 110%;
    }
}

@media (max-width: 600px) {
    p {
        font-size: 100%;
    }
}
</code>```

Other possible properties are max-height, min-width and min-height.

The rules can be combined:

```<code>@media screen and (max-width: 600px) and (min-height: 800px) {}
</code>```

Media Queries - MDN

Title: Scaling down image

Body:
What you're looking for are @media rules. With @media rules you can not only apply different designs for different output devices (screen, printer, braille, ...), you can also specify different designs for different screen sizes.

Example:

p {
    font-size: 120%;
}

@media (max-width: 1000px) {
    p {
        font-size: 110%;
    }
}

@media (max-width: 600px) {
    p {
        font-size: 100%;
    }
}

Other possible properties are max-height, min-width and min-height.

The rules can be combined:

@media screen and (max-width: 600px) and (min-height: 800px) {}

Media Queries - MDN


问:
How to check if JSONModel class was initialized in Objective-c?
I have a JSONModel class in my objective-c application. I use this class with a singleton then initialize this class with this code:

```<code>MyClass *client = [[MyClass alloc] init];
client = [[MyClass alloc] initWithDictionary:myDictionary error:nil];
</code>```

.h

```<code>@interface MyClass : JSONModel
...
+ (id)sharedInstance;
...
@end
</code>```

.m

```<code>static MyClass *singletonObject = nil;

+ (id) sharedInstance
{
    if (! singletonObject) {

        singletonObject = [[MyClass alloc] init];
    }
    return singletonObject;
}

- (id)init
{
    if (! singletonObject) {
        singletonObject = [super init];
    }
    return singletonObject;
}
</code>```

I'm trying check if I had initialize my class like:

```<code>if([MyClass sharedInstance] == nil){
</code>```

But it isn't working... How can I check if was initialized?

答:
Every time you used alloc/init you was just creating another instance instead of using the share one. If you want to init the share instance in a different way than just init, try something like that:

```<code>MyClass *client = [MyClass reinitSharedInstanceWithDictionary: myDictionary];
</code>```

.h

```<code>@interface MyClass : JSONModel
...
+ (id)sharedInstance;
+ (id)reinitSharedInstanceWithDictionary:(NSDictionary*)dict;
...
@end
</code>```

.m

```<code>static MyClass *singletonObject = nil;

+ (id) sharedInstance
{
    if (! singletonObject) {

        singletonObject = [[MyClass alloc] init];
    }
    return singletonObject;
}

+ (id) reinitSharedInstanceWithDictionary:(NSDictionary*)dict
{
    singletonObject = [[MyClass alloc] initWithDictionary:dict error:nil];
    return singletonObject;
}

- (id)init
{
    if (! singletonObject) {
        singletonObject = [super init];
    }
    return singletonObject;
}
</code>```

Body:
I have a JSONModel class in my objective-c application. I use this class with a singleton then initialize this class with this code:

MyClass *client = [[MyClass alloc] init];
client = [[MyClass alloc] initWithDictionary:myDictionary error:nil];

.h

@interface MyClass : JSONModel
...
+ (id)sharedInstance;
...
@end

.m

static MyClass *singletonObject = nil;

+ (id) sharedInstance
{
    if (! singletonObject) {

        singletonObject = [[MyClass alloc] init];
    }
    return singletonObject;
}

- (id)init
{
    if (! singletonObject) {
        singletonObject = [super init];
    }
    return singletonObject;
}

I'm trying check if I had initialize my class like:

if([MyClass sharedInstance] == nil){

But it isn't working... How can I check if was initialized?

Body:
Every time you used alloc/init you was just creating another instance instead of using the share one. If you want to init the share instance in a different way than just init, try something like that:

MyClass *client = [MyClass reinitSharedInstanceWithDictionary: myDictionary];

.h

@interface MyClass : JSONModel
...
+ (id)sharedInstance;
+ (id)reinitSharedInstanceWithDictionary:(NSDictionary*)dict;
...
@end

.m

static MyClass *singletonObject = nil;

+ (id) sharedInstance
{
    if (! singletonObject) {

        singletonObject = [[MyClass alloc] init];
    }
    return singletonObject;
}

+ (id) reinitSharedInstanceWithDictionary:(NSDictionary*)dict
{
    singletonObject = [[MyClass alloc] initWithDictionary:dict error:nil];
    return singletonObject;
}

- (id)init
{
    if (! singletonObject) {
        singletonObject = [super init];
    }
    return singletonObject;
}


问:
Two each loops that output text
I have a page with 100 questions and right answers. I want to document.write question and right answer in new line. HTML markup is straight forward.

$( ".qtext " ).each(function( index ) {

  $x =  $( this ).text() ;

console.log($x);

// document.write($x);
// document.write("
");

});
$( ".correct " ).each(function( index ) {

  $x =  $( this ).text() ;

console.log($x);

// document.write($x);
// document.write("
");

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div></code>```

Question repeat 100 times, here I just posted markup for one. So I managed to get loop to output all questions and then all correct answers.

Now the output is:

question
question
question
correct answer
correct answer
correct answer

What I would like to achieve is

Question
Correct answer

Question
correct answer

so on.

答:
You don't need two loops, only one. Loop through the questions and lookup the correct answer using your index and jQuery's .eq().

index refers to the current question in the loop (starting with 0), and jQuery's eq() finds the nth occurrence of an element (also starting with 0).

$( ".qtext " ).each(function( index ) {
    var x =  $( this ).text() ;
    var correct = $( ".correct " ).eq(index).text();
    console.log(x + ": " + correct);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div></code>```

As a stylistic choice, I've changed the scope of your $x variable to remain local, and I've removed the $. (Generally, this implies the variable refers to a jQuery object, not a string.)

Title: Two each loops that output text

Body:
I have a page with 100 questions and right answers. I want to document.write question and right answer in new line. HTML markup is straight forward.

$( ".qtext " ).each(function( index ) {

  $x =  $( this ).text() ;

console.log($x);

// document.write($x);
// document.write("
");

});
$( ".correct " ).each(function( index ) {

  $x =  $( this ).text() ;

console.log($x);

// document.write($x);
// document.write("
");

});

title

  <input type="hidden" name="q513920:15_:sequencecheck" value="3">

question

<input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked">correct answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3">answer

title

  <input type="hidden" name="q513920:15_:sequencecheck" value="3">

question

<input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked">correct answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3">answer

title

  <input type="hidden" name="q513920:15_:sequencecheck" value="3">

question

<input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1">answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked">correct answer

<input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3">answer

Question repeat 100 times, here I just posted markup for one. So I managed to get loop to output all questions and then all correct answers.

Now the output is:

question
question
question
correct answer
correct answer
correct answer

What I would like to achieve is

Question
Correct answer

Question
correct answer

so on.

Body:
You don't need two loops, only one. Loop through the questions and lookup the correct answer using your index and jQuery's .eq().

index refers to the current question in the loop (starting with 0), and jQuery's eq() finds the nth occurrence of an element (also starting with 0).

$( ".qtext " ).each(function( index ) {
    var x =  $( this ).text() ;
    var correct = $( ".correct " ).eq(index).text();
    console.log(x + ": " + correct);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>
<div class="formulation">
  <h4 class="accesshide">title</h4>
  <input type="hidden" name="q513920:15_:sequencecheck" value="3">
  <div class="qtext">
    <p><strong>question </strong></p>
  </div>
  <div class="ablock">
    <div class="answer">
      <div class="r0"><input type="radio" name="q513920:15_answer" disabled="disabled" value="0" id="q513920:15_answer0"><label for="q513920:15_answer0">answer</label> </div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="1" id="q513920:15_answer1"><label for="q513920:15_answer1">answer</label> </div>
  <div class="r0 correct"><input type="radio" name="q513920:15_answer" disabled="disabled" value="2" id="q513920:15_answer2" checked="checked"><label for="q513920:15_answer2">correct answer</label> <img src="https://estudijas.rtu.lv/theme/image.php/rtunew/core/1426259605/i/grade_correct" alt="Pareizi" class="questioncorrectnessicon"></div>
  <div class="r1"><input type="radio" name="q513920:15_answer" disabled="disabled" value="3" id="q513920:15_answer3"><label for="q513920:15_answer3">answer</label> </div>
</div>
</div>
</div>

As a stylistic choice, I've changed the scope of your $x variable to remain local, and I've removed the $. (Generally, this implies the variable refers to a jQuery object, not a string.)


问:
Is there a way of making the following shape by CSS coding
Is there a way of making the following shape by CSS coding, without JavaScript?

答:
Css always provide the user the ability to design any shapes, real or unreal, especially by inventing CSS3.

Here I give you a sample that I made with css, you can have a look and get the idea, how to make yours ->

```<code>#moon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  box-shadow: 15px 15px 3px 0px rgb(10, 56, 132);
}
</code>```

However I am suggesting to use SVG as the others mentioned in comment, but if you need it for special case then why not.

! moon (

Body:
Css always provide the user the ability to design any shapes, real or unreal, especially by inventing CSS3.

Here I give you a sample that I made with css, you can have a look and get the idea, how to make yours ->

#moon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  box-shadow: 15px 15px 3px 0px rgb(10, 56, 132);
}

However I am suggesting to use SVG as the others mentioned in comment, but if you need it for special case then why not.

! moon (


问:
Disk out of space on Azure Web app on Linux
I having trouble building and deploying new Docker containers on Azure Web App on Linux.

Error logs is claiming to be out off space, and when looking at disk usage through Kudu I can see that I'm indeed out of space.

/>df -H gives:

```<code>Filesystem Size  Used Avail Use% Mounted on
none        29G   28G     0 100% /
/dev/sda1   29G   28G     0 100% /etc/hosts
</code>```

Have deployed several docker containers in web apps before and removed them aswell but it seems as they are still taking up space.

Creating a new App Service plan without anything deployed gives about 5.7G of free space.

Can't seem to run docker commands from the Kudu terminal so I'm not able to check how many images and can't figure out how to clean up space. Also sodu isn't available.
Does anyone have any ideas about how to free up some space?

答:
Your disk was indeed full of Docker images. I have cleared them off; you should be unblocked.

This is a known issue that we will have a fix for soon. Iterating and deploying new containers is a common scenario, and the goal is that this should be completely abstracted away and you should not have to worry about this.

Body:
I having trouble building and deploying new Docker containers on Azure Web App on Linux.

Error logs is claiming to be out off space, and when looking at disk usage through Kudu I can see that I'm indeed out of space.

/>df -H gives:

Filesystem Size  Used Avail Use% Mounted on
none        29G   28G     0 100% /
/dev/sda1   29G   28G     0 100% /etc/hosts

Have deployed several docker containers in web apps before and removed them aswell but it seems as they are still taking up space.

Creating a new App Service plan without anything deployed gives about 5.7G of free space.

Can't seem to run docker commands from the Kudu terminal so I'm not able to check how many images and can't figure out how to clean up space. Also sodu isn't available.
Does anyone have any ideas about how to free up some space?


问:
What's the best way to manage dates across PHP, MySQL, etc?
My server is in Dallas.  I'm in New York City.. and both PHP and MySQL have configuration variables for setting the timezone.

How do I get them all to work together?  What dates should I store in MySQL?  How do I get PHP to handle changing the date based on the user's preference?

Bear in mind:  I don't think I'm ever having PHP explicitly set the date, it's always using "NOW()" in queries.. however I foresee the need to do this.  How would this be done?

I'm hoping SO's experience can help me out here.

答: I prefer using dates and times in the native form with respect to the environment, that is, Unix timestamps in PHP and DATE/TIME/DATETIME/TIMESTAMP fields in MySQL. I translate both values into another using FROM_UNIXTIME() and UNIX_TIMESTAMP(). I prefer this instead of Unix timestamps, because native dates/times are much easier to read.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5


问:
How to update elegantly the Failure exception of a Try?
I would like to update the Failure exception of a Try to provide a more understandable failure.

I successfully do this by using the following implementation:

```<code>case class NoDataAvailableException() extends Exception

[...]

    Try(...) match {
      case Success(f) => Success(f)
      case Failure(_) => Failure(NoDataAvailableException())
    }
</code>```

But I think this implementation is not really elegant, so my question is:

Is there a way to do this more elegantly ?

答:
You are looking for Try.recoverWith

```<code>Try(...) recoverWith {
    case _ => Failure(NoDataAvailableException())
}
</code>```

Body:
I would like to update the Failure exception of a Try to provide a more understandable failure.

I successfully do this by using the following implementation:

case class NoDataAvailableException() extends Exception

[...]

    Try(...) match {
      case Success(f) => Success(f)
      case Failure(_) => Failure(NoDataAvailableException())
    }

But I think this implementation is not really elegant, so my question is:

Is there a way to do this more elegantly ?

Body:
You are looking for Try.recoverWith

Try(...) recoverWith {
    case _ => Failure(NoDataAvailableException())
}


问:
Docker on MacOSX does not translate file ownership correctly in volumes
I use a simple Linux machine in Docker. Using it with Linux, I clone my dev repository and mount the repo as a volume in Docker. Then, when I enter into the Docker container, the files in the volume belong to user 1000 in group 1000 (all is fine because Docker keeps correctly all file owners). Now I'm trying to do the same in macOS, but in my macOS machine, my uid is 501 and my gid is 20. But when I go to the container, I realize that files inside it have gid and uid 0, the same as root. What can I do to keep file ownership in Docker? </p>

答:
What can I do to keep file ownership in docker?

why do you need to do this?

if you're using a host-mounted volume (via docker run, with -v $PWD:/my/app args for example) in your container, then it doesn't matter what the permissions are in the image itself.

you can edit the files on your mac and the changes will be immediately reflected in the container.

this is all i ever do from my mac, and i never have issues editing files in my volume or having those changes reflected in the container


问:
simple wildcard use missunderstanding
I'm looking at Wildcards and I understood them in a very simple way.
<? extends Type> when I use them just for reading (Returntype) and <? super Type> when I'm using It for writing (Parametertype)

```<code>interface P<T> {
    boolean eval(T e);
}

public class IsZero implements P<Integer> {
    public boolean eval(Integer e) {
        return e.intValue() == 0;
    }
}

public class QQ<T> {
    public void filter(Q<T> q1, Q<T> q2, P<T> p) {
        while (!q2.isEmpty()) {
            T tmp = q2.remove();
            if (p.eval(tmp)) {
                q1.add(tmp);
            }
        }
    }
}
</code>```

So, this code given. My professor wrote following solution:

```<code>/*
Q<? super T> q1 just used as a Parametertype for writing (add)
Q<? extends T> q2 just used as a Returntype for reading (remove)
P<? super T> p just used as Parametertype (eval)
*/
</code>```

I agree with this, but I'll cant figure out why it's P<? super T> since eval returns a boolean? Or am I getting the whole Return/Parameter stuff wrong?

答:
p and q1 need to be Q<? super T> for the same reason... because both need to be able to handle any instance of T and if you are able to handle T or any of its superclasses you are good in that regard. So The reason to set it to Q<? super T> instead of Q<T> is to make your code as general as it can be.

Another way to put it... if X > Y means that X is a superclass/interface of Y or Y itself and p is Q, q1 is Q and q2 is Q<C>

The the constraints above state that A > C and B > C regardless what is the relationship between A and B; if at least one of them is an interface the might not be related at all.

It does not matter whether the method call is going to modify or no the subject.

By the way in most Java standard collections classes add also returns a boolean to indicate if the operation changed the collection which is most of the time ignored. So that is not relevant at all.

Title: simple wildcard use missunderstanding

Body:
I'm looking at Wildcards and I understood them in a very simple way.
<? extends Type> when I use them just for reading (Returntype) and <? super Type> when I'm using It for writing (Parametertype)

interface P<T> {
    boolean eval(T e);
}

public class IsZero implements P<Integer> {
    public boolean eval(Integer e) {
        return e.intValue() == 0;
    }
}

public class QQ<T> {
    public void filter(Q<T> q1, Q<T> q2, P<T> p) {
        while (!q2.isEmpty()) {
            T tmp = q2.remove();
            if (p.eval(tmp)) {
                q1.add(tmp);
            }
        }
    }
}

So, this code given. My professor wrote following solution:

/*
Q<? super T> q1 just used as a Parametertype for writing (add)
Q<? extends T> q2 just used as a Returntype for reading (remove)
P<? super T> p just used as Parametertype (eval)
*/

I agree with this, but I'll cant figure out why it's P<? super T> since eval returns a boolean? Or am I getting the whole Return/Parameter stuff wrong?

Body:
p and q1 need to be Q<? super T> for the same reason... because both need to be able to handle any instance of T and if you are able to handle T or any of its superclasses you are good in that regard. So The reason to set it to Q<? super T> instead of Q<T> is to make your code as general as it can be.

Another way to put it... if X > Y means that X is a superclass/interface of Y or Y itself and p is Q<A>, q1 is Q<B> and q2 is Q<C>

The the constraints above state that A > C and B > C regardless what is the relationship between A and B; if at least one of them is an interface the might not be related at all.

It does not matter whether the method call is going to modify or no the subject.

By the way in most Java standard collections classes add also returns a boolean to indicate if the operation changed the collection which is most of the time ignored. So that is not relevant at all.


问:
Asynchronous Threading that is not coming over correctly using a code converter from C# to VB
I have some C# code that is doing a asynchronous call and pulling back a data set. I do this so the windows desktop UI does not hang/freeze while it is being retrieved. I now need to do the same thing in vb.net but after putting in through an online code converter it gives me the error.

Delegate 'Func(Of String, Boolean, DataSet)' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.

Here is the code before and after conversion.

Before:

```<code>var DataFunc = new Func<string, string, DataSet> (getData);

IAsyncResult Result = DataFunc.BeginInvoke(barCodeResult, orderType, null, null);

DataSet ds = DataFunc.EndInvoke(Result);
</code>```

After:

```<code>Dim DataFunc As var = New Func(Of String, String, DataSet)(getData)

Dim Result As IAsyncResult = DataFunc.BeginInvoke(barCodeResult, orderType, Nothing, Nothing)

Dim ds As DataSet = mtrDataFunc.EndInvoke(Result)
</code>```

Thank you very much in advance for your insights.

答:
There are two fixes to be made:

There's no data type called var. In this case you can replace As var = with As New.

As the error states, the method that you pass to the Func constructor must be prepended by AddressOf to create a delegate.

```<code>Dim DataFunc As New Func(Of String, String, DataSet)(AddressOf getData)
</code>```

Body:
I have some C# code that is doing a asynchronous call and pulling back a data set. I do this so the windows desktop UI does not hang/freeze while it is being retrieved. I now need to do the same thing in vb.net but after putting in through an online code converter it gives me the error.

Delegate 'Func(Of String, Boolean, DataSet)' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.

Here is the code before and after conversion.

Before:

var DataFunc = new Func<string, string, DataSet> (getData);

IAsyncResult Result = DataFunc.BeginInvoke(barCodeResult, orderType, null, null);

DataSet ds = DataFunc.EndInvoke(Result);

After:

Dim DataFunc As var = New Func(Of String, String, DataSet)(getData)

Dim Result As IAsyncResult = DataFunc.BeginInvoke(barCodeResult, orderType, Nothing, Nothing)

Dim ds As DataSet = mtrDataFunc.EndInvoke(Result)

Thank you very much in advance for your insights.

Body:
There are two fixes to be made:

There's no data type called var. In this case you can replace As var = with As New.

As the error states, the method that you pass to the Func constructor must be prepended by AddressOf to create a delegate.

Dim DataFunc As New Func(Of String, String, DataSet)(AddressOf getData)


问:
Cloud Functions for Firebase: retrieve the date of creation of a child from the database
I'm trying to make a function that runs all the children from a certain node to perform something on those that were created exactly x days ago. I have already created a cron on my server to call the function once a day. My problem is that I do not find how to iterate all the children from a node and know their creation date. Is there a function to do this or do I have to put a field with the creation date?</p>

答:
Add a timestamp (creation date) child to each node.

```<code>parent_node
    node_0
      timestamp: "20170328"
    node_1
      timestamp: "20170329"
    node_2
      timestamp: "20170330"
</code>```

Then iterate over all the children of parent_node with .childAdded events or if it's a smaller number of nodes, use .value to load all of the children and iterate in code.

Body:
Add a timestamp (creation date) child to each node.

parent_node
    node_0
      timestamp: "20170328"
    node_1
      timestamp: "20170329"
    node_2
      timestamp: "20170330"

Then iterate over all the children of parent_node with .childAdded events or if it's a smaller number of nodes, use .value to load all of the children and iterate in code.


答: How about using try.recover or try.recoverWith?</p>

Title: How to update elegantly the Failure exception of a Try?


问:
Why is the gets function so dangerous that it should not be used?
When I try to compile C code that uses the gets() function with GCC, I get this warning:

(.text+0x34): warning: the `gets' function is dangerous and should not be used.

I remember this has something to do with stack protection and security, but I'm not sure exactly why.

How can I remove this warning and why is there such a warning about using gets()?

If gets() is so dangerous then why can't we remove it?

答:
You should not use gets since it has no way to stop a buffer overflow. If the user types in more data than can fit in your buffer, you will most likely end up with corruption or worse.

In fact, ISO have actually taken the step of removing gets from the C standard (as of C11, though it was deprecated in C99) which, given how highly they rate backward compatibility, should be an indication of how bad that function was.

The correct thing to do is to use the fgets function with the stdin file handle since you can limit the characters read from the user.

But this also has its problems such as:

extra characters entered by the user will be picked up the next time around.

there's no quick notification that the user entered too much data.

To that end, almost every C coder at some point in their career will write a more useful wrapper around fgets as well. Here's mine:

```<code>#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}
</code>```

with some test code:

```<code>// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}
</code>```

It provides the same protections as fgets in that it prevents buffer overflows but it also notifies the caller as to what happened and clears out the excess characters so that they do not affect your next input operation.

Feel free to use it as you wish, I hereby release it under the "do what you damn well want to" licence :-)

ContentLicense: CC BY-SA 4.0

Body:
You should not use gets since it has no way to stop a buffer overflow. If the user types in more data than can fit in your buffer, you will most likely end up with corruption or worse.

In fact, ISO have actually taken the step of removing gets from the C standard (as of C11, though it was deprecated in C99) which, given how highly they rate backward compatibility, should be an indication of how bad that function was.

The correct thing to do is to use the fgets function with the stdin file handle since you can limit the characters read from the user.

But this also has its problems such as:

extra characters entered by the user will be picked up the next time around.

there's no quick notification that the user entered too much data.

To that end, almost every C coder at some point in their career will write a more useful wrapper around fgets as well. Here's mine:

#include <stdio.h>
#include <string.h>

#define OK       0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
    int ch, extra;

    // Get line with buffer overrun protection.
    if (prmpt != NULL) {
        printf ("%s", prmpt);
        fflush (stdout);
    }
    if (fgets (buff, sz, stdin) == NULL)
        return NO_INPUT;

    // If it was too long, there'll be no newline. In that case, we flush
    // to end of line so that excess doesn't affect the next call.
    if (buff[strlen(buff)-1] != '\n') {
        extra = 0;
        while (((ch = getchar()) != '\n') && (ch != EOF))
            extra = 1;
        return (extra == 1) ? TOO_LONG : OK;
    }

    // Otherwise remove newline and give string back to caller.
    buff[strlen(buff)-1] = '\0';
    return OK;
}

with some test code:

// Test program for getLine().

int main (void) {
    int rc;
    char buff[10];

    rc = getLine ("Enter string> ", buff, sizeof(buff));
    if (rc == NO_INPUT) {
        printf ("No input\n");
        return 1;
    }

    if (rc == TOO_LONG) {
        printf ("Input too long\n");
        return 1;
    }

    printf ("OK [%s]\n", buff);

    return 0;
}

It provides the same protections as fgets in that it prevents buffer overflows but it also notifies the caller as to what happened and clears out the excess characters so that they do not affect your next input operation.

Feel free to use it as you wish, I hereby release it under the "do what you damn well want to" licence :-)


问:
How to Save OpenCV (JavaCV) Trained Faces pictures to database?
Recently I complete a project about face recognition using JavaCV. it save faces to computer directory but i want to save those faces to RDBMs like SQLite, MySQL would be welcome.

Code for save image to computer directory

```<code>private String createPictureFilePathName(File dir) {
    File file = new File(dir.getPath() + "/image-0.png");
    int counter = 1;
    while (file.exists()) {
        file = new File(dir.getPath() + "/image-" + counter + ".png");
        counter++;
    }
    return file.getPath();
}

private static JFileChooser initPictureDirChooser() {
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")).getAbsoluteFile());
        return chooser;
    }
</code>```

Any leads to make this possible to save images to database?

答:
Get the input stream of the file and save it into db as a blob using preparedstatement.

Example Code :

```<code>public boolean saveFile(File file) throws Exception{
    boolean completed = false;
    ConnectionManager conn = new ConnectionManager();
    try {
        PreparedStatement statement = conn.getConnection().prepareStatement("QUERY_TO_INSERT_FILE");
        statement.setBlob(1, file.getInputStream());
        statement.execute();
        conn.commit();
        completed = true;
    } catch (SQLException e) {
        conn.rollbackQuietly();
        e.printStackTrace();
        throw e;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally{
        conn.close();
    }
    return completed;
}
</code>```

Body:
Recently I complete a project about face recognition using JavaCV. it save faces to computer directory but i want to save those faces to RDBMs like SQLite, MySQL would be welcome.

Code for save image to computer directory

private String createPictureFilePathName(File dir) {
    File file = new File(dir.getPath() + "/image-0.png");
    int counter = 1;
    while (file.exists()) {
        file = new File(dir.getPath() + "/image-" + counter + ".png");
        counter++;
    }
    return file.getPath();
}

private static JFileChooser initPictureDirChooser() {
        JFileChooser chooser = new JFileChooser();
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setCurrentDirectory(new File(System.getProperty("user.home")).getAbsoluteFile());
        return chooser;
    }

Any leads to make this possible to save images to database?

Body:
Get the input stream of the file and save it into db as a blob using preparedstatement.

Example Code :

public boolean saveFile(File file) throws Exception{
    boolean completed = false;
    ConnectionManager conn = new ConnectionManager();
    try {
        PreparedStatement statement = conn.getConnection().prepareStatement("QUERY_TO_INSERT_FILE");
        statement.setBlob(1, file.getInputStream());
        statement.execute();
        conn.commit();
        completed = true;
    } catch (SQLException e) {
        conn.rollbackQuietly();
        e.printStackTrace();
        throw e;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally{
        conn.close();
    }
    return completed;
}


问:
Editing a form is not working on react redux
I am new on react. I am working on react application with redux. I have a form (I am using redux-form) by which I can save data or edit data.
my problem is , In edit mode I populate data using componentWillReceiveProps. and populated perfectly, now when I try to clear any field on form its again fill.

```<code>componentWillReceiveProps(nextProps){
    this.props.dispatch(initialize('NewProject', nextProps.project.project[0]));
  }
</code>```

I would be grateful for any help.

答:
Is there a reason you're not dispatching this action somewhere else, like in componentDidMount? I can't say without seeing more code, but it's possible that whenever you edit your form, React again calls componentWillReceiveProps and overwrites whatever you did with the behavior you've given your component.

Per the React documentation:

Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render.

It may be a good idea for you to move your dispatch to a more predictable event if possible, like componentDidMount. Typically, your render method should be capable of handling different cases if a component has multiple possible states. You could also create an edit and save version of your component, and render one or the other based on the props you receive. The best way to "populate" data, as you put it, is to define propTypes for your component, and then use your props to insert that data into elements in the render method.

Body:
I am new on react. I am working on react application with redux. I have a form (I am using redux-form) by which I can save data or edit data.
my problem is , In edit mode I populate data using componentWillReceiveProps. and populated perfectly, now when I try to clear any field on form its again fill.

componentWillReceiveProps(nextProps){
    this.props.dispatch(initialize('NewProject', nextProps.project.project[0]));
  }

I would be grateful for any help.


问:
Command menu contribution adds parameter names to the label
I have the following menuContribution, adding one command to the context menu of a Tree. There are two technical parameters expand and useSelection.

```<code><menuContribution
    locationURI="popup:com.softmodeler.ui.editors.StructureCompareEditor?after=additions">
 <command
       commandId="softmodeler.cmd.refreshViewer"
       id="softmodeler.cmd.refreshViewer"
       style="push">
    <parameter
          name="expand"
          value="1">
    </parameter>
    <parameter
          name="useSelection"
          value="true">
    </parameter>
 </command>
</menuContribution>
</code>```

This shows up in the Tree as follows:

Any idea how to get rid of the parameter names in the label?

I could set the label attribute on the command but then I would have redundant labels (supporting four UI languages, trying to prevent redundancy).

答:
You need to provide a label attribute, otherwise this default label will be used. For localization, use %label in the attribute value and provide plugin.properties files for each language (but I guess you know that already). From what I know that's as good as it gets.

Alternatively, you can create menu contributions programmatically, providing an ExtensionContributionFactory. Within the createContributionItems() method you should be able to create contribution items from the desired commands while re-using the command names as labels. This will, of course, activate your plug-ins as soon as the menu is shown.

Body:
I have the following menuContribution, adding one command to the context menu of a Tree. There are two technical parameters expand and useSelection.

<menuContribution
    locationURI="popup:com.softmodeler.ui.editors.StructureCompareEditor?after=additions">
 <command
       commandId="softmodeler.cmd.refreshViewer"
       id="softmodeler.cmd.refreshViewer"
       style="push">
    <parameter
          name="expand"
          value="1">
    </parameter>
    <parameter
          name="useSelection"
          value="true">
    </parameter>
 </command>
</menuContribution>

This shows up in the Tree as follows:

Any idea how to get rid of the parameter names in the label?

I could set the label attribute on the command but then I would have redundant labels (supporting four UI languages, trying to prevent redundancy).


问:
Get FullPath in WPF treeview?
If I create a WPF TreeView programmatically, for example:

```<code>// TreeView treeView; <- added in the designer
TreeViewItem rootNode = new TreeViewItem();
rootNode.Header = "RootNode"
treeView.Items.Add(rootNode);

TreeViewItem subNode1 = new TreeViewItem();
subNode1.Header = "SubNode1";
rootNode.Items.Add(subNode1);

TreeViewItem subNode2 = new TreeViewItem();
subNode2.Header = "SubNode2";
rootNode.Items.Add(subNode2);
</code>```

However, I would like to get the path to a certain node in the treeview much like the FullPath property in the System.Windows.Forms.TreeNode class. So the path for subNode2 would be RootNode//SubNode2. How do I do this?

Edit: I am not looking for the manual solution, however I am wondering if there is an equivalent accessor like FullPath or if I'm going about using the WPF TreeView class in the wrong way. Eg. I've looked at DisplayMemberPath and SelectedValuePath but they don't seem to provide the result I'm after.

答:
Take a look in my answer here:

Silverlight: Determine parent TreeViewItem?

Determine path then is simple:

```<code>public string GetFullPath(TreeViewItem node)
{
  if (node == null)
    throw new ArgumentNullException();

  var result = Convert.ToString(node.Header);

  for (var i = GetParentItem(node); i != null; i = GetParentItem(i))
    result = i.Header + "\\" + result;

  return result;
}
</code>```

Title: Get FullPath in WPF treeview?

Body:
If I create a WPF TreeView programmatically, for example:

// TreeView treeView; <- added in the designer
TreeViewItem rootNode = new TreeViewItem();
rootNode.Header = "RootNode"
treeView.Items.Add(rootNode);

TreeViewItem subNode1 = new TreeViewItem();
subNode1.Header = "SubNode1";
rootNode.Items.Add(subNode1);

TreeViewItem subNode2 = new TreeViewItem();
subNode2.Header = "SubNode2";
rootNode.Items.Add(subNode2);

However, I would like to get the path to a certain node in the treeview much like the FullPath property in the System.Windows.Forms.TreeNode class. So the path for subNode2 would be RootNode//SubNode2. How do I do this?

Edit: I am not looking for the manual solution, however I am wondering if there is an equivalent accessor like FullPath or if I'm going about using the WPF TreeView class in the wrong way. Eg. I've looked at DisplayMemberPath and SelectedValuePath but they don't seem to provide the result I'm after.

Body:
Take a look in my answer here:

Silverlight: Determine parent TreeViewItem?

Determine path then is simple:

public string GetFullPath(TreeViewItem node)
{
  if (node == null)
    throw new ArgumentNullException();

  var result = Convert.ToString(node.Header);

  for (var i = GetParentItem(node); i != null; i = GetParentItem(i))
    result = i.Header + "\\" + result;

  return result;
}


问:
how to print all text in a specific tag using xpath in python?
I am new to python and xpath. And I am trying to print the text inside the tag 'p' from an html file.
I have this portion of code:

```<code><section>
    <p>Hello <br>nnn</br> <a href="google.com"> dfgdfg </a> World!</p>
</section>
</code>```

I want to print: Hello nnn World! and The code I am using is:

```<code>for el in html.xpath('//section/p'):
    print (el.text)
</code>```

But the printed text is only: Hello
Can any one help me solve this?

答:
use text() inside the xpath directly:

```<code>for el in html.xpath('//section/p//text()'):
    print (el)
</code>```

Check the // says to get all text from all nodes inside the current p.

to print all together, try:

```<code>print(''.join(html.xpath('//section/p//text()')))
</code>```

Body:
I am new to python and xpath. And I am trying to print the text inside the tag 'p' from an html file.
I have this portion of code:

Hello
nnn
  dfgdfg  World!

I want to print: Hello nnn World! and The code I am using is:

for el in html.xpath('//section/p'):
    print (el.text)

But the printed text is only: Hello
Can any one help me solve this?

Body:
use text() inside the xpath directly:

for el in html.xpath('//section/p//text()'):
    print (el)

Check the // says to get all text from all nodes inside the current p.

to print all together, try:

print(''.join(html.xpath('//section/p//text()')))


问:
C++ static member modifiers for subclasses
Consider the following code:

```<code>#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};
</code>```

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.

答:
What you are requesting requires virtual dispatch somewhere, because you don't know the type of the object you are dealing with until runtime.  The purpose of virtual dispatch is to solve exactly the problem you are facing.

The simplest solution is what you have given as number 2: make GetAttrib() virtual, and implement it on each derived class where you introduce a shadowing constattribute_.

Body:
Consider the following code:

#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.


问:
Java - throws not working for a subtype of an exception that is handled
Take this as example:

```<code>public class TestClass {

    public static void test() throws SSLHandshakeException {
        throw new SSLHandshakeException("I'm a SSL Exception");
    }

    public static void main(String[] args) throws SSLHandshakeException {
        try {
            test ();
        } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
    }
}
</code>```

So, I have my test method in which I'm just throwing an SSLHandshakeException which is a subtype of IOException.

The output for this is "I`m handling IO exception".

Why does this happen? I expected that my method will throw the SSLHandshakeException. Is there a rule that catch is more important than throws?

I just want to avoid using

```<code>try {
   test ();
} catch (SSLHandshakeException se) {
   throw se;
} catch (IOException ioe) {
   System.out.println("I`m handling IO exception");
}
</code>```

Because I consider it less readable

答:
SSLHandshakeException is a subclass of javax.net.ssl.SSLException wich is a subclass of java.io.IOException.

So this code :

```<code>public static void main(String[] args) throws SSLHandshakeException {
     try {
          test ();
         } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
}
</code>```

will catch and IOException, and thus print the message "I`m handling IO exception".

Body:
Take this as example:

public class TestClass {

    public static void test() throws SSLHandshakeException {
        throw new SSLHandshakeException("I'm a SSL Exception");
    }

    public static void main(String[] args) throws SSLHandshakeException {
        try {
            test ();
        } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
    }
}

So, I have my test method in which I'm just throwing an SSLHandshakeException which is a subtype of IOException.

The output for this is "I`m handling IO exception".

Why does this happen? I expected that my method will throw the SSLHandshakeException. Is there a rule that catch is more important than throws?

I just want to avoid using

try {
   test ();
} catch (SSLHandshakeException se) {
   throw se;
} catch (IOException ioe) {
   System.out.println("I`m handling IO exception");
}

Because I consider it less readable

Body:
SSLHandshakeException is a subclass of javax.net.ssl.SSLException wich is a subclass of java.io.IOException.

So this code :

public static void main(String[] args) throws SSLHandshakeException {
     try {
          test ();
         } catch (IOException ioe) {
            System.out.println("I`m handling IO exception");
        }
}

will catch and IOException, and thus print the message "I`m handling IO exception".


问:
PhpStorm double quotes in TypeScript auto import
I'm using PhpStorm in my project.
PhpStorm auto import adds import statements with double quotes instead of single quotes.

Can this behaviour be fixed?

答: Try changing Preferences | Editor | Code Style | TypeScript | Punctuation to Use <single> quotes <always>


问:
Which way is the best to run a thread in java?

Possible Duplicate:

  Java: “implements Runnable” vs. “extends Thread”

Should I use Runnable interface or extends from Thread class? Is there any advantage on one and another?

Thanks in advance.

答:
you can only extend 1 class so if you have multiple inheritance you can only use an interface. I never extend Thread class, but implement runnable/callable interface.

I use executors to help me with thread-management.


问:
Getting null values into the table while importing XML Data into a table
I'm trying to import a XML file into a table in SQL Server.

Here is the code I wrote:

```<code>Declare @x xml

Select @x = p
            from OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server     Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)

Declare @hdoc int

exec sp_xml_preparedocument @hdoc output,@x

IF OBJECT_ID('BOOKS') IS NOT NULL
     DROP Table BOOKS

select *
into BOOKS
from openxml(@hdoc,'/catalog/book',2)
with
(   Author nvarchar(150),
    Title nvarchar(150),
    Genre nvarchar(150),
    Price float,
    Publish_Date Date,
    Description nvarchar(200))
exec sp_xml_removedocument @hdoc
select * from BOOKS
</code>```

I ended up getting null values into the table ..

What modifications do I need to do?

Here is the original XML file:

```<code><?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.</description>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty
      thousand leagues beneath the sea.</description>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.</description>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.</description>
   </book>
   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.</description>
   </book>
   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>
</catalog>
</code>```

答:
I would prefer to use the native, built-in XQuery methods rather than the clunky, memory-leaking OPENXML stuff.....

Try this code:

```<code>DECLARE @x XML

SELECT @x = p FROM OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)

SELECT
    Author = xc.value('(author)[1]', 'nvarchar(150)'),
    Title = xc.value('(title)[1]', 'nvarchar(150)'),
    Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
    Price = xc.value('(price)[1]', 'decimal(15,2)'),
    Publish_Date = xc.value('(publish_date)[1]', 'date'),
    Description = xc.value('(genre)[1]', 'nvarchar(200)')
FROM
    @x.nodes('/catalog/book') AS XT(XC)
</code>```

Of course, this only displays the values - but you can easily replace the final SELECT with this:

```<code>INSERT INTO dbo.Books(Author, Title, Genre, Price, Publish_Date, Description)
    SELECT
        Author = xc.value('(author)[1]', 'nvarchar(150)'),
        Title = xc.value('(title)[1]', 'nvarchar(150)'),
        Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
        Price = xc.value('(price)[1]', 'decimal(15,2)'),
        Publish_Date = xc.value('(publish_date)[1]', 'date'),
        Description = xc.value('(genre)[1]', 'nvarchar(200)')
    FROM
        @x.nodes('/catalog/book') AS XT(XC)
</code>```

and insert your data into the table dbo.Books (which has to exist before running this statement).

Also note: I changed the datatype for Price from float (which is notoriously susceptible to rounding errors) and picked decimal(15,2) instead (which has none of those rounding errors)

Body:
I'm trying to import a XML file into a table in SQL Server.

Here is the code I wrote:

Declare @x xml

Select @x = p
            from OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server     Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)

Declare @hdoc int

exec sp_xml_preparedocument @hdoc output,@x

IF OBJECT_ID('BOOKS') IS NOT NULL
     DROP Table BOOKS

select *
into BOOKS
from openxml(@hdoc,'/catalog/book',2)
with
(   Author nvarchar(150),
    Title nvarchar(150),
    Genre nvarchar(150),
    Price float,
    Publish_Date Date,
    Description nvarchar(200))
exec sp_xml_removedocument @hdoc
select * from BOOKS

I ended up getting null values into the table ..

What modifications do I need to do?

Here is the original XML file:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
   <book id="bk104">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk105">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk106">
      <author>Randall, Cynthia</author>
      <title>Lover Birds</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-09-02</publish_date>
      <description>When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.</description>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty
      thousand leagues beneath the sea.</description>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.</description>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.</description>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.</description>
   </book>
   <book id="bk111">
      <author>O'Brien, Tim</author>
      <title>MSXML3: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-01</publish_date>
      <description>The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.</description>
   </book>
   <book id="bk112">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>
</catalog>

Body:
I would prefer to use the native, built-in XQuery methods rather than the clunky, memory-leaking OPENXML stuff.....

Try this code:

DECLARE @x XML

SELECT @x = p FROM OpenRowSet(BULK 'C:\Users\sivat\OneDrive\Projects\SQL Server Projects\Books.xml',SINGLE_BLOB) as BOOKS(p)

SELECT
    Author = xc.value('(author)[1]', 'nvarchar(150)'),
    Title = xc.value('(title)[1]', 'nvarchar(150)'),
    Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
    Price = xc.value('(price)[1]', 'decimal(15,2)'),
    Publish_Date = xc.value('(publish_date)[1]', 'date'),
    Description = xc.value('(genre)[1]', 'nvarchar(200)')
FROM
    @x.nodes('/catalog/book') AS XT(XC)

Of course, this only displays the values - but you can easily replace the final SELECT with this:

INSERT INTO dbo.Books(Author, Title, Genre, Price, Publish_Date, Description)
    SELECT
        Author = xc.value('(author)[1]', 'nvarchar(150)'),
        Title = xc.value('(title)[1]', 'nvarchar(150)'),
        Genre = xc.value('(genre)[1]', 'nvarchar(150)'),
        Price = xc.value('(price)[1]', 'decimal(15,2)'),
        Publish_Date = xc.value('(publish_date)[1]', 'date'),
        Description = xc.value('(genre)[1]', 'nvarchar(200)')
    FROM
        @x.nodes('/catalog/book') AS XT(XC)

and insert your data into the table dbo.Books (which has to exist before running this statement).

Also note: I changed the datatype for Price from float (which is notoriously susceptible to rounding errors) and picked decimal(15,2) instead (which has none of those rounding errors)


问:
Model is running iOS 10.2 (14C92), which may not be supported by this version of Xcode
I am facing this error, i am done with research on that.

I conclude the result, i need one file for device support 10.2(14C92)

Please share that file.

GoTo:

Right click on Xcode 8 or Newer version of your Xcode, select "Show
Package Contents", "Contents", "Developer", "Platforms",
"iPhoneOS.Platform", "Device Support"

Copy the 10.2(14C92) folder (or above for later version).

I need that folder.

Thanks.

答:
If somebody facing similar issue with Xcode 9.1

Open directory:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Create new folder "11.2 (15C107)" (or "10.3 (14E269)" for older versions, depends on what exactly are you missing)

Paste files from provided google drive folder

11.2 (15C107)
(or 10.3 (14E269) if you need older files)

Restart Xcode

For other iOS versions you may check @Sour LeangChhean 's answer

Keep in mind, that some day you will need to upgrade your Xcode anyway :)