答:
your start script is live-server in your package.json.

If you want to work ng serve or ng start then need to generate angular project by angular-cli.This project isn't made by ng-cli that why you can't work.

Therefore, use ng-cli to make a project and it's easily to set up.Though it's not what you ask but I supported.

```<code>npm install -g @angular/cli

ng help
#test for your install completely

#if show the help logs
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve
</code>```

At last, it's impossible to use install angular/cli to start the ng cli , you even didn't got the .angular-cli.json.

Title: ng serve and ng build is not working

Body:
your start script is live-server in your package.json.

If you want to work ng serve or ng start then need to generate angular project by angular-cli.This project isn't made by ng-cli that why you can't work.

Therefore, use ng-cli to make a project and it's easily to set up.Though it's not what you ask but I supported.

npm install -g @angular/cli

ng help
#test for your install completely

#if show the help logs
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve

At last, it's impossible to use install angular/cli to start the ng cli , you even didn't got the .angular-cli.json.


来源: stackexchange

问:
Valid font-family names
I've made some research and I found this article, but it doesn't completely help me. I am interested in what are valid characters that can be used for naming font families. Theoretically, can I use every character for naming, just by putting everything in quotation marks? How is with naming in practice?

Example:

```<code>@font-face {
        font-family: '&This is my font 1234#!&&&';
        src: url('font.eot');
        src: url('font.eot?#iefix') format('embedded-opentype'),
             url('font.woff') format('woff'),
             url('font.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
</code>```

I would also want to know if there are some standards, conventions used for naming font families?

答:
The Mozilla page references the examples from the W3C page.

The only font family names which can be unquoted start with an Alpha [a-zA-Z] and contain ONLY alphanumerics afterwards [A-Za-z0-9].  And possibly also the underscore (_) as well.

As for quoted, it is unspecified.  One could assume anything goes, but who has any idea what browsers will actually accept?  Best to include tests on supported browsers to ensure continual support and catch breakage quickly in development or user bug reports in new or less used browsers.

But it should never be absolutely necessary to use such characters which may increase the odds of breaking somewhere, now or in the future.  Such naming conventions are most definitely a code smell and need reconsideration.

The only restriction on double quoting is that it must quote the entire font family name, i.e. not "One Two" Three.  I've also noticed sporadic breakage if quoting a name that has only Alpha or regex /[a-zA-Z][a-zA-Z0-9_]+/. "One","Two","Three", may or may not work, or partly work as expected, or may be fine.

Although only tangentially related, there is something that remains stupidly broken in many browsers: the monospace font.  According to this article - and my observation in Mozilla Firefox recent v58 nightly - this still remains the case.  The monospace font is shrunk down way too much.  The "fix" seems to be a hack where you specify monospace, monospace as the single font family, NO QUOTES.  Quoting breaks the behavior and defaults to something like inherit or something different from either inherit or monospace.  Quoting either monospace breaks it.  Quoting both breaks it.

ContentLicense: CC BY-SA 3.0

Title: Valid font-family names

Body:
I've made some research and I found this article, but it doesn't completely help me. I am interested in what are valid characters that can be used for naming font families. Theoretically, can I use every character for naming, just by putting everything in quotation marks? How is with naming in practice?

Example:

@font-face {
        font-family: '&This is my font 1234#!&&&';
        src: url('font.eot');
        src: url('font.eot?#iefix') format('embedded-opentype'),
             url('font.woff') format('woff'),
             url('font.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}

I would also want to know if there are some standards, conventions used for naming font families?


问:
ios audio unit how to get decibel directly
How can I get decibel by audio unit directly rather than calculate use formula ？

I found occur error when I use formula to get decibel. So I want to exchange method get decibel.

答: The question is that I find audio unit data become abnormal from the data[512](the data size is 1024). So I don't handle these data and find the audio unit can work abnormality. Because we only use the data to calculate db.  </p>


问:
Need a regular expression to match letter followed by number or capital
I need a regular expression that can replace the lowercase letter n with a newline, but only when it is followed by a digit 0-9 or a capital letter.

For example, the string:

Company Buildingn100 Prospect Way

Should convert into:

Company Building

 100 Prospect Way

I'm trying to sanitize this data in PHP, so the resulting expression needs to be compatible.

答:
```<code>$result = preg_replace("/n(?=[\dA-Z])/", "\n", $subject);
</code>```

will do this if by capital letter you mean ASCII letters.

```<code>$result = preg_replace("/n(?=[\d\p{Lu}])/u", "\n", $subject);
</code>```

if you're using Unicode.

ContentLicense: CC BY-SA 2.5

Body:
$result = preg_replace("/n(?=[\dA-Z])/", "\n", $subject);

will do this if by capital letter you mean ASCII letters.

$result = preg_replace("/n(?=[\d\p{Lu}])/u", "\n", $subject);

if you're using Unicode.


问:
How to remove warnings of nullable in Android?
I'm using annotations library supported by Android.
It is useful for checking NullpointerExceptions.
But, it also annoying if I checked the variable if it is null.

In this case:

```<code>@Nullable
String value;

boolean isValid(String target) {
    return (target != null && target.length() > 0);
}

void test() {
    if (isValid(value)) {
        Log.d("TEST", value);
        // Do something.
    }
}
</code>```

In above code, I already checked if 'value' is null, but still got the warning of "It maybe produce NullPointerException".

Is there some annotations that I checked null-type in this function?

答:
You can use the annotation:

```<code>@SuppressWarnings("ConstantConditions")
</code>```

Body:
I'm using annotations library supported by Android.
It is useful for checking NullpointerExceptions.
But, it also annoying if I checked the variable if it is null.

In this case:

@Nullable
String value;

boolean isValid(String target) {
    return (target != null && target.length() > 0);
}

void test() {
    if (isValid(value)) {
        Log.d("TEST", value);
        // Do something.
    }
}

In above code, I already checked if 'value' is null, but still got the warning of "It maybe produce NullPointerException".

Is there some annotations that I checked null-type in this function?

Body:
You can use the annotation:

@SuppressWarnings("ConstantConditions")


问:
how can I change numbers from 10 radix to 2 in C language in Code :: blocks IDE?
I wrote this code to change the radix of numbers from 10 to 2, but it does not work well. Can you help me?</p>

```<code>#include <stdio.h>
//changing numbers from 10 radix to 2.
int main()
{
int n ,i=0 , s=0 ;
printf("Please Enter a number in ten radix: ");
scanf("%d",&n);
while(n!=0){
    int r=n%2 ;
    s= s+(r*(10^i));
    i++;
    int m=n/2;
    n=m;
}
printf("\nThe number in two radix is %d",s);
return 0;
}
</code>```

答:
```<code>int main()
{
int n, r = 0, i, base2[50];
printf("Please Enter a number in ten radix: ");
scanf("%d",&n);
while(n!=0){
    base2[r]=n%2 ;
    r++;
    n = n/2;
}
printf("\nThe number in two radix is);
for(i = r; i >= 0; i--)
{
   printf("%d", base2[i]);
}
return 0;

}
</code>```

Body:
I wrote this code to change the radix of numbers from 10 to 2, but it does not work well. Can you help me?

#include <stdio.h>
//changing numbers from 10 radix to 2.
int main()
{
int n ,i=0 , s=0 ;
printf("Please Enter a number in ten radix: ");
scanf("%d",&n);
while(n!=0){
    int r=n%2 ;
    s= s+(r*(10^i));
    i++;
    int m=n/2;
    n=m;
}
printf("\nThe number in two radix is %d",s);
return 0;
}


问:
Using the official php docker image and running memcached on start
I have a docker file that I am basing from the php:5.5.36-apache image, for creating image expressly for development. My Dockerfile installs memcached but I am having no luck getting memcached to start on boot. If I ssh into the container and start memcached manually, it starts just fine.

```<code>FROM php:5.5.36-apache

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    default-jdk
RUN apt-get install -y --no-install-recommends autoconf
RUN apt-get install -y --no-install-recommends python python-pip

RUN apt-get update && apt-get install -y libmemcached-dev \
    apt-utils re2c g++ memcached \
    zlib1g zlib1g-dbg zlib1g-dev zlibc mysql-client php5-mysql \
    && pecl install memcached \
    && docker-php-ext-enable memcached\
    && pecl install memcache \
    && docker-php-ext-enable memcache

RUN docker-php-ext-install pdo pdo_mysql

RUN apt-get install -y gettext

RUN pip install hgapi

RUN a2enmod headers \
    && a2enmod rewrite

COPY ./apache2.conf /etc/apache2/apache2.conf

RUN mkdir /var/www/content

EXPOSE 11211

RUN systemctl enable memcached.service
</code>```

The base image is based on debian:jessie

答:
This link worked for me for the same issue with php5, apache2 and memcached in a Dockerfile based on ubuntu:

https://github.com/moby/moby/issues/5137

Install supervisor

```<code>RUN apt-get install -y supervisor
</code>```

and config that in Dockerfile:

```<code>RUN touch  /etc/supervisor/conf.d/supervisord.conf && \
    echo "[supervisord]" >> /etc/supervisor/conf.d/supervisord.conf && \
    echo "nodaemon=true" >> /etc/supervisor/conf.d/supervisord.conf

RUN touch /etc/supervisor/conf.d/memcached.conf && \
    echo "[program:memcache]" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "command=/usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 -DFOREGROUND" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "autostart=true" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "autorestart=true" >> /etc/supervisor/conf.d/memcached.conf

RUN touch /etc/supervisor/conf.d/apache2.conf && \
    echo "[program:apache2]" >> /etc/supervisor/conf.d/apache2.conf && \
    echo 'command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"' >> /etc/supervisor/conf.d/apache2.conf && \
    echo "autostart=true" >> /etc/supervisor/conf.d/apache2.conf && \
    echo "autorestart=true" >> /etc/supervisor/conf.d/apache2.conf

CMD ["/usr/bin/supervisord"]
</code>```

This link also explains how to run multiple services in a container:

https://docs.docker.com/engine/admin/multi-service_container/

Body:
I have a docker file that I am basing from the php:5.5.36-apache image, for creating image expressly for development. My Dockerfile installs memcached but I am having no luck getting memcached to start on boot. If I ssh into the container and start memcached manually, it starts just fine.

FROM php:5.5.36-apache

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
    default-jdk
RUN apt-get install -y --no-install-recommends autoconf
RUN apt-get install -y --no-install-recommends python python-pip

RUN apt-get update && apt-get install -y libmemcached-dev \
    apt-utils re2c g++ memcached \
    zlib1g zlib1g-dbg zlib1g-dev zlibc mysql-client php5-mysql \
    && pecl install memcached \
    && docker-php-ext-enable memcached\
    && pecl install memcache \
    && docker-php-ext-enable memcache

RUN docker-php-ext-install pdo pdo_mysql

RUN apt-get install -y gettext

RUN pip install hgapi

RUN a2enmod headers \
    && a2enmod rewrite

COPY ./apache2.conf /etc/apache2/apache2.conf

RUN mkdir /var/www/content

EXPOSE 11211

RUN systemctl enable memcached.service

The base image is based on debian:jessie

Body:
This link worked for me for the same issue with php5, apache2 and memcached in a Dockerfile based on ubuntu:

https://github.com/moby/moby/issues/5137

Install supervisor

RUN apt-get install -y supervisor

and config that in Dockerfile:

RUN touch  /etc/supervisor/conf.d/supervisord.conf && \
    echo "[supervisord]" >> /etc/supervisor/conf.d/supervisord.conf && \
    echo "nodaemon=true" >> /etc/supervisor/conf.d/supervisord.conf

RUN touch /etc/supervisor/conf.d/memcached.conf && \
    echo "[program:memcache]" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "command=/usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1 -DFOREGROUND" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "autostart=true" >> /etc/supervisor/conf.d/memcached.conf && \
    echo "autorestart=true" >> /etc/supervisor/conf.d/memcached.conf

RUN touch /etc/supervisor/conf.d/apache2.conf && \
    echo "[program:apache2]" >> /etc/supervisor/conf.d/apache2.conf && \
    echo 'command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"' >> /etc/supervisor/conf.d/apache2.conf && \
    echo "autostart=true" >> /etc/supervisor/conf.d/apache2.conf && \
    echo "autorestart=true" >> /etc/supervisor/conf.d/apache2.conf

CMD ["/usr/bin/supervisord"]

This link also explains how to run multiple services in a container:

https://docs.docker.com/engine/admin/multi-service_container/


问:
How do i return date with MMDDYYYY format as a valid date value in sql server?
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

```<code>SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';
</code>```

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

答:
The ONLY safe date literal without delimiters is 'YYYYMMDD'
(style 102)

(in fact it remains "the safest", even a 'YYYY-MM-DD' literal can get messed up by a French language setting. see ref below)

You will NOT get ISDATE() to recognize 'MMDDYYYY' without manipulating the string to insert delimiters.

Bad habits to kick : mis-handling date / range queries

Body:
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

ContentLicense: CC BY-SA 4.0


问:
Time selection is not working in jquery
I have below post code. I have append a html code for table body (tbl_body). There are time selection fields as fe_date and fs_date. but the time selection window does not show.
Please help me.

```<code>$.post("<?php echo base_url('controller/function_name') ?>", {'cid': cid},
    function (data)
    {
        if (data.length > 0) {
            $('#tbl_body').find('tr').remove();
            for (j = 0; j < data.length; j++) {
                $('#att_st_time'+(j+1)).datetimepicker({pickDate: false});
                $('#att_end_time'+(j+1)).datetimepicker({pickDate: false});
                $('#tbl_body').append("<tr><td style='width:14%;text-align: center'>" + (j + 1) + "</td><td style='width:25%;text-align: center'><input class='form-control' id='att_st_time"+(j+1)+"' data-validation='required' data-validation-error-msg-required='Empty is field' type='text' name='fs_date' time-format='H:M:S' value='" + data[j]['ttlc_starttime'] + "'> </td><td style='width:25%;text-align: center'><input class='form-control' id='att_end_time"+(j+1)+"' data-validation='required' data-validation-error-msg-required='Empty is field' type='text' name='fe_date' time-format='H:M:S' value='" + data[j]['ttlc_endtime'] + "'></td></tr>");
            }

        }
    },
    "json"
);
</code>```

答:
Add a class to your input like class="form-control date-picker"

Then try to add this code.

```<code>$(document).on('focus',".date-picker", function(){
    $(this).datetimepicker();
});
</code>```

Title: Time selection is not working in jquery

Body:
I have below post code. I have append a html code for table body (tbl_body). There are time selection fields as fe_date and fs_date. but the time selection window does not show.
Please help me.

$.post("<?php echo base_url('controller/function_name') ?>", {'cid': cid},
    function (data)
    {
        if (data.length > 0) {
            $('#tbl_body').find('tr').remove();
            for (j = 0; j < data.length; j++) {
                $('#att_st_time'+(j+1)).datetimepicker({pickDate: false});
                $('#att_end_time'+(j+1)).datetimepicker({pickDate: false});
                $('#tbl_body').append("
" + (j + 1) + "	<input class='form-control' id='att_st_time"+(j+1)+"' data-validation='required' data-validation-error-msg-required='Empty is field' type='text' name='fs_date' time-format='H:M:S' value='" + data[j]['ttlc_starttime'] + "'> 	<input class='form-control' id='att_end_time"+(j+1)+"' data-validation='required' data-validation-error-msg-required='Empty is field' type='text' name='fe_date' time-format='H:M:S' value='" + data[j]['ttlc_endtime'] + "'>
");
            }

        }
    },
    "json"
);

Body:
Add a class to your input like class="form-control date-picker"

Then try to add this code.

$(document).on('focus',".date-picker", function(){
    $(this).datetimepicker();
});


问:
!important rule in CSS not working in firefox for width style for table
Currently I am adding below style in CSS but the width is not setting properly in firefox but same is working in Chrome, IE, Mircosoft Edge. Can you please let me know how to make it work in Firefox

Please View Demo In Full Window to Produce issue in Firefox

HTML Code

```<code> <tbody>

                    <tr class="features" ng-repeat="list in opMessageLogs">
                        <td style="width : 183px !important;">{{list._id.$id}}</td>
                        <td style="width : 353px !important;">{{list.OPERATION}}</td>
                        <td style="width : 88px !important;">{{list.STATUS}}</td>
                        <td style="width : 153px !important;">{{list.ACCOUNTNUMBER}}</td>
                        <td style="width : 130px !important;">{{list.SENDTIME.sec * 1000 | date:'yyyy-MM-dd HH:mm:ss'}}</td>
                        <td style="width : 130px !important;">{{list.RECEIVETIME.sec * 1000 | date:'yyyy-MM-dd HH:mm:ss'}}</td>
                        <td ng-click="showText(list.REQUEST,$index)" style="width : 113px !important;"><a style="cursor: pointer;">Request</a></td>
                        <td ng-click="showText(list.RESPONSE,$index)" style="width : 128px !important;"><a style="cursor: pointer;">Response</a></td>
                    </tr>

                </tbody>
</code>```

Firefox Issue

As you can see in the below screenshot the width of first element is set as 183px but its reflecting as 194.867px

答:
In some case like mine, firefox just doesn't apply width: 100%; and display: table;, It just not recognized or something else, i don't know. Then i did a little search and find a way to make display table work correctly in firefox by changing the width value width: -moz-max-content;.

Here is the full code

```<code>display: table !important;
position: absolute;
top: 25px;
left: 0;
width: -moz-max-content;
</code>```

Just in case if someone have same trouble like me.

Body:
Currently I am adding below style in CSS but the width is not setting properly in firefox but same is working in Chrome, IE, Mircosoft Edge. Can you please let me know how to make it work in Firefox

Please View Demo In Full Window to Produce issue in Firefox

HTML Code

                        {{list._id.$id}}
                        {{list.OPERATION}}
                        {{list.STATUS}}
                        {{list.ACCOUNTNUMBER}}
                        {{list.SENDTIME.sec * 1000 | date:'yyyy-MM-dd HH:mm:ss'}}
                        {{list.RECEIVETIME.sec * 1000 | date:'yyyy-MM-dd HH:mm:ss'}}
                        Request
                        Response

Firefox Issue

As you can see in the below screenshot the width of first element is set as 183px but its reflecting as 194.867px

Body:
In some case like mine, firefox just doesn't apply width: 100%; and display: table;, It just not recognized or something else, i don't know. Then i did a little search and find a way to make display table work correctly in firefox by changing the width value width: -moz-max-content;.

Here is the full code

display: table !important;
position: absolute;
top: 25px;
left: 0;
width: -moz-max-content;

Just in case if someone have same trouble like me.


问:
How to draw checkbox or tick mark in GitHub Markdown table?
I am able to draw checkbox in Github README.md lists using

```<code>- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)
</code>```

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?

答:
Try adding a -  before the [ ] or [x]. That's an - followed by a blank space  . An unchecked box also need a space   between the brackets.

Below is an example from Github blog.

```<code>### Solar System Exploration, 1950s – 1960s

- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley
</code>```

It appears like below:

Here's how one could do the same in a table:

```<code>| Task           | Time required | Assigned to   | Current Status | Finished |
|----------------|---------------|---------------|----------------|-----------|
| Calendar Cache | > 5 hours  |  | in progress | - [x] ok?
| Object Cache   | > 5 hours  |  | in progress | [x] item1<br/>[ ] item2
| Object Cache   | > 5 hours  |  | in progress | <ul><li>- [x] item1</li><li>- [ ] item2</li></ul>
| Object Cache   | > 5 hours  |  | in progress | <ul><li>[x] item1</li><li>[ ] item2</li></ul>

- [x] works
- [x] works too
</code>```

Here's how it looks:

Body:
I am able to draw checkbox in Github README.md lists using

- [ ] (for unchecked checkbox)
- [x] (for checked checkbox)

But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?

Body:
Try adding a -  before the [ ] or [x]. That's an - followed by a blank space  . An unchecked box also need a space   between the brackets.

Below is an example from Github blog.

### Solar System Exploration, 1950s – 1960s

- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley

It appears like below:

Here's how one could do the same in a table:

| Task           | Time required | Assigned to   | Current Status | Finished |
|----------------|---------------|---------------|----------------|-----------|
| Calendar Cache | > 5 hours  |  | in progress | - [x] ok?
| Object Cache   | > 5 hours  |  | in progress | [x] item1<br/>[ ] item2
| Object Cache   | > 5 hours  |  | in progress | <ul><li>- [x] item1</li><li>- [ ] item2</li></ul>
| Object Cache   | > 5 hours  |  | in progress | <ul><li>[x] item1</li><li>[ ] item2</li></ul>

- [x] works
- [x] works too

Here's how it looks:


问:
Number of variables doesn't match number of parameters in prepared statement in
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode</p>

```<code><?php
$con = mysqli_connect("hostname", "username", "password", "dbname");

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];

$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>
</code>```

答:
You are injecting the params and you are preparing the query at the same time, use ? to tell mysql where to place the data,remove the variables from the sql string

```<code>$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
(?, ?, ?, ?)");
</code>```

Body:
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode

<?php
$con = mysqli_connect("hostname", "username", "password", "dbname");

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];

$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>

Body:
You are injecting the params and you are preparing the query at the same time, use ? to tell mysql where to place the data,remove the variables from the sql string

$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
(?, ?, ?, ?)");


问:
Ionic Native Storage is not persisting after rebuilding app
I am using ionic 3 native storage and store a value like this:

```<code>this.storage.set('myValue', this.value);
</code>```

Then I rebuild the app and try to get that value and it returns null:

```<code>this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
})
</code>```

The result is: My value: null

Not sure why its doing this isn't storage suppose to store it in the database so it should not matter if I rebuild the app or not?

答:
Try this ; </p>

```<code>this.storage.get('myValue').then((data) => {
console.log('My Value : ' + data);
})
</code>```

Body:
I am using ionic 3 native storage and store a value like this:

this.storage.set('myValue', this.value);

Then I rebuild the app and try to get that value and it returns null:

this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
})

The result is: My value: null

Not sure why its doing this isn't storage suppose to store it in the database so it should not matter if I rebuild the app or not?

Body:
Try this ;

this.storage.get('myValue').then((data) => {
console.log('My Value : ' + data);
})


问:
View.LAYER_TYPE_HARDWARE crashes WebView inside a NestedScrollView
I'm trying to create a WebView that collapses the toolbar on scroll and also hides an FAB. I have it all working but as soon as I set the WebView to View.LAYER_TYPE_HARDWARE the thing crashes. The crashes happen on 5.0 and higher. Below 4.4 it seems to work fine. The crash output is:

```<code>01-14 18:10:09.720 2941-3090/com.webviewtesthw D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-14 18:10:09.796 2941-3090/com.webviewtesthw I/OpenGLRenderer: Initialized EGL, version 1.4
01-14 18:10:09.886 2941-3097/com.webviewtesthw E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
01-14 18:10:10.583 2941-2941/com.webviewtesthw W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2941
01-14 18:10:11.553 2941-2941/com.webviewtesthw W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2941
01-14 18:10:11.727 2941-3090/com.webviewtesthw W/OpenGLRenderer: Layer exceeds max. dimensions supported by the GPU (1088x4288, max=4096x4096)
01-14 18:10:11.728 2941-3090/com.webviewtesthw D/OpenGLRenderer: Current memory usage / total memory usage (bytes):
                                                                   TextureCache            57600 / 75497472
                                                                   LayerCache           17825792 / 50331648 (numLayers = 1)
                                                                     Layer size 1088x4096; isTextureLayer()=0; texid=7 fbo=0; refs=1
                                                                   Layers total   17825792 (numLayers = 1)
                                                                   RenderBufferCache           0 /  8388608
                                                                   GradientCache           40960 /  1048576
                                                                   PathCache                   0 / 33554432
                                                                   TessellationCache           0 /  1048576
                                                                   TextDropShadowCache         0 /  6291456
                                                                   PatchCache                  0 /   131072
                                                                   FontRenderer 0 A8     1048576 /  1048576
                                                                   FontRenderer 0 RGBA         0 /        0
                                                                   FontRenderer 0 total  1048576 /  1048576
                                                                 Other:
                                                                   FboCache                    0 /        0
                                                                 Total memory usage:
                                                                   18972928 bytes, 18.09 MB
01-14 18:10:11.729 2941-2941/com.webviewtesthw D/AndroidRuntime: Shutting down VM
01-14 18:10:11.733 2941-2941/com.webviewtesthw E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.webviewtesthw, PID: 2941
                                                                 java.lang.IllegalStateException: Unable to create layer for WebView
                                                                     at android.os.MessageQueue.nativePollOnce(Native Method)
                                                                     at android.os.MessageQueue.next(MessageQueue.java:323)
                                                                     at android.os.Looper.loop(Looper.java:135)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

My code is as follows:

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.webviewtesthw.ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.webviewtesthw.ScrollingActivity"
        tools:showIn="@layout/activity_scrolling">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            >
            <WebView
                android:layout_width="match_parent"
                android:layout_height="match_parent" android:id="@+id/webview"></WebView>
            </FrameLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"/>

</android.support.design.widget.CoordinatorLayout>

package com.webviewtesthw;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        WebView view = (WebView) findViewById(R.id.webview);
        view.setWebViewClient(new WebViewClient());
        WebSettings settings = view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setBuiltInZoomControls(true);

        settings.setAppCacheEnabled(true);
        settings.setAppCachePath(getCacheDir().getAbsolutePath());
        settings.setDatabaseEnabled(true);
        settings.setSupportMultipleWindows(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setSaveFormData(true);
   //     view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        view.loadUrl("http://vimeo.com");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

What am I doing wrong?

Thanks.

EDIT: if I set the height and width of the WebView to a fixed size then it works but as soon as I change it to match parent or wrap content it breaks. Also this issue does not happen if I take out the NestedScrollView

答: If there is scrolling function or "app:layout_behavior="@string/appbar_scrolling_view_behavior" line on the outer layout. Remove the nestedscrollview from the layout. It will not be necessary.</p>

Body:
I'm trying to create a WebView that collapses the toolbar on scroll and also hides an FAB. I have it all working but as soon as I set the WebView to View.LAYER_TYPE_HARDWARE the thing crashes. The crashes happen on 5.0 and higher. Below 4.4 it seems to work fine. The crash output is:

01-14 18:10:09.720 2941-3090/com.webviewtesthw D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-14 18:10:09.796 2941-3090/com.webviewtesthw I/OpenGLRenderer: Initialized EGL, version 1.4
01-14 18:10:09.886 2941-3097/com.webviewtesthw E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
01-14 18:10:10.583 2941-2941/com.webviewtesthw W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2941
01-14 18:10:11.553 2941-2941/com.webviewtesthw W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 2941
01-14 18:10:11.727 2941-3090/com.webviewtesthw W/OpenGLRenderer: Layer exceeds max. dimensions supported by the GPU (1088x4288, max=4096x4096)
01-14 18:10:11.728 2941-3090/com.webviewtesthw D/OpenGLRenderer: Current memory usage / total memory usage (bytes):
                                                                   TextureCache            57600 / 75497472
                                                                   LayerCache           17825792 / 50331648 (numLayers = 1)
                                                                     Layer size 1088x4096; isTextureLayer()=0; texid=7 fbo=0; refs=1
                                                                   Layers total   17825792 (numLayers = 1)
                                                                   RenderBufferCache           0 /  8388608
                                                                   GradientCache           40960 /  1048576
                                                                   PathCache                   0 / 33554432
                                                                   TessellationCache           0 /  1048576
                                                                   TextDropShadowCache         0 /  6291456
                                                                   PatchCache                  0 /   131072
                                                                   FontRenderer 0 A8     1048576 /  1048576
                                                                   FontRenderer 0 RGBA         0 /        0
                                                                   FontRenderer 0 total  1048576 /  1048576
                                                                 Other:
                                                                   FboCache                    0 /        0
                                                                 Total memory usage:
                                                                   18972928 bytes, 18.09 MB
01-14 18:10:11.729 2941-2941/com.webviewtesthw D/AndroidRuntime: Shutting down VM
01-14 18:10:11.733 2941-2941/com.webviewtesthw E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.webviewtesthw, PID: 2941
                                                                 java.lang.IllegalStateException: Unable to create layer for WebView
                                                                     at android.os.MessageQueue.nativePollOnce(Native Method)
                                                                     at android.os.MessageQueue.next(MessageQueue.java:323)
                                                                     at android.os.Looper.loop(Looper.java:135)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

My code is as follows:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.webviewtesthw.ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.widget.NestedScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.webviewtesthw.ScrollingActivity"
        tools:showIn="@layout/activity_scrolling">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            >
            <WebView
                android:layout_width="match_parent"
                android:layout_height="match_parent" android:id="@+id/webview"></WebView>
            </FrameLayout>

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"/>

</android.support.design.widget.CoordinatorLayout>

package com.webviewtesthw;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        WebView view = (WebView) findViewById(R.id.webview);
        view.setWebViewClient(new WebViewClient());
        WebSettings settings = view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setBuiltInZoomControls(true);

        settings.setAppCacheEnabled(true);
        settings.setAppCachePath(getCacheDir().getAbsolutePath());
        settings.setDatabaseEnabled(true);
        settings.setSupportMultipleWindows(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccess(true);
        settings.setSaveFormData(true);
   //     view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        view.loadUrl("http://vimeo.com");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

What am I doing wrong?

Thanks.

EDIT: if I set the height and width of the WebView to a fixed size then it works but as soon as I change it to match parent or wrap content it breaks. Also this issue does not happen if I take out the NestedScrollView


问:
Upload the file, view and rewriting the same file from that same page in php
I have a form that using to upload many datas and files. If a user uploaded a file, the file have to view from the same page while clicking view button and if any changes, have to update the same file. I have number of file uploads in one form.

My Form is...

```<code><fieldset id="pan-step4-new" class="form-style">
  <h2 class="fs-title">Please Upload Documents</h2>
  <div class="black-underline" ></div>

  <div class="col-md-4"><p>Your Passport Copy</p> </div>
  <div class="col-md-4 col-xs-12 pan_new_pass_front_label">
      <label class="btn btn-default btn-file btn-block" >
      <h5 id="pan_new_pass_front_label">Attach Passport Front Page</h5>
       <input type="file" name="pan_new_pass_front"     id="pan_new_pass_front" accept="image/*" />
     </label>
    </div>
  <div class="col-md-4 col-xs-12  input-group">
    <label class="btn btn-default btn-file btn-block">
    <h5 id="pan_new_pass_back_label">Attach Passport Address Page</h5>
    <input type="file" name="pan_new_pass_back" id="pan_new_pass_back" accept="image/*" />
      </label>
      </div>

  <div class="col-md-4"><p>Your Visa Page</p></div>
  <div class="col-md-offset-4 col-md-4 col-xs-12 input-group">
  <label class="btn btn-default btn-file btn-block">
  <h5 id="pan_new_visa_label">Attach Visa Page</h5>
  <input type="file" name="pan_new_visa" id="pan_new_visa" accept="image/*" />
   </label>
   </div>
  <div class="col-md-4 "><p>Your Residency Proof in UAE</p></div>
  <div class="col-md-offset-4 col-md-4 col-xs-12 input-group">
  <label class="btn btn-default btn-file btn-block">
  <h5 id="pan_new_proof_uae_label">Attach Proof Page</h5>
  <input type="file" name="pan_new_proof_uae" id="pan_new_proof_uae" accept="image/*" />
   </label>
   </div>
   <div class="col-md-4"><p>Your Photo</p></div>
    <div class="col-md-offset-4 col-md-4 col-xs-12 input-group">
    <label class="btn btn-default btn-file btn-block">
   <h5 id="pan_new_photo_label">Attach Passport Size Photo</h5>
   <input type="file" name="pan_new_photo" id="pan_new_photo" accept="image/*" />
    </label>
                      </div>
  <input type="button" class="btn btn-prev btn-style previous-button-style" value="prev"  id="pan-step4-new-prev" />
   <input type="submit" class="btn btn-next btn-style previous-button-style" name="pan_new_submit" value="submit" id="pan_new_submit"/>
   </fieldset>
</code>```

答:
Use DropzoneJS.
It will preview your file before upload, and you can even remove the file before upload. </p>

Body:
I have a form that using to upload many datas and files. If a user uploaded a file, the file have to view from the same page while clicking view button and if any changes, have to update the same file. I have number of file uploads in one form.

My Form is...

<fieldset id="pan-step4-new" class="form-style">

Please Upload Documents

Your Passport Copy

Attach Passport Front Page

       <input type="file" name="pan_new_pass_front"     id="pan_new_pass_front" accept="image/*" />

Attach Passport Address Page

    <input type="file" name="pan_new_pass_back" id="pan_new_pass_back" accept="image/*" />

Your Visa Page

Attach Visa Page

  <input type="file" name="pan_new_visa" id="pan_new_visa" accept="image/*" />

Your Residency Proof in UAE

Attach Proof Page

  <input type="file" name="pan_new_proof_uae" id="pan_new_proof_uae" accept="image/*" />

Your Photo

Attach Passport Size Photo

   <input type="file" name="pan_new_photo" id="pan_new_photo" accept="image/*" />

  <input type="button" class="btn btn-prev btn-style previous-button-style" value="prev"  id="pan-step4-new-prev" />
   <input type="submit" class="btn btn-next btn-style previous-button-style" name="pan_new_submit" value="submit" id="pan_new_submit"/>
   </fieldset>


问:
Is there a design pattern to collect and aggregate information and report it at the end?
I'm working on a desktop software with user interface. The software lets the user do certain things. Now, this software will need to keep track of certain things the user has done over time. Finally, when the time is right, this software should post the information it has accumulated over time. I'm wondering what design pattern would fit in this scenario.

I used to use a static class and a static string field to accumulate the bits and pieces of information and finally send that string to report on the state. But I'm in a similar situation again and I think I could do better than make calls to this static field throughout the code.

Is there a design pattern around this?

答:
Well if you don't want to couple your classes, a Singleton is the way to go. Depending on the programming language you are working with, you'll have to implement this pattern differently

As I understand it, you want to share Information between different tiers of your application. A Singleton as you described above, would be just fine.

Any different solution would increase the coupling of your classes a lot. Therefore the Singleton pattern is the way to go.

edit: Since you got me thinking, why I'm getting downvotes, I'll change my answer to: use Dependency Injection instead. Read this, and you'll understand why: http://sites.google.com/site/steveyegge2/singleton-considered-stupid (at least I did) and also get a hint on how to do it.

Hey SO, you just brought me off the dark path of Singleton misuse just at the right time.


问:
VLOOKUP a cell that does not contain specific text
Currently using this formula;

```<code>=ARRAYFORMULA(VLOOKUP("*"&$W$2&"*",H1:T1000,{2,3,5,8,11},false))
</code>```

which works fine when I put something into cell W2.

However, what if I want to return all rows that do not contain that value from W2, is there a way?

答:
Use QUERY instead:

```<code>=QUERY(H1:T1000,"Select I, J, L Where not H contains '"&W2&"'")
</code>```

Or

```<code>…not H matches '.*"&W2&".*'…
</code>```

Body:
Currently using this formula;

=ARRAYFORMULA(VLOOKUP("*"&$W$2&"*",H1:T1000,{2,3,5,8,11},false))

which works fine when I put something into cell W2.

However, what if I want to return all rows that do not contain that value from W2, is there a way?

Body:
Use QUERY instead:

=QUERY(H1:T1000,"Select I, J, L Where not H contains '"&W2&"'")

Or

…not H matches '.*"&W2&".*'…


问:
C++ Virtual function called normally or virtually?
Let's say a virtual function is called on a derived class object (on the object normally or through pointer/reference) that overrides that function but none of its derived classes override it. Is it called "virtually" through v-pointer or as a normal function so all optimizations / inlining apply to it? Does the standard say anything about this?</p>

```<code>class CBase{

public:
    virtual void doSomething() = 0;

};

class CDerived1 : public CBase{

public:
    void doSomething() override { /* do stuff */};

};

class CDerived2 : public CDerived1{

};

//...

CDerived1   derived1;
CDerived1*  p_derived1 = &derived1;

p_derived1->doSomething();
</code>```

答:
Does the standard say anything about this?

No. Whether the call uses the dynamic dispatch mechanism or not is not observable behavior. And the standard only concerns itself with observable behavior.

How much compilers "devirtualize" virtual calls is ultimately implementation defined. If you just have T t; and you do t.whatever(), then you shouldn't use a compiler that cannot devirtualize that.

Inlining affects devirtualization as well. Given the T t declarations, if you pass a function a reference to this object, and it takes a T& parameter, calls into it can be devirtualized if that function gets inlined.

But if its a non-inlined instance of that function (say, a pointer to the function, perhaps through std::function or whatever), then devirtualization is much harder. See, the compiler doesn't see the whole program, so it cannot see if you have some class somewhere that inherits from T and overrides that method.

Only the linker, through whole program optimization, could possibly see all class definitions that inherit from it. And even then... maybe not. Because it is still technically possible for DLLs/SOs to inherit from classes. And the non-inlined function ought to be able to take those T&s and call their overridden methods.

So once you leave a chain of inlining where the object's dynamic type and virtual calls into it are both visible to the compiler, devirtualization becomes far more difficult if not impossible.

Body:
Let's say a virtual function is called on a derived class object (on the object normally or through pointer/reference) that overrides that function but none of its derived classes override it. Is it called "virtually" through v-pointer or as a normal function so all optimizations / inlining apply to it? Does the standard say anything about this?

class CBase{

public:
    virtual void doSomething() = 0;

};

class CDerived1 : public CBase{

public:
    void doSomething() override { /* do stuff */};

};

class CDerived2 : public CDerived1{

};

//...

CDerived1   derived1;
CDerived1*  p_derived1 = &derived1;

p_derived1->doSomething();


问:
yii2 - How to get checked checkbox values from gridview to controller
I need to get checked checkbox value from my view to controller when button is press.

Gridview :

```<code><div class="installment-ready">
<!-- <h1><?= Html::encode($this->title) ?></h1> -->
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    //'filterModel' => $searchModel,
    'columns' => [
    [
    'class' => 'yii\grid\SerialColumn',
    'contentOptions'=>[ 'style'=>'width: 60px'],
    ],
//Checkbox
[
    'class' => 'yii\grid\CheckboxColumn',
    'contentOptions'=>[ 'style'=>'width: 50px'],
    'name' => 'checked',
    'checkboxOptions'=> function($model, $key, $index, $column) {
     return ["value" => $model->ACCOUNT_ID];
    }
],
</code>```

Button to process selected checkbox:

```<code><?= Html::a('Submit', ['#'], ['class' => 'btn btn-success pull-right']) ?>
</code>```

答:
I found a solution. I'm using ajax to post selected checkbox to my controller.

Script that I use in my view

```<code><script type="text/javascript">
  // action for all selected rows
  function submit(){
    var dialog = confirm("Are you sure to submit the installment?");
    if (dialog == true) {
        var keys = $('#grid').yiiGridView('getSelectedRows');
        // console.log(keys);
        var ajax = new XMLHttpRequest();
        $.ajax({
            type: "POST",
            url: 'index.php?r=installment/submit', // Your controller action
            data: {keylist: keys},
            success: function(result){
              console.log(result);
            }
          });
    }
  }
</script>
<!-- Submit button -->
<button type="button" onclick="submit()" class="btn btn-success pull-right">Submit</button
</code>```

And you can use usual Yii::$app->request->post() in controller to get your data.

Body:
I need to get checked checkbox value from my view to controller when button is press.

Gridview :

<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    //'filterModel' => $searchModel,
    'columns' => [
    [
    'class' => 'yii\grid\SerialColumn',
    'contentOptions'=>[ 'style'=>'width: 60px'],
    ],
//Checkbox
[
    'class' => 'yii\grid\CheckboxColumn',
    'contentOptions'=>[ 'style'=>'width: 50px'],
    'name' => 'checked',
    'checkboxOptions'=> function($model, $key, $index, $column) {
     return ["value" => $model->ACCOUNT_ID];
    }
],

Button to process selected checkbox:

<?= Html::a('Submit', ['#'], ['class' => 'btn btn-success pull-right']) ?>

Body:
I found a solution. I'm using ajax to post selected checkbox to my controller.

Script that I use in my view

<script type="text/javascript">
  // action for all selected rows
  function submit(){
    var dialog = confirm("Are you sure to submit the installment?");
    if (dialog == true) {
        var keys = $('#grid').yiiGridView('getSelectedRows');
        // console.log(keys);
        var ajax = new XMLHttpRequest();
        $.ajax({
            type: "POST",
            url: 'index.php?r=installment/submit', // Your controller action
            data: {keylist: keys},
            success: function(result){
              console.log(result);
            }
          });
    }
  }
</script>
<!-- Submit button -->
<button type="button" onclick="submit()" class="btn btn-success pull-right">Submit</button

And you can use usual Yii::$app->request->post() in controller to get your data.


问:
getCompoundDrawables returns null inside of onCreateView, but not later
I want to run the code below in order to tint a button's drawable on pre-lollipop devices, however button.getCompoundDrawables() is returning null for all 4 elements of the array when called inside of the Fragment's onCreateView method.

If I inspect the same Drawable[] array at a later point in time - say upon a button click event -  I can see the drawable value has been correctly assigned (3 are null, 1 is valid).

Is there some button life cycle or fragment life cycle that I can rely on the compound drawables array to have been already properly initialized?

```<code>Drawable[] drawables = button.getCompoundDrawables();
        if( drawables[2] != null){
            Drawable wrapDrawable = DrawableCompat.wrap(drawables[2]);
            DrawableCompat.setTint(wrapDrawable, color);
            button.invalidate();
        }
</code>```

Here's the lib versions I'm using:

```<code>compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:support-v4:24.1.1'
compile 'com.android.support:design:24.2.0'
</code>```

At request, I'm including also some xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
 [...]  >

<Button
    android:id="@+id/bt1"
    android:background="@android:color/transparent"
    android:textAppearance="@style/ConfigButtonTheme"
    android:text="Sincronizar Música"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:drawableEnd="@drawable/ic_chevron_right_white_24dp"
    android:textAlignment="textStart"
    android:layout_width="match_parent"
    android:layout_height="60dp" />

</LinearLayout>
</code>```

答:
for android:drawableRight, you should use getCompoundDrawables(), where as for android:drawableEnd, you should use getCompoundDrawablesRelative().

getCompoundDrawablesRelative()

Body:
I want to run the code below in order to tint a button's drawable on pre-lollipop devices, however button.getCompoundDrawables() is returning null for all 4 elements of the array when called inside of the Fragment's onCreateView method.

If I inspect the same Drawable[] array at a later point in time - say upon a button click event -  I can see the drawable value has been correctly assigned (3 are null, 1 is valid).

Is there some button life cycle or fragment life cycle that I can rely on the compound drawables array to have been already properly initialized?

Drawable[] drawables = button.getCompoundDrawables();
        if( drawables[2] != null){
            Drawable wrapDrawable = DrawableCompat.wrap(drawables[2]);
            DrawableCompat.setTint(wrapDrawable, color);
            button.invalidate();
        }

Here's the lib versions I'm using:

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:support-v4:24.1.1'
compile 'com.android.support:design:24.2.0'

At request, I'm including also some xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
 [...]  >

<Button
    android:id="@+id/bt1"
    android:background="@android:color/transparent"
    android:textAppearance="@style/ConfigButtonTheme"
    android:text="Sincronizar Música"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:drawableEnd="@drawable/ic_chevron_right_white_24dp"
    android:textAlignment="textStart"
    android:layout_width="match_parent"
    android:layout_height="60dp" />

</LinearLayout>


问:
How to query a pandas DataFrame using an array of tuples ?
I have a pandas DataFrame with the following structure:

And I have an array of tuples

arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

Each tuple in the array represent the row and column index of the above dataframe respectively.

I can find all the values in the data frame for the indices in arr_tuples using for loop like this:

```<code>value_array = []
for item in arr_tuples:
    row = item[0]
    col = item[1]
    value = df.iloc[row,col] # I also tried df.get_value here with similar result
    value_array.append(value)
</code>```

But this seems to be a very slow method. If there are a lot of tuples in my arr_tuples, this will take a long time.

Is there a better and faster way to achieve the same ?
Is there any way in pandas where I can use a list/array of tuples (containing row and column index) to get values in a dataframe ?

答:
It'll be faster if you make arr_tuples into a Series:

```<code>import pandas as pd
data = {0:[1,4,11,14],1:[2,5,12,5],2:[3,6,13,6],3:[4,7,14,7]}
df = pd.DataFrame(data)
arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

s = pd.Series(arr_tuples)
value_array = s.apply(lambda (x,y): df.iloc[x,y])

value_array
0     4
1     5
2     7
3    12
dtype: int64
</code>```

Body:
I have a pandas DataFrame with the following structure:

And I have an array of tuples

arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

Each tuple in the array represent the row and column index of the above dataframe respectively.

I can find all the values in the data frame for the indices in arr_tuples using for loop like this:

value_array = []
for item in arr_tuples:
    row = item[0]
    col = item[1]
    value = df.iloc[row,col] # I also tried df.get_value here with similar result
    value_array.append(value)

But this seems to be a very slow method. If there are a lot of tuples in my arr_tuples, this will take a long time.

Is there a better and faster way to achieve the same ?
Is there any way in pandas where I can use a list/array of tuples (containing row and column index) to get values in a dataframe ?

Body:
It'll be faster if you make arr_tuples into a Series:

import pandas as pd
data = {0:[1,4,11,14],1:[2,5,12,5],2:[3,6,13,6],3:[4,7,14,7]}
df = pd.DataFrame(data)
arr_tuples = [(0,3),(1,1),(1,3),(2,1)]

s = pd.Series(arr_tuples)
value_array = s.apply(lambda (x,y): df.iloc[x,y])

value_array
0     4
1     5
2     7
3    12
dtype: int64


问:
Creating a sequential step in a jenkins declarative pipeline preceding a parallel stage
I would like to setup parallel stages as described in the image

In this instance, the setup is pretty heavy so has to be done once before the parallel group starts of G1, G2 and G3. At the same time, the stage : Initial Checks has 2 items that I would like to run in parallel.

Is this possible in the Declarative Pipeline or do I have to resort to a script?

I couldnt see in the documentation the ability for this to work

```<code>Stages {
    stage ('P1') {
    }
    stage ('P2 Setup') {}
    stage ('P2') {
    //Here it can contain either Steps or Parallel. I can only do
       parallel {
          stage ('g1') {} //Parallel tests
          stage ('g2') {}
          stage ('g3') {}
       }
    }
    stage ('P2 Cleanup') {}
}
</code>```

Have you encountered similar situations and what have your solutions been like?

Ofcourse 1 solution is to make Setup and Cleanup as part of every group, but like I said, its pretty intensive and I would only take it on if what the diagram indicates isn't possible.

Solution 2

```<code> stage ('p2') {
    script {
      //Some scripting here to get the result?

    }
 }
</code>```

Pipeline

答:
I think you are looking for this</p>

```<code>  node {
        stage("P1"){}
        stage("p2") {}
        stage("p3") {
          parallel (
                "firstTask" : {

                },
                "secondTask" : {

               }
            )
        }

    }
</code>```

Body:
I would like to setup parallel stages as described in the image

In this instance, the setup is pretty heavy so has to be done once before the parallel group starts of G1, G2 and G3. At the same time, the stage : Initial Checks has 2 items that I would like to run in parallel.

Is this possible in the Declarative Pipeline or do I have to resort to a script?

I couldnt see in the documentation the ability for this to work

Stages {
    stage ('P1') {
    }
    stage ('P2 Setup') {}
    stage ('P2') {
    //Here it can contain either Steps or Parallel. I can only do
       parallel {
          stage ('g1') {} //Parallel tests
          stage ('g2') {}
          stage ('g3') {}
       }
    }
    stage ('P2 Cleanup') {}
}

Have you encountered similar situations and what have your solutions been like?

Ofcourse 1 solution is to make Setup and Cleanup as part of every group, but like I said, its pretty intensive and I would only take it on if what the diagram indicates isn't possible.

Solution 2

 stage ('p2') {
    script {
      //Some scripting here to get the result?

    }
 }

Pipeline

Body:
I think you are looking for this

  node {
        stage("P1"){}
        stage("p2") {}
        stage("p3") {
          parallel (
                "firstTask" : {

                },
                "secondTask" : {

               }
            )
        }

    }


问:
Python SMTP lib required SMTPUTF8 for non-ASCI characters in from adress display name
I'm using python's smtplip for sending emials. Everything id working fine except when I'm use  non-ASCI character in message from address.

I'm using python 3.5.

This works fine even with non-ASCI To and Subject:

```<code>import smtplib

from email.message import EmailMessage
from email.headerregistry import Addressmsg = EmailMessage()

msg['Subject'] = "Subject with non-asci chars like á"
msg['From'] = Address("Foo Bar", "foo.bar", "example.cz")
msg['To'] = (Address("Fóó Bár", "foo.bar", "example.cz"),
</code>```

Bud when I'm try use non-ASCI in from like this:

```<code>msg['Subject'] = "Subject with non-asci chars like á"
msg['From'] = Address("Fóó Bár", "foo.bar", "example.cz")
msg['To'] = (Address("Fóó Bár", "foo.bar", "example.cz"),
</code>```

Both from above sending with:

```<code>with smtplib.SMTP('localhost') as s:
        s.send_message(msg)
</code>```

I'm get this exception:

```<code>smtplib.SMTPNotSupportedError: One or more source or delivery addresses require internationalized email support, but the server does not advertise the required SMTPUTF8 capability`
</code>```

I know that caused by our's smtp server that does not support SMTPUTF8, but only from non-ASCI display name it shouldn't be necesery.

答:
I tricked the send_message library by first sending a 'ehlo()', then modified the features manually:

```<code>s = smtplib.SMTP(server)
s.ehlo()
s.esmtp_features["smtputf8"] = ""
s.send_message(msg)
</code>```

I also changed the message policy as I had other issues:

```<code>msg = MIMEMultipart(policy=SMTPUTF8)
</code>```

Hope this helps! (This will work only if your server is UTF8 compatible but does not answer it with ehlo)

Body:
I'm using python's smtplip for sending emials. Everything id working fine except when I'm use  non-ASCI character in message from address.

I'm using python 3.5.

This works fine even with non-ASCI To and Subject:

import smtplib

from email.message import EmailMessage
from email.headerregistry import Addressmsg = EmailMessage()

msg['Subject'] = "Subject with non-asci chars like á"
msg['From'] = Address("Foo Bar", "foo.bar", "example.cz")
msg['To'] = (Address("Fóó Bár", "foo.bar", "example.cz"),

Bud when I'm try use non-ASCI in from like this:

msg['Subject'] = "Subject with non-asci chars like á"
msg['From'] = Address("Fóó Bár", "foo.bar", "example.cz")
msg['To'] = (Address("Fóó Bár", "foo.bar", "example.cz"),

Both from above sending with:

with smtplib.SMTP('localhost') as s:
        s.send_message(msg)

I'm get this exception:

smtplib.SMTPNotSupportedError: One or more source or delivery addresses require internationalized email support, but the server does not advertise the required SMTPUTF8 capability`

I know that caused by our's smtp server that does not support SMTPUTF8, but only from non-ASCI display name it shouldn't be necesery.

Body:
I tricked the send_message library by first sending a 'ehlo()', then modified the features manually:

s = smtplib.SMTP(server)
s.ehlo()
s.esmtp_features["smtputf8"] = ""
s.send_message(msg)

I also changed the message policy as I had other issues:

msg = MIMEMultipart(policy=SMTPUTF8)

Hope this helps! (This will work only if your server is UTF8 compatible but does not answer it with ehlo)


问:
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users.
To add some context: I'm not talking about Authentication (username / password). That will be taken care of by Auth0 (see auth0.com). So AFTER they are logged in, I see that Shiny Server does not pass the username to the Shiny session (maybe deliberately, so that you are forced to purchase the Commercial license to Shiny Server?).My question is more about : a) how do I make it recognize the username of the logged in user? b) will it scale to hundreds of concurrent (simultaneous) users?</p>

答:
The free version of Shiny Server can be enabled to utilize authentication before loading an app (a login screen) but does not then launch the shiny app as the user. This feature is only available in the pro version.

These cases are impossible with free Shiny Server

User logs in and the app executes a query against a secured database using the logged in identity

User logs in and the app recognizes them - free Shiny Server is already running under a user account and all users share that space.

User logs in and has their own private execution environment (if you have thousands of concurrent users you may well run into variable collisions which could expose what another user is looking at)


问:
Find Majority element in a sorted array in O(lg n) tie complexity
I am working with this problem and while looking at some of posts I went got a solution with time complexity O(n) using Moore's voting algorithm .
Majority element is that element which occurs more than size of array divided by 2 .
For o(lg n) time following is my code please suggest whether it is in o(lg n).
I welcome suggestions as I am very new to programming .</p>

```<code>#include <bits/stdc++.h>
#include <algorithm>
using namespace std ;

int binarySearch(vector <int> a, int l, int h){

        if(l - h < a.size() / 2)
            return -1;

        int mid = (l+h)/2;
        int temporaryLow = mid;
        int temporaryHigh = mid;

        while(temporaryLow > 0 && a[temporaryLow] == a[mid])
            temporaryLow--;

        while(temporaryHigh < a.size() && a[temporaryHigh] == a[mid])
            temporaryHigh++;

        if((temporaryHigh -1) - (temporaryLow+1) +1 >= a.size()/2){
            return a[mid];
        }else{

            return max(binarySearch(a,0,temporaryLow),binarySearch(a,temporaryHigh,h));

        }
    }

 int findMajority(vector <int> numbers){

        return binarySearch(numbers , 0, numbers.size());
    }

    int main()
    {
        int n ;
        vector <int> a ;
    while ((cin >> n) && n != 9999)
    a.push_back(n);

        int majority = findMajority(a);
        cout << majority ;
    }
</code>```

答:
No, it is not O(log n). Idea of binary search is to reduce the search space by half each time, which your code is not doing.

If array is ordered, majority value could be the middle value. To verify this, let mid be the middle value.

Find the lower_bound and upper_bound of mid check if difference is greater than half of array size.

code :

```<code>#include <vector>
#include <algorithm>

int majorityElement(const std::vector<int> &array) {
    auto size = array.size();
    if (!size)
        throw std::runtime_error("no majority element");
    auto mid = array[size/2];
    // These run in O(lg N) because array is sorted
    auto low_index = std::lower_bound(array.cbegin(), array.cend(), mid);
    auto upp_index = std::upper_bound(array.cbegin(), array.cend(), mid);
    if ((upp_index - low_index) > size/2)
        return mid;
    throw std::runtime_error("no majority element");
}
</code>```

Body:
I am working with this problem and while looking at some of posts I went got a solution with time complexity O(n) using Moore's voting algorithm .
Majority element is that element which occurs more than size of array divided by 2 .
For o(lg n) time following is my code please suggest whether it is in o(lg n).
I welcome suggestions as I am very new to programming .

#include <bits/stdc++.h>
#include <algorithm>
using namespace std ;

int binarySearch(vector <int> a, int l, int h){

        if(l - h  0 && a[temporaryLow] == a[mid])
            temporaryLow--;

        while(temporaryHigh = a.size()/2){
            return a[mid];
        }else{

            return max(binarySearch(a,0,temporaryLow),binarySearch(a,temporaryHigh,h));

        }
    }

 int findMajority(vector <int> numbers){

        return binarySearch(numbers , 0, numbers.size());
    }

    int main()
    {
        int n ;
        vector <int> a ;
    while ((cin >> n) && n != 9999)
    a.push_back(n);

        int majority = findMajority(a);
        cout << majority ;
    }

Body:
No, it is not O(log n). Idea of binary search is to reduce the search space by half each time, which your code is not doing.

If array is ordered, majority value could be the middle value. To verify this, let mid be the middle value.

Find the lower_bound and upper_bound of mid check if difference is greater than half of array size.

code :

#include <vector>
#include <algorithm>

int majorityElement(const std::vector<int> &array) {
    auto size = array.size();
    if (!size)
        throw std::runtime_error("no majority element");
    auto mid = array[size/2];
    // These run in O(lg N) because array is sorted
    auto low_index = std::lower_bound(array.cbegin(), array.cend(), mid);
    auto upp_index = std::upper_bound(array.cbegin(), array.cend(), mid);
    if ((upp_index - low_index) > size/2)
        return mid;
    throw std::runtime_error("no majority element");
}


问:
Can I add a subcolumn to a hive struct column using alter table?
I've a very complex table structure in hive, let's say that it's like the following table:

```<code>create table dirceu ( a struct<b:string,c:string>);
</code>```

Now I do need to add another subcolumn to the a column, and it should have the structure b,c and d, I'm trying to do it with the following alter table:

```<code>alter table dirceu change column a a struct<b:string,c:string, d:string>;
</code>```

But this throw the following error:

```<code>Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The following columns have types incompatible with the existing columns in their respective positions :
a (state=08S01,code=1)
</code>```

Is there a way to do this using alter table? I know that I can do it using create table and copy the data, but I would like to know if there is another way to do it.
 UPDATE
I'm using hive: 2.1.0.2.6.1.0-129
HortonWorks: HDP-2.6.1.0

答:
This is the command you need to give,

```<code>ALTER TABLE dirceu CHANGE COLUMN a a STRUCT<b:STRING, c:STRING, d:STRING>;
</code>```

You can't add a new field to Collection data type. Instead, you need to completely change the schema.
Hope you like the answer. Yippee!!

Body:
I've a very complex table structure in hive, let's say that it's like the following table:

create table dirceu ( a struct);

Now I do need to add another subcolumn to the a column, and it should have the structure b,c and d, I'm trying to do it with the following alter table:

alter table dirceu change column a a struct;

But this throw the following error:

Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter table. The following columns have types incompatible with the existing columns in their respective positions :
a (state=08S01,code=1)

Is there a way to do this using alter table? I know that I can do it using create table and copy the data, but I would like to know if there is another way to do it.
 UPDATE
I'm using hive: 2.1.0.2.6.1.0-129
HortonWorks: HDP-2.6.1.0

Body:
This is the command you need to give,

ALTER TABLE dirceu CHANGE COLUMN a a STRUCT<b:STRING, c:STRING, d:STRING>;

You can't add a new field to Collection data type. Instead, you need to completely change the schema.
Hope you like the answer. Yippee!!


问:
Declaration expected in VB dll
First of all thanking everyone....

I am currently working on VB. I am using Visual Studio 2008.

The piece of code below is a console application which builds without any error.

```<code>    Imports System.Net

Module Module1

    Public Sub Main()

        Dim address As IPAddress
        Dim remoteIP As System.Net.IPEndPoint
        Dim socketAddress As System.Net.SocketAddress

        Try
            address = IPAddress.Parse("192.168.0.187")
            remoteIP = New System.Net.IPEndPoint(address, 0)

            socketAddress = remoteIP.Serialize()

            Console.WriteLine("Address Family :" & remoteIP.AddressFamily.ToString())
            Console.WriteLine("IP :" & remoteIP.Address.ToString() & "Port :" & remoteIP.Port.ToString())
            Console.WriteLine("Socket address :" & socketAddress.ToString())

        Catch ex As Exception
            Console.WriteLine(ex.StackTrace.ToString())

        End Try

    End Sub

End Module
</code>```

In the next program which is a dll the same gives error saying "Declaration Expected for addr, remoteIP and socketAddr"

```<code>Imports System.Net

Public Class Class1

End Class
Public Class ethernet

    Dim addr As IPAddress
    Dim remoteIP As System.Net.IPEndPoint
    Dim socketAddr As System.Net.SocketAddress

    addr = IPAddress.Parse("192.168.0.187")
    remoteIP = New System.Net.IPEndPoint(addr,0)

    socketAddr = remoteIP.Serialize()

End Class
</code>```

Can anybody tell me why is this happening...

答:
Your code in the second class ethernet is not contained within a Method, therefore you are only declaring the addr, remoteIP and socketAddr variables.

To make that work just put the code in a method, like:

```<code>Public Class ethernet
    Public Function SerializeSocket(address As String) As System.Net.SocketAddress
        Dim addr As IPAddress = IPAddress.Parse("192.168.0.187")
        Dim remoteIP As System.Net.IPEndPoint = New System.Net.IPEndPoint(addr,0)
        Return remoteIP.Serialize()
    End Sub
End Class
</code>```

Title: Declaration expected in VB dll

Body:
First of all thanking everyone....

I am currently working on VB. I am using Visual Studio 2008.

The piece of code below is a console application which builds without any error.

    Imports System.Net

Module Module1

    Public Sub Main()

        Dim address As IPAddress
        Dim remoteIP As System.Net.IPEndPoint
        Dim socketAddress As System.Net.SocketAddress

        Try
            address = IPAddress.Parse("192.168.0.187")
            remoteIP = New System.Net.IPEndPoint(address, 0)

            socketAddress = remoteIP.Serialize()

            Console.WriteLine("Address Family :" & remoteIP.AddressFamily.ToString())
            Console.WriteLine("IP :" & remoteIP.Address.ToString() & "Port :" & remoteIP.Port.ToString())
            Console.WriteLine("Socket address :" & socketAddress.ToString())

        Catch ex As Exception
            Console.WriteLine(ex.StackTrace.ToString())

        End Try

    End Sub

End Module

In the next program which is a dll the same gives error saying "Declaration Expected for addr, remoteIP and socketAddr"

Imports System.Net

Public Class Class1

End Class
Public Class ethernet

    Dim addr As IPAddress
    Dim remoteIP As System.Net.IPEndPoint
    Dim socketAddr As System.Net.SocketAddress

    addr = IPAddress.Parse("192.168.0.187")
    remoteIP = New System.Net.IPEndPoint(addr,0)

    socketAddr = remoteIP.Serialize()

End Class

Can anybody tell me why is this happening...

Body:
Your code in the second class ethernet is not contained within a Method, therefore you are only declaring the addr, remoteIP and socketAddr variables.

To make that work just put the code in a method, like:

Public Class ethernet
    Public Function SerializeSocket(address As String) As System.Net.SocketAddress
        Dim addr As IPAddress = IPAddress.Parse("192.168.0.187")
        Dim remoteIP As System.Net.IPEndPoint = New System.Net.IPEndPoint(addr,0)
        Return remoteIP.Serialize()
    End Sub
End Class


问:
Visual C#, how can I set SetItemChecked property using Control?
I have a form which contains several CheckedListBox items, along with other controls. I'm trying to loop through each the controls and set its property values. Unfortunately, the SetItemChecked property is is not available in the Control class, so I can't figure out how to manipulate the Checked state of the control.

Here's what I have so far:

```<code>for (int i = 0; i < Controls.Count(); i++) {
  switch(Controls[i].GetType().ToString()) {
    case "System.Windows.Forms.TextBox":
    case "System.Windows.Forms.RichTextBox":
      Controls[i].Text=i.ToString();
        break;
    case "System.Windows.Forms.CheckedListBox":
      Controls[i].SetItemChecked(0,true);
      // ^^ This line doesn't work, because SetItemChecked is not available
      break;
    default:
      Controls[i].Tag=i;
      break;
  }
}
</code>```

答:
You can cast the Control into a CheckedListBox Like this:

```<code>(Controls[i] as CheckedListBox).SetItemChecked(0,true);
</code>```

I'm not sure of this one, but it might work also:

```<code>CheckedListBox myCbList= (ChecekdListBox) Controls[i];
myCbList.SetItemChecked(0,true)
</code>```

Body:
I have a form which contains several CheckedListBox items, along with other controls. I'm trying to loop through each the controls and set its property values. Unfortunately, the SetItemChecked property is is not available in the Control class, so I can't figure out how to manipulate the Checked state of the control.

Here's what I have so far:

for (int i = 0; i < Controls.Count(); i++) {
  switch(Controls[i].GetType().ToString()) {
    case "System.Windows.Forms.TextBox":
    case "System.Windows.Forms.RichTextBox":
      Controls[i].Text=i.ToString();
        break;
    case "System.Windows.Forms.CheckedListBox":
      Controls[i].SetItemChecked(0,true);
      // ^^ This line doesn't work, because SetItemChecked is not available
      break;
    default:
      Controls[i].Tag=i;
      break;
  }
}

Body:
You can cast the Control into a CheckedListBox Like this:

(Controls[i] as CheckedListBox).SetItemChecked(0,true);

I'm not sure of this one, but it might work also:

CheckedListBox myCbList= (ChecekdListBox) Controls[i];
myCbList.SetItemChecked(0,true)


问:
How to click Radio Button using python Selenium
I am trying to Click the Radio Button "Monthly (Final)" in the left side tab.

Please find the link https://socds.huduser.gov/permits/index.html?

Here is the Code which i tried,

```<code>from selenium import webdriver
import time

chrome_path = r"/usr/bin/chromedriver"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.huduser.gov/portal/datasets/socds.html") # Hitting the Site
driver.maximize_window()
driver.find_element_by_xpath("""//*[@id="block-system-main"]/div[4]/div/div/div/div/form[5]/input""").click() #Clicking Buiding Permits Database
time.sleep(10)
### Not working ###
print driver.find_element_by_xpath("""/html/body/form/a[2]/input""").location # Getting the Location of the Element
Radio = driver.find_element_by_xpath("""/html/body/form/a[2]/input""") # Clicking Monthly Final Radio button
Radio.click()
driver.find_element_by_css_selector("body > form:nth-child(2) > a:nth-child(29) > input:nth-child(1)").click()
print "DONE"
</code>```

答:
Radio button located inside an iframe. To be able to click it you should swith to iframe first:

```<code>driver.switch_to.frame('select')
Radio = driver.find_element_by_xpath("""//input[@value="monthlyF"]""")
Radio.click()
</code>```

Body:
I am trying to Click the Radio Button "Monthly (Final)" in the left side tab.

Please find the link https://socds.huduser.gov/permits/index.html?

Here is the Code which i tried,

from selenium import webdriver
import time

chrome_path = r"/usr/bin/chromedriver"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.huduser.gov/portal/datasets/socds.html") # Hitting the Site
driver.maximize_window()
driver.find_element_by_xpath("""//*[@id="block-system-main"]/div[4]/div/div/div/div/form[5]/input""").click() #Clicking Buiding Permits Database
time.sleep(10)
### Not working ###
print driver.find_element_by_xpath("""/html/body/form/a[2]/input""").location # Getting the Location of the Element
Radio = driver.find_element_by_xpath("""/html/body/form/a[2]/input""") # Clicking Monthly Final Radio button
Radio.click()
driver.find_element_by_css_selector("body > form:nth-child(2) > a:nth-child(29) > input:nth-child(1)").click()
print "DONE"

Body:
Radio button located inside an iframe. To be able to click it you should swith to iframe first:

driver.switch_to.frame('select')
Radio = driver.find_element_by_xpath("""//input[@value="monthlyF"]""")
Radio.click()


问:
Mocha / Typescript
How would I write a basic test class to compare the value of two numbers, to test a minimum value validation rule I wrote.
For example if the number I give is 10, I need to assert that a 9 "falls below the minimum value"  while if the number is 11, then it is acceptable.</p>

答:
Here is a function that should to do the check; If variable is greater that 10, the test passes, otherwise the test fails.

var assert = require('assert');
var variable = 11;
describe('comparison', function() {
  describe('#functionName()', function() {
    it('should return true when the variable is greater than 10', function() {
      assert.equal(true, variable > 10);
    });
  });
});
```

Title: Mocha / Typescript