问:
CORS problem with axios from a Vue app to a PHP API running on WAMP
I have trouble making an XHR request with axios from a Vue app to a PHP API running on WAMP.

The error message is the following :

Access to XMLHttpRequest at 'http://localhost/myapp/api/test/1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As you can see, it's a problem with CORS. After some documentation, here is what I have been doing to fix it (still not working).

Axios call :

```<code>axios({
  method: 'get',
  url: 'http://localhost/myapp/api/test/1',
  data: JSON.stringify({}),
  headers: { 'Content-Type': 'application/json', },
  crossdomain: true,
});
</code>```

If I visit http://localhost/myapp/api/test/1 in my web browser, I got my response.

I attempted putting this line of code in my PHP API, in my entry point (index.php)

```<code>header('Access-Control-Allow-Origin: *');
</code>```

I configured WAMP :

Changed httpd-vhosts.conf and httpd.conf

```<code># Virtual Hosts

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    Header set Access-Control-Allow-Origin "*"
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>
</code>```

Activated the "headers_module" in apache's modules

Rebooted everything, cleared my cache, tried from another browser ...

Still not working, am I missing something ?

答:
I use this at the top of my index.php file to fix CORS problems:</p>

```<code>function cors() {
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");

        exit(0);
    }
}
cors();
</code>```

Body:
I have trouble making an XHR request with axios from a Vue app to a PHP API running on WAMP.

The error message is the following :

Access to XMLHttpRequest at 'http://localhost/myapp/api/test/1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As you can see, it's a problem with CORS. After some documentation, here is what I have been doing to fix it (still not working).

Axios call :

axios({
  method: 'get',
  url: 'http://localhost/myapp/api/test/1',
  data: JSON.stringify({}),
  headers: { 'Content-Type': 'application/json', },
  crossdomain: true,
});

If I visit http://localhost/myapp/api/test/1 in my web browser, I got my response.

I attempted putting this line of code in my PHP API, in my entry point (index.php)

header('Access-Control-Allow-Origin: *');

I configured WAMP :

Changed httpd-vhosts.conf and httpd.conf

# Virtual Hosts

<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    Header set Access-Control-Allow-Origin "*"
    AllowOverride All
    Require local
  </Directory>
</VirtualHost>

Activated the "headers_module" in apache's modules

Rebooted everything, cleared my cache, tried from another browser ...

Still not working, am I missing something ?

Body:
I use this at the top of my index.php file to fix CORS problems:

function cors() {
    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
        header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");

        exit(0);
    }
}
cors();


来源: stackexchange

问:
Huge disparity in classification prediction results in CNN model Keras
I trained a CNN model with Keras with a df of 921 rows x 10165 columns Each row is a sample with 10160 features. I then used the pretrained model for prediction.

I made sure that the training data was well balanced, with around 50% samples with label 0 and the remaining 50% with label 1. Model accuracy looks decent but problem during prediction.

So the input data looks like this:

```<code>X = df.iloc[:,0:10160]
X = X.to_numpy()
X = X.reshape([X.shape[0], X.shape[1],1])
X_train_1 = X[:,0:10080,:]
X_train_2 = X[:,10080:10160,:].reshape(921,80)
Y = df.iloc[:,10163:10165]
Y = Y.to_numpy()
</code>```

and I predicted the number of samples with predicted label '1' (for label_1) with code:

```<code>prediction = pd.DataFrame(model.predict([X_train_1,X_train_2]))
prediction['label_1'] = ['0' if x < 0.5 else '1' for x in prediction['prob']]

prediction[prediction['label_1'] == '1'].shape[0]/921
</code>```

The second line of code calculates the fraction of samples with label_1 ==1 out of all samples. The issue is that given the input data has balanced number of 1 and 0, I was expecting that the fraction is around 50% or so, but the calculated fraction is between range 0.08~ 0.98(if not more extreme) with huge disparity. What could have gone wrong?

答:
Use model.predict_classes() instead. Otherwise you're getting probabilities.

```<code>prediction = pd.DataFrame(model.predict_classes([X_train_1,X_train_2]))
prediction[prediction['label_1'] == '1'].shape[0]/921
</code>```

If you're using the functional API, use np.argmax():

```<code>np.argmax(model.predict([X_train_1,X_train_2]), axis=1)
</code>```

Then you will need to predictions you need, as 0 and 1 instead of probabilities.

ContentLicense: CC BY-SA 4.0

Body:
I trained a CNN model with Keras with a df of 921 rows x 10165 columns Each row is a sample with 10160 features. I then used the pretrained model for prediction.

I made sure that the training data was well balanced, with around 50% samples with label 0 and the remaining 50% with label 1. Model accuracy looks decent but problem during prediction.

So the input data looks like this:

X = df.iloc[:,0:10160]
X = X.to_numpy()
X = X.reshape([X.shape[0], X.shape[1],1])
X_train_1 = X[:,0:10080,:]
X_train_2 = X[:,10080:10160,:].reshape(921,80)
Y = df.iloc[:,10163:10165]
Y = Y.to_numpy()

and I predicted the number of samples with predicted label '1' (for label_1) with code:

prediction = pd.DataFrame(model.predict([X_train_1,X_train_2]))
prediction['label_1'] = ['0' if x < 0.5 else '1' for x in prediction['prob']]

prediction[prediction['label_1'] == '1'].shape[0]/921

The second line of code calculates the fraction of samples with label_1 ==1 out of all samples. The issue is that given the input data has balanced number of 1 and 0, I was expecting that the fraction is around 50% or so, but the calculated fraction is between range 0.08~ 0.98(if not more extreme) with huge disparity. What could have gone wrong?

Body:
Use model.predict_classes() instead. Otherwise you're getting probabilities.

prediction = pd.DataFrame(model.predict_classes([X_train_1,X_train_2]))
prediction[prediction['label_1'] == '1'].shape[0]/921

If you're using the functional API, use np.argmax():

np.argmax(model.predict([X_train_1,X_train_2]), axis=1)

Then you will need to predictions you need, as 0 and 1 instead of probabilities.


问:
Reverse Order of a Nested Dictionary Python
I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

```<code>{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}
</code>```

and I wanted to instead make it the following:

```<code>{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}
</code>```

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()}, but I had no success with either.

Any help is appreciated!

答:
The solutions that implement reversed don't seem to work in older versions of Python i.e. pre 3.8. This solution should work in Python 3.x

Code

```<code>so_dict = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

{k: v for k, v in sorted(list(so_dict.items()), key=lambda x:x[0].lower(), reverse=True)}
</code>```

Output

```<code>{'dictC': {'key_3', 'value_3'},
 'dictB': {'key_2': 'value_2'},
 'dictA': {'key_1': 'value_1'}}
</code>```

Body:
I have a two-layered dictionary and would like a simple command or function (if possible) to reverse the order of the dictionary, but only the outer layer, not the inner. For instance, if my dictionary were as follows:

{'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

and I wanted to instead make it the following:

{'dictC': {'key_3', 'value_3'}, 'dictB': {'key_2': 'value_2'}, 'dictA': {'key_1': 'value_1'}}

How would I do this? I have tried methods like invertdict() and inv_map = {v: k for k, v in my_map.items()}, but I had no success with either.

Any help is appreciated!

Body:
The solutions that implement reversed don't seem to work in older versions of Python i.e. pre 3.8. This solution should work in Python 3.x

Code

so_dict = {'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}, 'dictC': {'key_3', 'value_3'}}

{k: v for k, v in sorted(list(so_dict.items()), key=lambda x:x[0].lower(), reverse=True)}

Output

{'dictC': {'key_3', 'value_3'},
 'dictB': {'key_2': 'value_2'},
 'dictA': {'key_1': 'value_1'}}


问:
Getting the localtime in milliseconds
I need the fastest way to get the localtime (thus considering the current timezone) at least in milliseconds precision, if is possible to get in tenths of milliseconds it would be better.

I would like to avoid the use of gettimeofday() as it is now an obsolete function.

So, there seems that I'll need to use the clock_gettime(CLOCK_REALTIME, ...) and adjust the hour to the current timezone, but how ? And where is the best point to do that ? Before to store the timestamp got with clock_gettime, or before to convert it in a gregorian calendar in the current timezone?

EDIT: My original sample joining get_clock and localtime - There are better ways to reach that?

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

int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    struct tm* ptm;
    ptm = localtime(&(ts.tv_sec));

    // Tenths of milliseconds (4 decimal digits)
    int tenths_ms = ts.tv_nsec / (100000L);

    printf("%04d-%02d-%02d %02d:%02d:%02d.%04d\n",
        1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday,
        ptm->tm_hour, ptm->tm_min, ptm->tm_sec, tenths_ms);
}
</code>```

答:
I don't think there's a better way than with clock_gettime() and localtime(). However you need to round the returned nanoseconds correctly and consider the case when the time is rounded up to the next second. To format the time you can use strftime() instead of formatting the tm struct manually:

#include <time.h>
#include <stdio.h>

int main(void) {
    struct timespec ts;
    long msec;
    int err = clock_gettime(CLOCK_REALTIME, &ts);
    if (err) {
        perror("clock_gettime");
        return 1;
    }

    // round nanoseconds to milliseconds
    if (ts.tv_nsec >= 999500000) {
        ts.tv_sec++;
        msec = 0;
    } else {
        msec = (ts.tv_nsec + 500000) / 1000000;
    }

    struct tm* ptm = localtime(&ts.tv_sec);
    if (ptm == NULL) {
        perror("localtime");
        return 1;
    }

    char time_str[sizeof("1900-01-01 23:59:59")];
    time_str[strftime(time_str, sizeof(time_str),
            "%Y-%m-%d %H:%M:%S", ptm)] = '\0';

    printf("%s.%03li\n", time_str, msec);
}
```

Title: Getting the localtime in milliseconds

Body:
I need the fastest way to get the localtime (thus considering the current timezone) at least in milliseconds precision, if is possible to get in tenths of milliseconds it would be better.

I would like to avoid the use of gettimeofday() as it is now an obsolete function.

So, there seems that I'll need to use the clock_gettime(CLOCK_REALTIME, ...) and adjust the hour to the current timezone, but how ? And where is the best point to do that ? Before to store the timestamp got with clock_gettime, or before to convert it in a gregorian calendar in the current timezone?

EDIT: My original sample joining get_clock and localtime - There are better ways to reach that?

#include <time.h>
#include <stdio.h>

int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    struct tm* ptm;
    ptm = localtime(&(ts.tv_sec));

    // Tenths of milliseconds (4 decimal digits)
    int tenths_ms = ts.tv_nsec / (100000L);

    printf("%04d-%02d-%02d %02d:%02d:%02d.%04d\n",
        1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday,
        ptm->tm_hour, ptm->tm_min, ptm->tm_sec, tenths_ms);
}


问:
How to add a local non-maven project as a dependency for a maven project?
I created a new Spring web app, and I'd very much like to use Maven to handle builds/dependencies.  My problem is that the project depends on some existing local projects, and mavenizing them is not currently an option.  Is it possible to depend on these projects without mavenizing them?</p>

答:
This answer's a tad late but just in case somebody needs it, I found the solution using Maven's Build Helper Plugin, that is if you don't want deploying your non-maven project as a jar:

So basically you just add the source directory of the non-maven project in the <sources> tag:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>C:\Users\user123\eclipse-workspace\my_non_maven_project\src</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Now if that non-maven project has dependencies of its own, you need to add them in the <dependencies> section of your maven project as well.

ContentLicense: CC BY-SA 3.0

Body:
This answer's a tad late but just in case somebody needs it, I found the solution using Maven's Build Helper Plugin, that is if you don't want deploying your non-maven project as a jar:

So basically you just add the source directory of the non-maven project in the <sources> tag:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>3.0.0</version>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>C:\Users\user123\eclipse-workspace\my_non_maven_project\src</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

Now if that non-maven project has dependencies of its own, you need to add them in the <dependencies> section of your maven project as well.


问:
Preg Replace - E Modifier
```<code>$strpost_a = preg_replace("/\[CallName]([^]]+)\[\/CallName\]/e", getInfo('\\1',"fullname"), $strpost_a);
</code>```

I always get this in return:

```<code>Parse error: syntax error, unexpected T_STRING in C:\wamp\www\-site\files\index\stream.php(88) : regexp code on line 1
Fatal error: preg_replace() [<a href='function.preg-replace'>function.preg-replace</a>]: Failed evaluating code: James -LastName Removed- in C:\wamp\www\-site-\files\index\stream.php on line 88
</code>```

答:
The second parameter to preg_replace must always be a string. Using the /e flag doesn't change that. And the second parameter simply should be a string consisting of code:

```<code>$strpost_a = preg_replace(
                 "/\[CallName]([^]]+)\[\/CallName\]/e",
                 'getInfo("\\1","fullname")',
                 $strpost_a
             );
</code>```

The string 'getInfo("\\1","fullname")' will then be evaluated. If you do not enclose it in quotes here, it will not be executed by preg_replace, but beforehand. That's why you got the error message.

(It's sometimes more suitable to use preg_replace_callback, but would likely require a specific getInfo_fullname in your case.)

Title: Preg Replace - E Modifier

Body:
$strpost_a = preg_replace("/\[CallName]([^]]+)\[\/CallName\]/e", getInfo('\\1',"fullname"), $strpost_a);

I always get this in return:

Parse error: syntax error, unexpected T_STRING in C:\wamp\www\-site\files\index\stream.php(88) : regexp code on line 1
Fatal error: preg_replace() [function.preg-replace]: Failed evaluating code: James -LastName Removed- in C:\wamp\www\-site-\files\index\stream.php on line 88

Body:
The second parameter to preg_replace must always be a string. Using the /e flag doesn't change that. And the second parameter simply should be a string consisting of code:

$strpost_a = preg_replace(
                 "/\[CallName]([^]]+)\[\/CallName\]/e",
                 'getInfo("\\1","fullname")',
                 $strpost_a
             );

The string 'getInfo("\\1","fullname")' will then be evaluated. If you do not enclose it in quotes here, it will not be executed by preg_replace, but beforehand. That's why you got the error message.

(It's sometimes more suitable to use preg_replace_callback, but would likely require a specific getInfo_fullname in your case.)


问:
Error installing reactjs: Error unexpected end of JSON input while parsing near
I tried installing reactjs via node using two different commands in the terminal using 1) npx create-react-app my-app and 2) npx create-react-app app

But both yielded the same error shown below:

Installing packages. This might take a couple of minutes.

Installing react, react-dom, and react-scripts with cra-template...

npm ERR! Unexpected end of JSON input while parsing near
  '....1","object-hash":"^1'

npm ERR! A complete log of this run can be found in:

npm ERR!
  C:\Users\David\AppData\Roaming\npm-cache_logs\2020-02-12T03_53_37_836Z-debug.log

Aborting installation.

npm install --save --save-exact --loglevel error react react-dom
  react-scripts cra-template has failed.

I tried uninstalling and reinstalling node and also trying to install different older versions of reactjs but still got the same error. Also, I have tried clearing the node cache and then verifying it again via npm cache clear --force and then npm cache verify but still have not had any luck. Any help will be greatly appreciated.

The more detailed log shows this at the bottom:

203 silly saveTree `-- react@16.12.0

204 verbose stack SyntaxError: Unexpected end of JSON input while
  parsing near '....1","object-hash":"^1'

204 verbose stack at JSON.parse ()

204 verbose stack at parseJson (C:\Program
  Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)

204 verbose stack at C:\Program
  Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50

204 verbose stack at processTicksAndRejections
  (internal/process/task_queues.js:97:5)

205 verbose cwd C:\Users\David\Desktop\React\my-app

206 verbose Windows_NT 10.0.17763

207 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "--save"
  "--save-exact" "--loglevel" "error" "react" "react-dom"
  "react-scripts" "cra-template"

208 verbose node v13.8.0

209 verbose npm v6.13.6

210 error Unexpected end of JSON input while parsing near
  '....1","object-hash":"^1'

211 verbose exit [ 1, true ]

答:
Installing yarn using node package manager fixed the issue for me. Open command prompt and enter:</p>

```<code>npm install -g yarn
</code>```

Body:
Installing yarn using node package manager fixed the issue for me. Open command prompt and enter:

npm install -g yarn


问:
Can't save values of variable through header files
I have declared a struct in a header A file. I assigned a value to a variable of that type struct on the same A file.
I included the A.h file on the other B.h file that is going to run the code.

For some reason, when I try to access the value of the the variable, it always resets. Is there a problem with my code or is this a reference issue?

Since I'm doing structures, I want the first node of the structure to always be the same (void option 1) I tried using extern but that doesn't help.

A.h file

```<code>using namespace std;

struct nodeChar
{
    char character;
    struct nodeChar *next;
    struct nodeChar *previous;
};

extern nodeChar *firstChar = new nodeChar();
extern nodeChar *previousChar = new nodeChar();
extern nodeChar *sentinelCharacter = new nodeChar();

void addCharacterNode(nodeChar *newCharacter)
{

    sentinelCharacter = firstChar;

    if(firstChar->character == NULL)
    {
        firstChar = newCharacter;
    }
    else while(sentinelCharacter != NULL)
    {
        if(sentinelCharacter->next = NULL)
        {
            newCharacter->previous = sentinelCharacter;
            sentinelCharacter->next = newCharacter;
            break;
        }

        sentinelCharacter = sentinelCharacter->next;
    }
}
</code>```

B.h file

```<code>#include <iostream>
#include <string>

#include "TextStructure.h"
#include <curses.h>

void option1()
{
    printMenuOption1();
    int x = 1;
    int y = 7;
    bool keepWriting = TRUE;
    nodeChar *pressedCharacter = new nodeChar();

    while(keepWriting)
    {
        int key = getch();

        switch(key)
        {
            case '9':
                keepWriting = FALSE;
                clear();
                break;
            case '8':
                saveFile();
                printMenuOption1();
                break;
            case '7':

                break;

            default:
                pressedCharacter->character = key;
                addCharacterNode(pressedCharacter);
                mvprintw(y, x, "%c", firstChar->character); /*This is where it prints a character.
It prints the key pressed. But when I write again, it should still print the first character, not the key pressed. And it prints the key pressed. */

                if(x == 68)
                {
                    x = 1;
                    y++;
                } else
                {
                    x++;
                }
                break;

        }
    }
}
</code>```

Hopefully I posted the question correctly. Not a pro on c++, any tip is well received.

答:
First:
The code is written in assumption that 'next' and 'previous' will get assigned NULL when structure is alocated by operator 'new'. Normally it's not the case, if these pointer are not explicitely assigned NULL, then they get a random values. You need to assign 'next' and 'previous' NULL values after 'new'.

Second:
You allocate 'pressedCharacter' only once, before loop:

```<code>bool keepWriting = TRUE;
**nodeChar *pressedCharacter = new nodeChar();**
</code>```

So you always assign character to the same structure. The bold line should be inside the loop.

Body:
I have declared a struct in a header A file. I assigned a value to a variable of that type struct on the same A file.
I included the A.h file on the other B.h file that is going to run the code.

For some reason, when I try to access the value of the the variable, it always resets. Is there a problem with my code or is this a reference issue?

Since I'm doing structures, I want the first node of the structure to always be the same (void option 1) I tried using extern but that doesn't help.

A.h file

using namespace std;

struct nodeChar
{
    char character;
    struct nodeChar *next;
    struct nodeChar *previous;
};

extern nodeChar *firstChar = new nodeChar();
extern nodeChar *previousChar = new nodeChar();
extern nodeChar *sentinelCharacter = new nodeChar();

void addCharacterNode(nodeChar *newCharacter)
{

    sentinelCharacter = firstChar;

    if(firstChar->character == NULL)
    {
        firstChar = newCharacter;
    }
    else while(sentinelCharacter != NULL)
    {
        if(sentinelCharacter->next = NULL)
        {
            newCharacter->previous = sentinelCharacter;
            sentinelCharacter->next = newCharacter;
            break;
        }

        sentinelCharacter = sentinelCharacter->next;
    }
}

B.h file

#include <iostream>
#include <string>

#include "TextStructure.h"
#include <curses.h>

void option1()
{
    printMenuOption1();
    int x = 1;
    int y = 7;
    bool keepWriting = TRUE;
    nodeChar *pressedCharacter = new nodeChar();

    while(keepWriting)
    {
        int key = getch();

        switch(key)
        {
            case '9':
                keepWriting = FALSE;
                clear();
                break;
            case '8':
                saveFile();
                printMenuOption1();
                break;
            case '7':

                break;

            default:
                pressedCharacter->character = key;
                addCharacterNode(pressedCharacter);
                mvprintw(y, x, "%c", firstChar->character); /*This is where it prints a character.
It prints the key pressed. But when I write again, it should still print the first character, not the key pressed. And it prints the key pressed. */

                if(x == 68)
                {
                    x = 1;
                    y++;
                } else
                {
                    x++;
                }
                break;

        }
    }
}

Hopefully I posted the question correctly. Not a pro on c++, any tip is well received.

Body:
First:
The code is written in assumption that 'next' and 'previous' will get assigned NULL when structure is alocated by operator 'new'. Normally it's not the case, if these pointer are not explicitely assigned NULL, then they get a random values. You need to assign 'next' and 'previous' NULL values after 'new'.

Second:
You allocate 'pressedCharacter' only once, before loop:

bool keepWriting = TRUE;
**nodeChar *pressedCharacter = new nodeChar();**

So you always assign character to the same structure. The bold line should be inside the loop.


问:
AttributeError: 'numpy.ndarray' object has no attribute 'insert'
Code:

```<code>import numpy as np

coordinates = np.array([])

for x in range(1, 9):
  for y in range(1, 9):
    coordinates = coordinates.insert(coordinates, (x,y))
</code>```

Despite having read many tutorials and Stack Overflow responses, everything I try is not working. Can somebody help?

答:
Replace this line:

```<code>coordinates = coordinates.insert(coordinates, (x,y))
</code>```

With this:

```<code>coordinates = np.insert(coordinates, x,y)
</code>```

You'll get an error because you started your loop at index 1, and 1 is the second position in Python (indexing starts at 0). You can't insert something at position 1 in an empty numpy array. For your code to work, you have to start your loop at index 0:

```<code>import numpy as np

coordinates = np.array([])

for x in range(0, 9):
  for y in range(0, 9):
    coordinates = np.insert(coordinates, x, y)
</code>```

```<code>Out[10]:
array([8., 8., 8., 8., 8., 8., 8., 8., 8., 7., 6., 5., 4., 3., 2., 1., 0.,
       7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7.,
       6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6.,
       5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5.,
       4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0.])
</code>```

Body:
Code:

import numpy as np

coordinates = np.array([])

for x in range(1, 9):
  for y in range(1, 9):
    coordinates = coordinates.insert(coordinates, (x,y))

Despite having read many tutorials and Stack Overflow responses, everything I try is not working. Can somebody help?

Body:
Replace this line:

coordinates = coordinates.insert(coordinates, (x,y))

With this:

coordinates = np.insert(coordinates, x,y)

You'll get an error because you started your loop at index 1, and 1 is the second position in Python (indexing starts at 0). You can't insert something at position 1 in an empty numpy array. For your code to work, you have to start your loop at index 0:

import numpy as np

coordinates = np.array([])

for x in range(0, 9):
  for y in range(0, 9):
    coordinates = np.insert(coordinates, x, y)

Out[10]:
array([8., 8., 8., 8., 8., 8., 8., 8., 8., 7., 6., 5., 4., 3., 2., 1., 0.,
       7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7.,
       6., 5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6.,
       5., 4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0., 7., 6., 5.,
       4., 3., 2., 1., 0., 7., 6., 5., 4., 3., 2., 1., 0.])


问:
Correct approach to avoid rendering view in Action
I currently use an ajax post back to an action to create a new database object and then return the rendered html for a view of that object. I then inject that html into the page.

I was wondering, since MVC does easily allow you to render views to HTML from within controllers, if there was a better (or more correct) approach to the problem.

(I currently use this code to render the view as html in the action).

Any and all ideas appreciated.

答:
As a matter of fact there is. Just return a partial view.</p>

```<code>public ActionResult AjaxStuff()
{
    // do whatever
    var model = ...;
    return PartialView(model);
}
</code>```

Body:
As a matter of fact there is. Just return a partial view.

public ActionResult AjaxStuff()
{
    // do whatever
    var model = ...;
    return PartialView(model);
}


问:
Routing & pretty URL
I am looking to create prettier URLs, and I'm having issues creating a valid route:

Let's say I have the following page http://localhost/app/account/5/edit.

This works fine with Route::get('account/{account}', 'AccountController@edit');

If I modify the Account Model and modify getRouteKeyName to return 'name', I am able to (with the same Route from above) access the following link: http://localhost/app/account/randomName/edit

The thing is, I am interested in a slightly different route, which is: http://localhost/app/account/randomName-5/edit

If I create a route Route::get('/accounts/{ignore}-{account}/edit', 'AccountController@edit'), it will fail as the first argument sent to edit is string and not an instance of Account. This can easily be fixed by modifying edit(Account $ac) to edit($ignored, Account $ac);... but it feels like cheating.

Is there a way to to get the route to ignore the first {block}?

答:
According to the docs, you can customize your resolution logic for route model binding.

In this scenario, you can do something like this in App\Providers\RouteServiceProvider:

```<code>/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('accountNameWithId', function ($value) {
        list($accountName, $accountId) = explode('-', $value);

        return App\Account::whereKey($accountId)
            ->where('name', $accountName)
            ->firstOrFail();
    });
}
</code>```

Then you can redefine your route like this:

```<code>Route::get('account/{accountNameWithId}', 'AccountController@edit');
</code>```

Title: Routing & pretty URL

Body:
According to the docs, you can customize your resolution logic for route model binding.

In this scenario, you can do something like this in App\Providers\RouteServiceProvider:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('accountNameWithId', function ($value) {
        list($accountName, $accountId) = explode('-', $value);

        return App\Account::whereKey($accountId)
            ->where('name', $accountName)
            ->firstOrFail();
    });
}

Then you can redefine your route like this:

Route::get('account/{accountNameWithId}', 'AccountController@edit');


问:
Turbocharge a lambda function comparing values in two dataframes
I've got an OHLCV financial dataset I'm working with that's approx 1.5M rows. It's for a single security back to 2000 at a 1min resolution. The dataset had all the zero volume timestamps removed so has gaps in the trading day which I don't want for my purposes.

Raw data (df1) looks like:

Timestamp, Open, High, Low, Close, Volume

To fill in the all the zero volume timestamps I created an empty trading calendar (df2) using (pandas_market_calendars which is an amazing time saver) and I've then used df3 = merge_asof(df2, df1, on='Timestamp', direction = nearest) to fill all the timestamps. This is the behaviour I wanted for the price data (OHLC) but not for volume. I need all the 'filled' timestamps to show zero volume so I figured a lambda function would suit (as below) to check if each timestamp was in the original dataframe (df1) or not.

```<code>tss = df1.Timestamp.to_numpy()
df2['Adj_Volume'] = df2.apply(lambda x: x['Volume'] if x['Timestamp'] in tss else 0, axis=1)
</code>```

I ran this for an hour, then two hours, then five hours and it's still not finished. To try and work out what's going on, I then used tqdm (progress_apply) and it estimates that it'll take 100 hours to complete! I running the conda dist of Jupyter Notebooks on an 2014 MacbookAir (1.7Ghz, 8Gb RAM) which isn't a supercomputer but 100 hours seems whacky.

If I cut down tss and df3 to a single year (~50k rows), it'll run in ~5mins. However, this doesn't scale linearly to the full dataset. 100 hours vs 100 mins (5mins x 20 years (2000 - 2019)). Slicing the dataframe up into years in a python level loop to then join them again afterwards feels clunky, but I can't think of another way.

Is there a smarter way to do this which takes advantage of vectorised operations that can be run on the entire dataset in a single operation?

Cheers

答:
Maybe you could try with np.wherefunction and .isin method ?

```<code>import numpy as np
df2['Volume'] = np.where(df2['Timestamp'].isin(tss),df2['Volume'], 0)
</code>```

Body:
I've got an OHLCV financial dataset I'm working with that's approx 1.5M rows. It's for a single security back to 2000 at a 1min resolution. The dataset had all the zero volume timestamps removed so has gaps in the trading day which I don't want for my purposes.

Raw data (df1) looks like:

Timestamp, Open, High, Low, Close, Volume

To fill in the all the zero volume timestamps I created an empty trading calendar (df2) using (pandas_market_calendars which is an amazing time saver) and I've then used df3 = merge_asof(df2, df1, on='Timestamp', direction = nearest) to fill all the timestamps. This is the behaviour I wanted for the price data (OHLC) but not for volume. I need all the 'filled' timestamps to show zero volume so I figured a lambda function would suit (as below) to check if each timestamp was in the original dataframe (df1) or not.

tss = df1.Timestamp.to_numpy()
df2['Adj_Volume'] = df2.apply(lambda x: x['Volume'] if x['Timestamp'] in tss else 0, axis=1)

I ran this for an hour, then two hours, then five hours and it's still not finished. To try and work out what's going on, I then used tqdm (progress_apply) and it estimates that it'll take 100 hours to complete! I running the conda dist of Jupyter Notebooks on an 2014 MacbookAir (1.7Ghz, 8Gb RAM) which isn't a supercomputer but 100 hours seems whacky.

If I cut down tss and df3 to a single year (~50k rows), it'll run in ~5mins. However, this doesn't scale linearly to the full dataset. 100 hours vs 100 mins (5mins x 20 years (2000 - 2019)). Slicing the dataframe up into years in a python level loop to then join them again afterwards feels clunky, but I can't think of another way.

Is there a smarter way to do this which takes advantage of vectorised operations that can be run on the entire dataset in a single operation?

Cheers

Body:
Maybe you could try with np.wherefunction and .isin method ?

import numpy as np
df2['Volume'] = np.where(df2['Timestamp'].isin(tss),df2['Volume'], 0)


问:
MongoDB - Get SUM of values INSIDE of the array
I have JSON document recorded to MongoDB with structure like so:

```<code>[{ "SessionKey": "172e3b6b-509e-4ef3-950c-0c1dc5c83bab",
   "Query": {"Date": "2020-03-04"},
   "Flights": [
           {"LegId":"13235",
            "PricingOptions": [
                    {"Agents": [1963108],
                     "Price": 61763.64 },
                    {"Agents": [4035868],
                     "Price": 62395.83 }]},
            {"LegId": "13236",
             "PricingOptions": [{
                        "Agents": [2915951],
                        "Price": 37188.0}]}
                         ...
</code>```

The result I'm trying to get is "LegId":"sum_per_flight", in this case -> {'13235': (61763.64+62395.83), '13236': 37188.0} and then get flights with price < N

I've tried to run this pipeline for aggregation step (but it returns list of ALL prices - I don't know how to sum them up properly):

```<code>result = collection.aggregate([
    {'$match': {'Query.Date': '2020-03-01'}},
    {'$group': {'_id': {'Flight':'$Flights.LegId', 'Price':'$Flights.PricingOptions.Price'}}} ])
</code>```

Also I've tried this pipeline, but it returns 0 for 'total_price_per_flight':

```<code>result = collection.aggregate({'$project': {
        'Flights.LegId':1,
        'total_price_per_flight': {'$sum': '$Flights.PricingOptions.Price'}
    }})
</code>```

答:
You need to use $unwind to flatten Flights array to able iterate individually.

With $reduce operator, we iterate PricingOptions array and sum Price fields (accumulate prices).

The last step we return your documents into original structure. Before that, you may apply "get flights with price < N"

```<code>db.collection.aggregate([
  {
    "$match": {
      "Query.Date": "2020-03-04"
    }
  },
  {
    $unwind: "$Flights"
  },
  {
    $addFields: {
      "Flights.LegId": {
        $arrayToObject: [
          [
            {
              k: "$Flights.LegId",
              v: {
                $reduce: {
                  input: "$Flights.PricingOptions",
                  initialValue: 0,
                  in: {
                    $add: [
                      "$$value",
                      "$$this.Price"
                    ]
                  }
                }
              }
            }
          ]
        ]
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      SessionKey: {
        $first: "$SessionKey"
      },
      Query: {
        $first: "$Query"
      },
      Flights: {
        $push: "$Flights"
      }
    }
  }
])
</code>```

MongoPlayground

Body:
I have JSON document recorded to MongoDB with structure like so:

[{ "SessionKey": "172e3b6b-509e-4ef3-950c-0c1dc5c83bab",
   "Query": {"Date": "2020-03-04"},
   "Flights": [
           {"LegId":"13235",
            "PricingOptions": [
                    {"Agents": [1963108],
                     "Price": 61763.64 },
                    {"Agents": [4035868],
                     "Price": 62395.83 }]},
            {"LegId": "13236",
             "PricingOptions": [{
                        "Agents": [2915951],
                        "Price": 37188.0}]}
                         ...

The result I'm trying to get is "LegId":"sum_per_flight", in this case -> {'13235': (61763.64+62395.83), '13236': 37188.0} and then get flights with price < N

I've tried to run this pipeline for aggregation step (but it returns list of ALL prices - I don't know how to sum them up properly):

result = collection.aggregate([
    {'$match': {'Query.Date': '2020-03-01'}},
    {'$group': {'_id': {'Flight':'$Flights.LegId', 'Price':'$Flights.PricingOptions.Price'}}} ])

Also I've tried this pipeline, but it returns 0 for 'total_price_per_flight':

result = collection.aggregate({'$project': {
        'Flights.LegId':1,
        'total_price_per_flight': {'$sum': '$Flights.PricingOptions.Price'}
    }})

Body:
You need to use $unwind to flatten Flights array to able iterate individually.

With $reduce operator, we iterate PricingOptions array and sum Price fields (accumulate prices).

The last step we return your documents into original structure. Before that, you may apply "get flights with price < N"

db.collection.aggregate([
  {
    "$match": {
      "Query.Date": "2020-03-04"
    }
  },
  {
    $unwind: "$Flights"
  },
  {
    $addFields: {
      "Flights.LegId": {
        $arrayToObject: [
          [
            {
              k: "$Flights.LegId",
              v: {
                $reduce: {
                  input: "$Flights.PricingOptions",
                  initialValue: 0,
                  in: {
                    $add: [
                      "$$value",
                      "$$this.Price"
                    ]
                  }
                }
              }
            }
          ]
        ]
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      SessionKey: {
        $first: "$SessionKey"
      },
      Query: {
        $first: "$Query"
      },
      Flights: {
        $push: "$Flights"
      }
    }
  }
])

MongoPlayground


问:
Creating string values from for loop
Slightly strange question, but I have a for loop that loops through, and builds a list:

function buildList(jsonList) {
  var list = "
";
  for (i = 0; i < jsonList.length; i++) {
    list += "
";
    list += "
" + jsonList[i].keyNumber + "
";
    list +=
      "
" +
      "<button type='button' class='btn' onclick='deleteRow(this)'>" +
      "Remove" +
      "</button>" +
      "
";
    list += "
";
  }
  list += "
";
  document.getElementById("htmlList").innerHTML = list;
}
```

Is there anyway I can pass the jsonList[i].keyNumber value to inside my onlick function inside my button?

onclick= 'deleteRow(this, jsonList[i].keyNumber)'.

That way, deleteRow will know which list to delete.

I would like to keep the above format and not use Jquery.

I need the ID, sending it to an API

答:
```<code>function buildList(jsonList) {
let list = `<tbody>`;
for (i = 0; i < jsonList.length; i++) {
    list += `<ul class ='list'>
  <li> ${jsonList[i].keyNumber} </li>
  <li>
    <button type='button' class='btn' onclick='deleteRow(this)'>
    Remove
    </button>
    </li>
    </ul>`;
}
list += `</tbody>`;
document.getElementById("htmlList").innerHTML = list;}
</code>```

Should work.

Title: Creating string values from for loop

Body:
Slightly strange question, but I have a for loop that loops through, and builds a list:

function buildList(jsonList) {
  var list = "
";
  for (i = 0; i < jsonList.length; i++) {
    list += "
";
    list += "
" + jsonList[i].keyNumber + "
";
    list +=
      "
" +
      "<button type='button' class='btn' onclick='deleteRow(this)'>" +
      "Remove" +
      "</button>" +
      "
";
    list += "
";
  }
  list += "
";
  document.getElementById("htmlList").innerHTML = list;
}

Is there anyway I can pass the jsonList[i].keyNumber value to inside my onlick function inside my button?

onclick= 'deleteRow(this, jsonList[i].keyNumber)'.

That way, deleteRow will know which list to delete.

I would like to keep the above format and not use Jquery.

I need the ID, sending it to an API

Body:
function buildList(jsonList) {
let list = `<tbody>`;
for (i = 0; i < jsonList.length; i++) {
    list += `<ul class ='list'>
  <li> ${jsonList[i].keyNumber} </li>
  <li>
    <button type='button' class='btn' onclick='deleteRow(this)'>
    Remove
    </button>
    </li>
    </ul>`;
}
list += `</tbody>`;
document.getElementById("htmlList").innerHTML = list;}

Should work.


问:
(Pentaho PDI):Thread: Couldn't find starting point in this job
Pentaho running job through command line

I have a pentaho job which runs successfully in pentaho but if i try to run the same through command line i get the error -(But It runs Successfully in one PC throws, error in another PC)

Here is my problem of the moment:

2016/12/12 16:52:30 - Start of job execution

2016/12/12 16:52:30 - ERROR (version 6.0.0.0-353, build 1 from 2015-10-07

13.27.43 by buildguy) : A serious error occurred during job execution:

2016/12/12 16:52:30 - Couldn't find starting point in this job.

2016/12/12 16:52:30 - ERROR (version 6.0.0.0-353, build 1 from 2015-10-07

13.27.43 by buildguy) : org.pentaho.di.core.exception.KettleJobException:

2016/12/12 16:52:30 - Couldn't find starting point in this job.

2016/12/12 16:52:30 -   at org.pentaho.di.job.Job.execute(Job.java:532)

2016/12/12 16:52:30 -   at org.pentaho.di.job.Job.run(Job.java:435)

2016/12/12 16:52:30 - Kitchen - Finished!

2016/12/12 16:52:30 - Kitchen - ERROR (version 6.0.0.0-353, build 1 from

2015-10-07 13.27.43 by buildguy) : Finished with errors

2016/12/12 16:52:30 - Kitchen - Start=2016/12/12 16:52:15.536, Stop=2016/12/12 16:52:30.652

答:
Are you sure if you are using ****Start**** step while writing a job.
P.S. Each Pentaho job needs a start step to execute.</p>


问:
How to send information to database without reloading the page
I've been trying to send information to the database using AJAX but nothing is working, each time i click the submit button, nothing works, the pages stays static somewhat. All JS files are referenced properly so i'm not sure what i'm doing wrong.

Here's what i've done so far;

Controller:

```<code>public function contact_us_ajax() {
    //form validation rules and file upload config
    $this->form_validation->set_rules('name', 'Name', 'trim|required');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('subject', 'Subject', 'trim|required');
    $this->form_validation->set_rules('message', 'Message', 'trim|required');
    $this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
    $this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
        array(
            'required' => 'Captcha is required. Reload the page if you cannot see any code.',
            'matches' => 'Invalid captcha code'
        )
    );

    if ($this->form_validation->run()) {
        $this->message_model->contact_us(); //insert the data into database
        $res = ['status' => true, 'msg' => 'Message sent successfully!'];
        echo json_encode($res);
    } else {
        $res = ['status' => false, 'msg' => validation_errors()];
        echo json_encode($res);
    }
}
</code>```

Model:

```<code>public function contact_us() {
    $name = ucwords($this->input->post('name', TRUE));
    $email = $this->input->post('email', TRUE);
    $subject = ucwords($this->input->post('subject', TRUE));
    $message = ucfirst($this->input->post('message', TRUE));
    $message = nl2br($message);
    $data = array (
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'message' => $message,
    );
    $this->db->insert('contact_messages', $data);

    //email admins
    //$this->notify_admins($name, $email, $subject, $message);
}
</code>```

View:

```<code>        <?php
              $form_attributes = array("id" => "contact_us_form");
              echo form_open('home/contact_us_ajax', $form_attributes); ?>
     <!-- Contact Form -->
     <div class="col-md-5">

           <h4>Send Us a Message</h4>
           <div class="form-group">

              <label>Name:</label><input type="text" name="name" class="form-control input-field"  required>
              <label>Email:</label><input type="email" name="email" class="form-control input-field" required>
              <label>Subject:</label><input type="text" name="subject" class="form-control input-field" required>
           </div>

           <label>Message:</label>
           <textarea name="message" class="textarea-field form-control" rows="4"  required></textarea>

           <div class="col-md-6">
              <input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />
           </div>
           <div class="col-md-6">
               <input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />
           </div>

           <div id="status_msg"></div>

           <?php echo flash_message_success('status_msg'); ?>
           <?php echo flash_message_danger('status_msg_error'); ?>

           <button class="btn center-block">Send message</button>

     </div>

        <?php echo form_close(); ?>
</code>```

AJAX:

```<code>//Contact Us
$('#contact_us_form').submit(function(e) {
    e.preventDefault();
    var form_data = $(this).serialize();
    $.ajax({
        url: base_url + 'home/contact_us_ajax',
        type: 'POST',
        data: form_data,
        dataType: 'json',
        success: function(res) {
            if (res.status) {
                $( '#status_msg' ).html('<div class="alert alert-success text-center" style="color: #000">'+res.msg+'</div>').fadeIn('fast');
                $('#contact_us_form')[0].reset(); //reset form fields
                $('#captcha_code').val(''); //clear captcha field
                setTimeout(function() {
                    location.reload();
                }, 5000);
            } else {
                $( '#status_msg' ).html('<div class="alert alert-danger text-center" style="color: #000">' + res.msg + '</div>').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );
            }
        }
    });
});
</code>```

答:
base_url is defined in codeigniter's config.php, for example like:

```<code>$config['base_url'] =  'http://or.org/';
</code>```

BUT! This doesn't mean you can simply name a variable in javascript base_url and hope to get any value.

To use it in your ajax call, you need to echo the php constant out like:

```<code>url: '<?php echo base_url()?>' + 'home/contact_us_ajax'
</code>```

I normally just use the relative path

```<code>url: '/home/contact_us_ajax'
</code>```

which works fine as well, if you use a "regular" CI configuration

Body:
I've been trying to send information to the database using AJAX but nothing is working, each time i click the submit button, nothing works, the pages stays static somewhat. All JS files are referenced properly so i'm not sure what i'm doing wrong.

Here's what i've done so far;

Controller:

public function contact_us_ajax() {
    //form validation rules and file upload config
    $this->form_validation->set_rules('name', 'Name', 'trim|required');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('subject', 'Subject', 'trim|required');
    $this->form_validation->set_rules('message', 'Message', 'trim|required');
    $this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
    $this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
        array(
            'required' => 'Captcha is required. Reload the page if you cannot see any code.',
            'matches' => 'Invalid captcha code'
        )
    );

    if ($this->form_validation->run()) {
        $this->message_model->contact_us(); //insert the data into database
        $res = ['status' => true, 'msg' => 'Message sent successfully!'];
        echo json_encode($res);
    } else {
        $res = ['status' => false, 'msg' => validation_errors()];
        echo json_encode($res);
    }
}

Model:

public function contact_us() {
    $name = ucwords($this->input->post('name', TRUE));
    $email = $this->input->post('email', TRUE);
    $subject = ucwords($this->input->post('subject', TRUE));
    $message = ucfirst($this->input->post('message', TRUE));
    $message = nl2br($message);
    $data = array (
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'message' => $message,
    );
    $this->db->insert('contact_messages', $data);

    //email admins
    //$this->notify_admins($name, $email, $subject, $message);
}

View:

        <?php
              $form_attributes = array("id" => "contact_us_form");
              echo form_open('home/contact_us_ajax', $form_attributes); ?>

Send Us a Message

              Name:<input type="text" name="name" class="form-control input-field"  required>
              Email:<input type="email" name="email" class="form-control input-field" required>
              Subject:<input type="text" name="subject" class="form-control input-field" required>

           Message:
           <textarea name="message" class="textarea-field form-control" rows="4"  required></textarea>

              <input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />

               <input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />

           <?php echo flash_message_success('status_msg'); ?>
           <?php echo flash_message_danger('status_msg_error'); ?>

           <button class="btn center-block">Send message</button>

        <?php echo form_close(); ?>

AJAX:

//Contact Us
$('#contact_us_form').submit(function(e) {
    e.preventDefault();
    var form_data = $(this).serialize();
    $.ajax({
        url: base_url + 'home/contact_us_ajax',
        type: 'POST',
        data: form_data,
        dataType: 'json',
        success: function(res) {
            if (res.status) {
                $( '#status_msg' ).html('
'+res.msg+'
').fadeIn('fast');
                $('#contact_us_form')[0].reset(); //reset form fields
                $('#captcha_code').val(''); //clear captcha field
                setTimeout(function() {
                    location.reload();
                }, 5000);
            } else {
                $( '#status_msg' ).html('
' + res.msg + '
').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );
            }
        }
    });
});

Body:
base_url is defined in codeigniter's config.php, for example like:

$config['base_url'] =  'http://or.org/';

BUT! This doesn't mean you can simply name a variable in javascript base_url and hope to get any value.

To use it in your ajax call, you need to echo the php constant out like:

url: '<?php echo base_url()?>' + 'home/contact_us_ajax'

I normally just use the relative path

url: '/home/contact_us_ajax'

which works fine as well, if you use a "regular" CI configuration


问:
Stop and remove all docker containers
How can I stop and remove all docker containers to create a clean slate with my Docker containers? Lots of times I feel it is easier to start from scratch, but I have a bunch of containers that I am not sure what their states are, then when I run docker rm it won't let me because the docker container could still be in use.

答:
We can achieve this with one liner (also removes running containers)

```<code>docker container rm $(docker container ls -aq) -f
</code>```

What it does

docker container ls -aq lists container's ids only

docker container rm $(..) -f forcibly removes all container's ids

Title: Stop and remove all docker containers

Body:
We can achieve this with one liner (also removes running containers)

docker container rm $(docker container ls -aq) -f

What it does

docker container ls -aq lists container's ids only

docker container rm $(..) -f forcibly removes all container's ids


问:
Plotting vertical axis lines using values from an array
I have the following array in Jupyter, which I am using to plot as vertical lines from the x-axis.

```<code>array([6, 10, 18, 23, 29, 33, 50])
</code>```

I am using pylab and matplotlib to do this.

I have produced the following code below thus far:

mylist = array([6, 10, 18, 23, 29, 33, 50])
mylist
for i in mylist:
  axvline(mylist[i])
```

<p>However, I get the following error and only my last value plotted:</p>

```---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-106-37afa3c95407> in <module>
      2 mylist
      3 for i in mylist:
----> 4     axvline(mylist[i])

IndexError: index 10 is out of bounds for axis 0 with size 7
```

I am struggling to understand what to do to rectify the problem.

What error am I making here?

Photo showing graph being produced

I am unable to render my image in the question due to being a new user on this site.

答:
You are using the indexing wrongly. When you do for i in mylist:, you are directly looping over the elements. So you can't access the elements then using mylist[i] but you need to directly use i

IndexError: index 10 is out of bounds for axis 0 with size 7

The error above occurs when you access the second element which is 10. When i=10, you use it as mylist[10] which throws error because the length of mylist is 7 because it has 7 elements.

Correct way:

```<code>for i in mylist:
    plt.axvline(i)
</code>```

Body:
I have the following array in Jupyter, which I am using to plot as vertical lines from the x-axis.

array([6, 10, 18, 23, 29, 33, 50])

I am using pylab and matplotlib to do this.

I have produced the following code below thus far:

mylist = array([6, 10, 18, 23, 29, 33, 50])
mylist
for i in mylist:
  axvline(mylist[i])

However, I get the following error and only my last value plotted:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-106-37afa3c95407> in <module>
      2 mylist
      3 for i in mylist:
----> 4     axvline(mylist[i])

IndexError: index 10 is out of bounds for axis 0 with size 7

I am struggling to understand what to do to rectify the problem.

What error am I making here?

Photo showing graph being produced

I am unable to render my image in the question due to being a new user on this site.

Body:
You are using the indexing wrongly. When you do for i in mylist:, you are directly looping over the elements. So you can't access the elements then using mylist[i] but you need to directly use i

IndexError: index 10 is out of bounds for axis 0 with size 7

The error above occurs when you access the second element which is 10. When i=10, you use it as mylist[10] which throws error because the length of mylist is 7 because it has 7 elements.

Correct way:

for i in mylist:
    plt.axvline(i)


问:
How to use Zero-copy sendmsg/Receive in Boost.Asio
I am using Boost.Asio,
I want to improve my system by using Zero-copy sendmsg/Receive.
Can I use Zero-copy sendmsg/Receive in Boost.Asio?
Could you give me how to use them if I can use them?</p>

答:
Short answer, you can only if your in-memory representation is identical to the on-the-wire one.

See the answers here, which do an excellent job of describing how e.g. Cap'n Proto achieves this:

Do cereal and Boost Serialization use zero-copy?

Also compare:

TCP Zero copy using boost

And on creating memory-mappable representations of advanced C++ data structures so that they can be mapped on-the-wire:

https://www.boost.org/doc/libs/1_72_0/doc/html/interprocess/managed_memory_segments.html#interprocess.managed_memory_segments.making_ipc_easy.managed_memory_segments_intro, specifically about basic_managed_heap_memory and basic_managed_external_buffer

I have a gazillion examples on this site which show how to use such managed memory segments, but usually focused on managed_mapped_file and managed_shared_memory which have the exact same feature set, so you can use these with the previous managed heap segments in the same way: https://stackoverflow.com/search?q=user%3A85371+interprocess+allocator


问:
How do I reference Heroko Config Variables in Rails App
So I've created a few variables to store API key and secrets in. But I don't understand how I'm supposed to reference those variables in my code. When I try to push up my code to Heroku it says that I have undefined constant variables. Which yes I do. So what do I have to do here?</p>

答:
Heroku's config vars are exposed to your app’s code as environmental variables. In Ruby you can access env vars through the ENV hash. This is actually just a plain old hash.

You can either use the normal bracket accessors or Hash#key:

```<code>ENV['MY_SECRET_KEY']      # string / nil
ENV.key('MY_SECRET_KEY')  # string / nil
ENV.key?('MY_SECRET_KEY') # true / false
</code>```

You can also use Hash#fetch which lets you either raise an error if the key is missing or provide a default value:

```<code>ENV.fetch('MY_SECRET_KEY')             # raises a KeyError if the var is not set
ENV.fetch('MY_SECRET_KEY', 'abcd1234') # provides a default value
</code>```

Raising an error can really help with troubleshooting as it will fail fast and tell you exactly where the problem is.

Body:
Heroku's config vars are exposed to your app’s code as environmental variables. In Ruby you can access env vars through the ENV hash. This is actually just a plain old hash.

You can either use the normal bracket accessors or Hash#key:

ENV['MY_SECRET_KEY']      # string / nil
ENV.key('MY_SECRET_KEY')  # string / nil
ENV.key?('MY_SECRET_KEY') # true / false

You can also use Hash#fetch which lets you either raise an error if the key is missing or provide a default value:

ENV.fetch('MY_SECRET_KEY')             # raises a KeyError if the var is not set
ENV.fetch('MY_SECRET_KEY', 'abcd1234') # provides a default value

Raising an error can really help with troubleshooting as it will fail fast and tell you exactly where the problem is.


问:
createUser is not a function error while wriiting unit test?
I am getting below error while writing unit test case of my function.

```<code>(0 , _service.createUser) is not a function

TypeError: (0 , _service.createUser) is not a function
    at _callee$ (https://pbz00.csb.app/src/service.test.js:43:44)
    at tryCatch (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.<computed> [as next] (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:114:21)
</code>```

here is my function

```<code>export const createUser = async values => {
  try {
    const response = await axios.post("http:/10.13.15.245:3000/create", {
      values
    });
    console.log("response", response);
    if (response && response.data && response.data.status.code === "200") {
      abc = true;
      return abc;
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
    }
  }
};
</code>```

I want to check it's return value true or undefined.

here is my code
https://codesandbox.io/s/busy-galois-pbz00

```<code>import { createUser } from "./service.test";

describe("service test", () => {
  it("check abc value", async () => {
    const axios = {
      post: jest.fn(() =>
        Promise.resolve({
          data: {
            greeting: "hello there",
            status: {
              code: "200"
            }
          }
        })
      )
    };
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});
</code>```

```<code>import { createUser } from "./service";

describe("service test", () => {
  it("check abc value", async () => {
    jest.spyOn(axios, "post").mockImplementation(() =>
      Promise.resolve({
        data: {
          greeting: "hello there",
          status: {
            code: "200"
          }
        }
      })
    );
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});
</code>```

updated

```<code>import { createUser } from "./service";
import axios from "axios";
describe("service test", () => {
  it("check abc value", async () => {
    jest.spyOn(axios, "post").mockImplementation(() =>
      Promise.resolve({
        data: {
          greeting: "hello there",
          status: {
            code: "200"
          }
        }
      })
    );
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});
</code>```

答:
You are importing it wrong. It should be:

import { createUser } from "./service";
```

<p>to mock <code>axios</code> module, you can use this:</p>

```jest
  .spyOn(axios, 'post')
  .mockImplementation(() => Promise.resolve({
     data: {
       greeting: "hello there",
       status: {
        code: "200"
       }
     }
  }))
```

You could also mock the whole module: https://jestjs.io/docs/en/mock-functions.html#mocking-modules

Body:
I am getting below error while writing unit test case of my function.

(0 , _service.createUser) is not a function

TypeError: (0 , _service.createUser) is not a function
    at _callee$ (https://pbz00.csb.app/src/service.test.js:43:44)
    at tryCatch (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:288:22)
    at Generator.prototype.<computed> [as next] (https://pbz00.csb.app/node_modules/regenerator-runtime/runtime.js:114:21)

here is my function

export const createUser = async values => {
  try {
    const response = await axios.post("http:/10.13.15.245:3000/create", {
      values
    });
    console.log("response", response);
    if (response && response.data && response.data.status.code === "200") {
      abc = true;
      return abc;
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
    }
  }
};

I want to check it's return value true or undefined.

here is my code
https://codesandbox.io/s/busy-galois-pbz00

import { createUser } from "./service.test";

describe("service test", () => {
  it("check abc value", async () => {
    const axios = {
      post: jest.fn(() =>
        Promise.resolve({
          data: {
            greeting: "hello there",
            status: {
              code: "200"
            }
          }
        })
      )
    };
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});

import { createUser } from "./service";

describe("service test", () => {
  it("check abc value", async () => {
    jest.spyOn(axios, "post").mockImplementation(() =>
      Promise.resolve({
        data: {
          greeting: "hello there",
          status: {
            code: "200"
          }
        }
      })
    );
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});

updated

import { createUser } from "./service";
import axios from "axios";
describe("service test", () => {
  it("check abc value", async () => {
    jest.spyOn(axios, "post").mockImplementation(() =>
      Promise.resolve({
        data: {
          greeting: "hello there",
          status: {
            code: "200"
          }
        }
      })
    );
    console.log("createUser", createUser);
    let abc = await createUser();
    console.log("after createUser", abc);
    expect(abc).toBe(true);
  });
});

Body:
You are importing it wrong. It should be:

import { createUser } from "./service";

to mock axios module, you can use this:

jest
  .spyOn(axios, 'post')
  .mockImplementation(() => Promise.resolve({
     data: {
       greeting: "hello there",
       status: {
        code: "200"
       }
     }
  }))

You could also mock the whole module: https://jestjs.io/docs/en/mock-functions.html#mocking-modules


问:
Invalid Output for Coursera Python Assignment
I'm doing the Coursera Python for Everybody stream and I'm stuck on Assignment 10.2. I'm getting invalid output for it. Here is what the assignment asks:

Write a program to read through the mbox-short.txt and figure out the
  distribution by hour of the day for each of the messages. You can pull
  the hour out from the 'From ' line by finding the time and then
  splitting the string a second time using a colon.

```<code>From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
</code>```

Once you have accumulated the counts for each hour, print out the
  counts, sorted by hour as shown below.

Here is my code:

```<code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()

for line in handle:
    line = line.rstrip()
    if not line.startswith('From '):
        continue
    words = line.split()
    words = words[5]
    words = words.split(":")
    for word in counts:
        counts[word] = counts.get(word, 0) + 1

lst = list()
for key, val in counts.items():
    lst.append((key, val))

lst.sort()

print lst
</code>```

Let me know what I'm doing wrong. Any advice or hint is appreciated.

答:
```<code>name =input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)

counts = dict()

for line in handle:
    if line.startswith("From "):
        time = line.split()[5].split(":")
        counts [time[0]] = counts.get(time[0], 0) + 1

#print sorted( [ (v,k) for k,v in counts.items()] )

list = list()

for key, value in counts.items():
    list.append( (key,value) )
list.sort()

for hour, counts in list:
    print (hour, counts)
</code>```

Body:
I'm doing the Coursera Python for Everybody stream and I'm stuck on Assignment 10.2. I'm getting invalid output for it. Here is what the assignment asks:

Write a program to read through the mbox-short.txt and figure out the
  distribution by hour of the day for each of the messages. You can pull
  the hour out from the 'From ' line by finding the time and then
  splitting the string a second time using a colon.

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

Once you have accumulated the counts for each hour, print out the
  counts, sorted by hour as shown below.

Here is my code:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()

for line in handle:
    line = line.rstrip()
    if not line.startswith('From '):
        continue
    words = line.split()
    words = words[5]
    words = words.split(":")
    for word in counts:
        counts[word] = counts.get(word, 0) + 1

lst = list()
for key, val in counts.items():
    lst.append((key, val))

lst.sort()

print lst

Let me know what I'm doing wrong. Any advice or hint is appreciated.


问:
Didn't find class "android.view.menu"
I have been getting the following problem:

Caused by: android.view.InflateException: Binary XML file line #13: Binary XML file line #2: Error inflating class menu
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class menu
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.menu" on path: DexPathList[[zip file "/data/app/com.cpsc4150.glovebox-xjT3LiC43G5FDyD3dDmxuw==/base.apk"],nativeLibraryDirectories=[/data/app/com.cpsc4150.glovebox-xjT3LiC43G5FDyD3dDmxuw==/lib/x86, /system/lib]]

I have tried cleaning the build, deleting build files and having android studio remake them ect. No f which seem to work.

My menu file is in res/menu/menu.xml and is the only thing located there.

MainActivity

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    /**
     * <p>Defines the actions to be taken when the menu activity is created</p>
     * @param savedInstanceState a saved instance of the menu activity id one exist
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int REQUEST_ALL = 1;
        String[] PERMISSIONS = {
                android.Manifest.permission.WAKE_LOCK,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.CAMERA
        };

        if (hasPermissions(this, PERMISSIONS) == false) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_ALL);
        }

        serviceList = loadServices(SERVICE_LIST_ID);
        if (serviceList == null) serviceList = new ArrayList<>();
        inProgressList = loadServices(IN_PROGRESS_LIST_ID);
        if (inProgressList == null) inProgressList = new ArrayList<>();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setOnTabSelectedListener(tabListener);
</code>```

menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:layout_height="?attr/actionBarSize"
    xmlns:appcompat="http://schemas.android.com/apk/res-auto">
<!--        <item android:id="@+id/privacyPolicy"-->
<!--            android:title="Privacy Policy"-->
<!--            android:icon="@drawable/ic_more_vert_black_24dp"-->
<!--            app:showAsAction="always"></item>-->

</menu>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:backgroundTint="@color/appBackground"
    android:background="@color/appBackground"

    >
<include
    layout="@menu/menu"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>
</code>```

答:
Remove:

```<code><include
    layout="@menu/menu"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>
</code>```

<include> is only for including layout resources, not menu resources.

Title: Didn't find class "android.view.menu"

Body:
I have been getting the following problem:

Caused by: android.view.InflateException: Binary XML file line #13: Binary XML file line #2: Error inflating class menu
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class menu
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.menu" on path: DexPathList[[zip file "/data/app/com.cpsc4150.glovebox-xjT3LiC43G5FDyD3dDmxuw==/base.apk"],nativeLibraryDirectories=[/data/app/com.cpsc4150.glovebox-xjT3LiC43G5FDyD3dDmxuw==/lib/x86, /system/lib]]

I have tried cleaning the build, deleting build files and having android studio remake them ect. No f which seem to work.

My menu file is in res/menu/menu.xml and is the only thing located there.

MainActivity

@Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    /**
     *
Defines the actions to be taken when the menu activity is created

     * @param savedInstanceState a saved instance of the menu activity id one exist
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int REQUEST_ALL = 1;
        String[] PERMISSIONS = {
                android.Manifest.permission.WAKE_LOCK,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.CAMERA
        };

        if (hasPermissions(this, PERMISSIONS) == false) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_ALL);
        }

        serviceList = loadServices(SERVICE_LIST_ID);
        if (serviceList == null) serviceList = new ArrayList<>();
        inProgressList = loadServices(IN_PROGRESS_LIST_ID);
        if (inProgressList == null) inProgressList = new ArrayList<>();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setOnTabSelectedListener(tabListener);

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:layout_height="?attr/actionBarSize"
    xmlns:appcompat="http://schemas.android.com/apk/res-auto">

</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:backgroundTint="@color/appBackground"
    android:background="@color/appBackground"

    >
<include
    layout="@menu/menu"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

Body:
Remove:

<include
    layout="@menu/menu"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

<include> is only for including layout resources, not menu resources.


问:
Error running npm command on Windows: graceful-fs
I have a ReactJS project and I was trying to use some of the PrimeReact components. At some point, I faced an error (can't remember exactly which one) and I tried to run an older version of NPM in a copy of my main directory.

Now, I get this error every time, even when I run npm command.

I've already tried to delete my node_modules folder, delete my project and clone it back from GitHub and also to reinstall NodeJS several times. I don't know what to do!

I have Windows 10 and I'm using NodeJS v12.16.0.

Thanks to anyone that offers some help

Update: I have never installed gulp. I suppose that maybe some dependency is using it but, because I can't run any npm command, I can't remove them D:

The error:

```<code>C:\Users\Carlos>npm
evalmachine.<anonymous>:35
} = primordials;
    ^

ReferenceError: primordials is not defined
    at evalmachine.<anonymous>:35:5
    at Object.<anonymous> (C:\Users\Carlos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-registry-client\node_modules\graceful-fs\fs.js:12:1)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load (internal/modules/cjs/loader.js:900:14)
    at Module.require (internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (C:\Users\Carlos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-registry-client\node_modules\graceful-fs\graceful-fs.js:3:27)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)
</code>```

答:
It might be an error related with gulp and node v12 conflict. If you have the gulp installed globally in your environment and you can uninstall without problems, you can try it. To help with commands, check if you have the gulp installed, typing this in your command line interface:

```<code>gulp -v
</code>```

Uninstall your version:

```<code>npm uninstall -g gulp
</code>```

Body:
I have a ReactJS project and I was trying to use some of the PrimeReact components. At some point, I faced an error (can't remember exactly which one) and I tried to run an older version of NPM in a copy of my main directory.

Now, I get this error every time, even when I run npm command.

I've already tried to delete my node_modules folder, delete my project and clone it back from GitHub and also to reinstall NodeJS several times. I don't know what to do!

I have Windows 10 and I'm using NodeJS v12.16.0.

Thanks to anyone that offers some help

Update: I have never installed gulp. I suppose that maybe some dependency is using it but, because I can't run any npm command, I can't remove them D:

The error:

C:\Users\Carlos>npm
evalmachine.<anonymous>:35
} = primordials;
    ^

ReferenceError: primordials is not defined
    at evalmachine.<anonymous>:35:5
    at Object.<anonymous> (C:\Users\Carlos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-registry-client\node_modules\graceful-fs\fs.js:12:1)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load (internal/modules/cjs/loader.js:900:14)
    at Module.require (internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (C:\Users\Carlos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-registry-client\node_modules\graceful-fs\graceful-fs.js:3:27)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)

Body:
It might be an error related with gulp and node v12 conflict. If you have the gulp installed globally in your environment and you can uninstall without problems, you can try it. To help with commands, check if you have the gulp installed, typing this in your command line interface:

gulp -v

Uninstall your version:

npm uninstall -g gulp


问:
Calculate Custom Rate Function in a Pandas Data Frame Using GroupBy
I have a Pandas data frame with the column COLOR containing categorical data and NaN values -

```<code>  ZIP    YEAR    COLOR
11111    1990        0
11111    1990        1
11111    1990      NaN
11111    1990        1
22222    2000        0
22222    2000      NaN
22222    2000      NaN
22222    2000        1
</code>```

How do I aggregate the data by the ZIP and YEAR columns (df.groupby(['ZIP', 'YEAR'])) and calculate the categorical data as a rate such that the result resembles the data frame below? The rate should be calculated as the number of zeroes divided by the total number of records for each aggregate. For example, the rate for df.groupby(['ZIP', 'YEAR']) for [11111, 1990] is calculated by adding up the total number of zeroes (1) and dividing that number by the sum of the total number of zeroes and ones (3), resulting in 1/3 as 0.33.

```<code>  ZIP    YEAR    COLOR
11111    1990     0.33
22222    2000     0.50
</code>```

答:
First we convert your 0 to 1 and other way around.

Then we use GroupBy.sum and GroupBy.count:

```<code>df['COLOR'] = df['COLOR'].sub(1).abs()

grps = df.groupby(['ZIP', 'YEAR'])
dfn = grps.sum().div(grps.count()).reset_index()

     ZIP  YEAR     COLOR
0  11111  1990  0.333333
1  22222  2000  0.500000
</code>```

Body:
I have a Pandas data frame with the column COLOR containing categorical data and NaN values -

  ZIP    YEAR    COLOR
11111    1990        0
11111    1990        1
11111    1990      NaN
11111    1990        1
22222    2000        0
22222    2000      NaN
22222    2000      NaN
22222    2000        1

How do I aggregate the data by the ZIP and YEAR columns (df.groupby(['ZIP', 'YEAR'])) and calculate the categorical data as a rate such that the result resembles the data frame below? The rate should be calculated as the number of zeroes divided by the total number of records for each aggregate. For example, the rate for df.groupby(['ZIP', 'YEAR']) for [11111, 1990] is calculated by adding up the total number of zeroes (1) and dividing that number by the sum of the total number of zeroes and ones (3), resulting in 1/3 as 0.33.

  ZIP    YEAR    COLOR
11111    1990     0.33
22222    2000     0.50

Body:
First we convert your 0 to 1 and other way around.

Then we use GroupBy.sum and GroupBy.count:

df['COLOR'] = df['COLOR'].sub(1).abs()

grps = df.groupby(['ZIP', 'YEAR'])
dfn = grps.sum().div(grps.count()).reset_index()

     ZIP  YEAR     COLOR
0  11111  1990  0.333333
1  22222  2000  0.500000