问:
How to count in multiple columns a variable
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

```<code>UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill
</code>```

I need to produce a productivity report like below

```<code>        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3
</code>```

I am not sure how to group the counts by the names that are in the data?

答:
If it isn't massive you can use chained CTE's:</p>

```<code>DECLARE @activity AS TABLE
  (
       [uid]        INT
       , [approved] NVARCHAR(25)
       , [denied]   NVARCHAR(25)
       , [moved]    NVARCHAR(25)
       , [pending]  NVARCHAR(25)
  );

INSERT INTO @activity
            ([uid]
             , [approved]
             , [denied]
             , [moved]
             , [pending])
VALUES      (1,N'Curly',NULL,NULL,NULL),
            (2,NULL,NULL,N'Curly',NULL),
            (3,N'Curly',NULL,NULL,N'Mo'),
            (4,NULL,NULL,N'Joe',NULL),
            (5,N'Joe',NULL,N'Joe',NULL),
            (6,N'Joe',N'Shemp',N'Joe',NULL);

WITH [approved_builder]
     AS (SELECT [approved] AS [name]
                , count(*) AS [approved]
         FROM   @activity
         WHERE  [approved] IS NOT NULL
         GROUP  BY [approved])
   , [moved_builder]
     AS (SELECT [moved]    AS [name]
                , count(*) AS [moved]
         FROM   @activity
         WHERE  [moved] IS NOT NULL
         GROUP  BY [moved])
   , [denied_builder]
     AS (SELECT [denied]   AS [name]
                , count(*) AS [denied]
         FROM   @activity
         WHERE  [denied] IS NOT NULL
         GROUP  BY [denied])
   , [pending_builder]
     AS (SELECT [pending]  AS [name]
                , count(*) AS [pending]
         FROM   @activity
         WHERE  [pending] IS NOT NULL
         GROUP  BY [pending])
   , [aggregator]
     AS (SELECT [name]
                , [approved] AS [approved]
                , 0          AS [denied]
                , 0          AS [moved]
                , 0          AS [pending]
         FROM   [approved_builder]
         UNION ALL
         SELECT [name]
                , 0       AS [approved]
                , 0       AS [denied]
                , [moved] AS [moved]
                , 0       AS [pending]
         FROM   [moved_builder]
         UNION ALL
         SELECT [name]
                , 0        AS [approved]
                , [denied] AS [denied]
                , 0        AS [moved]
                , 0        AS [pending]
         FROM   [denied_builder]
         UNION ALL
         SELECT [name]
                , 0         AS [approved]
                , 0         AS [denied]
                , 0         AS [moved]
                , [pending] AS [pending]
         FROM   [pending_builder])
SELECT [name]            AS [name]
       , sum([approved]) AS [approved]
       , sum([denied])   AS [denied]
       , sum([moved])    AS [moved]
       , sum([pending])  AS [pending]
FROM   [aggregator]
GROUP  BY [name];
</code>```

Body:
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill

I need to produce a productivity report like below

        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3

I am not sure how to group the counts by the names that are in the data?

Body:
If it isn't massive you can use chained CTE's:

DECLARE @activity AS TABLE
  (
       [uid]        INT
       , [approved] NVARCHAR(25)
       , [denied]   NVARCHAR(25)
       , [moved]    NVARCHAR(25)
       , [pending]  NVARCHAR(25)
  );

INSERT INTO @activity
            ([uid]
             , [approved]
             , [denied]
             , [moved]
             , [pending])
VALUES      (1,N'Curly',NULL,NULL,NULL),
            (2,NULL,NULL,N'Curly',NULL),
            (3,N'Curly',NULL,NULL,N'Mo'),
            (4,NULL,NULL,N'Joe',NULL),
            (5,N'Joe',NULL,N'Joe',NULL),
            (6,N'Joe',N'Shemp',N'Joe',NULL);

WITH [approved_builder]
     AS (SELECT [approved] AS [name]
                , count(*) AS [approved]
         FROM   @activity
         WHERE  [approved] IS NOT NULL
         GROUP  BY [approved])
   , [moved_builder]
     AS (SELECT [moved]    AS [name]
                , count(*) AS [moved]
         FROM   @activity
         WHERE  [moved] IS NOT NULL
         GROUP  BY [moved])
   , [denied_builder]
     AS (SELECT [denied]   AS [name]
                , count(*) AS [denied]
         FROM   @activity
         WHERE  [denied] IS NOT NULL
         GROUP  BY [denied])
   , [pending_builder]
     AS (SELECT [pending]  AS [name]
                , count(*) AS [pending]
         FROM   @activity
         WHERE  [pending] IS NOT NULL
         GROUP  BY [pending])
   , [aggregator]
     AS (SELECT [name]
                , [approved] AS [approved]
                , 0          AS [denied]
                , 0          AS [moved]
                , 0          AS [pending]
         FROM   [approved_builder]
         UNION ALL
         SELECT [name]
                , 0       AS [approved]
                , 0       AS [denied]
                , [moved] AS [moved]
                , 0       AS [pending]
         FROM   [moved_builder]
         UNION ALL
         SELECT [name]
                , 0        AS [approved]
                , [denied] AS [denied]
                , 0        AS [moved]
                , 0        AS [pending]
         FROM   [denied_builder]
         UNION ALL
         SELECT [name]
                , 0         AS [approved]
                , 0         AS [denied]
                , 0         AS [moved]
                , [pending] AS [pending]
         FROM   [pending_builder])
SELECT [name]            AS [name]
       , sum([approved]) AS [approved]
       , sum([denied])   AS [denied]
       , sum([moved])    AS [moved]
       , sum([pending])  AS [pending]
FROM   [aggregator]
GROUP  BY [name];


来源: stackexchange

问:
AWS - is there a way to receive events asynchronously without the lambda
I have a general AWS question. I have started using AWS sdk, but looks like if I want to receive events asynchronously from AWS(ex: cloudwatch events), lambda functions is the only way. I want to write a simple application that registers a callback to AWS for events, but i couldn't find a way to do that till now, since i don't want to use lambda, i have been polling from my application. Please, let me know if polling is the only option or if there is a better way to resolve it without polling.</p>

答:
Already above answers might also be helpful, but one of the possible options to address your problem could be one of this as well.

You can make use of AWS SNS service to subscribe for the events on AWS resources. And the SNS can publish the events to your application end point. Which is nothing but pub/sub model.

Refer this link http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html

The end-point could be your http or https based application.

ContentLicense: CC BY-SA 3.0


问:
Python skipping XML child nodes while parsing in BeautifulSoup
I'm running into a problem where a certain group of child tags aren't parsing fully. I follow the same logic as this with other tags but for reasons I cannot see it's skipping all but the first entries of the tags I want. A basic snippet of my current script looks something like this:

```<code>for xml_string in separated_xml(infile):

   soup = BeautifulSoup(xml_string, "lxml")

        us_grant = soup.findAll("us-patent-grant")

        with open('./output.csv', 'ab+') as f:
            writer = csv.writer(f, dialect = 'excel')

            for info in us_grant:

              data = []
              us_class_search = soup.findAll("us-field-of-classification-search")

              for item2 in us_class_search:

                if item2.find("classification-national"):

                  country_search = item2.find("country")
                  main_class_search = item2.find("main-classification")

                  data.append((country_search).text)
                  data.append((main_class_search).text)
              print(data)
</code>```

Once I print(data) after each iteration it only gives me the first entry of each country and main-classification tag under every us-patent-grant parent; but there are many more. For example the XML file with these tags looks like:

```<code><us-field-of-classification-search>
<classification-national>
<country>US</country>
<main-classification>D 1100-130</main-classification>
<additional-info>unstructured</additional-info>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>D 1199</main-classification>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>426  5</main-classification>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>426 76</main-classification>
</classification-national>
</us-field-of-classification-search>
</code>```

I know that the if item2 statement does not follow through correctly because even if I take it out it still runs the for item2 loop the same way; finding and appending only the first tags under each. This means it must be the loop itself not running through and finding each instance and treating the first tag as all of them.

Any ideas? I don't see any obvious fault in logic.

If you'd like to see the XML itself you can find it here on USPTO

答:
Simple fix when introducing the for-loop:

```<code>for items in item2.findAll("classification-national")
</code>```

Allowed me to hit every component inside the parent.

Body:
I'm running into a problem where a certain group of child tags aren't parsing fully. I follow the same logic as this with other tags but for reasons I cannot see it's skipping all but the first entries of the tags I want. A basic snippet of my current script looks something like this:

for xml_string in separated_xml(infile):

   soup = BeautifulSoup(xml_string, "lxml")

        us_grant = soup.findAll("us-patent-grant")

        with open('./output.csv', 'ab+') as f:
            writer = csv.writer(f, dialect = 'excel')

            for info in us_grant:

              data = []
              us_class_search = soup.findAll("us-field-of-classification-search")

              for item2 in us_class_search:

                if item2.find("classification-national"):

                  country_search = item2.find("country")
                  main_class_search = item2.find("main-classification")

                  data.append((country_search).text)
                  data.append((main_class_search).text)
              print(data)

Once I print(data) after each iteration it only gives me the first entry of each country and main-classification tag under every us-patent-grant parent; but there are many more. For example the XML file with these tags looks like:

<us-field-of-classification-search>
<classification-national>
<country>US</country>
D 1100-130
<additional-info>unstructured</additional-info>
</classification-national>
<classification-national>
<country>US</country>
D 1199
</classification-national>
<classification-national>
<country>US</country>
426  5
</classification-national>
<classification-national>
<country>US</country>
426 76
</classification-national>
</us-field-of-classification-search>

I know that the if item2 statement does not follow through correctly because even if I take it out it still runs the for item2 loop the same way; finding and appending only the first tags under each. This means it must be the loop itself not running through and finding each instance and treating the first tag as all of them.

Any ideas? I don't see any obvious fault in logic.

If you'd like to see the XML itself you can find it here on USPTO

Body:
Simple fix when introducing the for-loop:

for items in item2.findAll("classification-national")

Allowed me to hit every component inside the parent.


问:
Best way to handle file uploads through HTTP
File uploads through web pages using the standard HTML  input always seems clunky to me.  If the user tries to upload a large file, it can go on forever and they get no queue that the file is actually being uploaded.

I have tried to do things like provide a gif graphic that is an animated graphic bar, but it doesn't give the user any indication of how much is uploaded.  I have even tried to do a progress bar with AJAX, but those were always ugly and never seemed to work right.

This has been an issue with many of my clients, and often I'm asked if there is a better way.  Sometimes I'll just provide them an FTP site so they can upload it there, but that's not a practical solution either.

What do you think the best way to handle HTTP file uploads from HTML is?  What are some good ideas / examples you have seen around the internet?

答: Interesting, no one has mentioned NeatUpload upload component by Dean Brettle, it has lots of interesting features and runs on MONO, too</p>

OwnerDisplayName: Ryan Smith

ContentLicense: CC BY-SA 2.5


问:
Infinite Linked List issue
I'm trying to construct a node list, and I believe the list turns into a loop, but I cannot figure out how! Below are the two methods that are used to do this.

GraphNode Class

```<code>public class GraphNode {
public int nodeID;
public int color;
public int numEdges;
public GraphNode next;

public GraphNode() {
    nodeID = 0;
    color = 0;
    numEdges = 0;
    next = null;
}

public GraphNode(int id, int e) {
    nodeID = id;
    color = 0;
    numEdges = e;
    next = null;
}

public void setNext (GraphNode next) { this.next = next; } }
</code>```

constructNodeList method (numNodes = 19, it reads from input file)

```<code>public void constructNodeList(GraphNode p) {
    int edgeCount;
    for (int i = 0; i < numNodes; i++) {
        edgeCount = 0;
        for (int j = 0; j < numNodes; j++) {
            System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
            if (adjMatrix[i][j] == 1) edgeCount++;
        }
        p.nodeID = i+1;
        p.numEdges = edgeCount;
        System.out.println(p.nodeID + ": " + p.numEdges);
        insertOneNode(p);
    }
}
</code>```

insertOneNode method

```<code>public void insertOneNode(GraphNode newNode) {
    GraphNode current = listHead;
GraphNode temp = current;

    while (current.next != null && newNode.numEdges > current.next.numEdges) {
        current = current.next;
    }
    if (current.next == null) current.setNext(newNode);
    else {
        temp = current.next;
        current.setNext(newNode);
        newNode.next = temp;
    }
}
</code>```

This should insert each node in ascending order by the numEdges in each node. But when I try to print out the linked list after each insert, it prints out an unlimited amount of what I believe to be the first node in the list.

答:
After almost an entire day of asking people, searching online, etc, one person finally knew what was wrong.

Such a simple thing, as usual! The constructNodeList method re-uses the same node every time! So the same node gets re-written, creating the same "next" node of the inserted node. So, to fix this, the new method is now:

```<code>public void constructNodeList() {
    int edgeCount;
    for (int i = 0; i < numNodes; i++) {
        edgeCount = 0;
        for (int j = 0; j < numNodes; j++) {
            //System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
            if (adjMatrix[i][j] == 1 && i != j) edgeCount++;
        }
        GraphNode p = new GraphNode(); // new node every time!
        p.nodeID = i+1;
        p.numEdges = edgeCount;
        System.out.println(p.nodeID + ": " + p.numEdges);
        insertOneNode(p);
    }
}
</code>```

Title: Infinite Linked List issue

Body:
I'm trying to construct a node list, and I believe the list turns into a loop, but I cannot figure out how! Below are the two methods that are used to do this.

GraphNode Class

public class GraphNode {
public int nodeID;
public int color;
public int numEdges;
public GraphNode next;

public GraphNode() {
    nodeID = 0;
    color = 0;
    numEdges = 0;
    next = null;
}

public GraphNode(int id, int e) {
    nodeID = id;
    color = 0;
    numEdges = e;
    next = null;
}

public void setNext (GraphNode next) { this.next = next; } }

constructNodeList method (numNodes = 19, it reads from input file)

public void constructNodeList(GraphNode p) {
    int edgeCount;
    for (int i = 0; i < numNodes; i++) {
        edgeCount = 0;
        for (int j = 0; j < numNodes; j++) {
            System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
            if (adjMatrix[i][j] == 1) edgeCount++;
        }
        p.nodeID = i+1;
        p.numEdges = edgeCount;
        System.out.println(p.nodeID + ": " + p.numEdges);
        insertOneNode(p);
    }
}

insertOneNode method

public void insertOneNode(GraphNode newNode) {
    GraphNode current = listHead;
GraphNode temp = current;

    while (current.next != null && newNode.numEdges > current.next.numEdges) {
        current = current.next;
    }
    if (current.next == null) current.setNext(newNode);
    else {
        temp = current.next;
        current.setNext(newNode);
        newNode.next = temp;
    }
}

This should insert each node in ascending order by the numEdges in each node. But when I try to print out the linked list after each insert, it prints out an unlimited amount of what I believe to be the first node in the list.

Body:
After almost an entire day of asking people, searching online, etc, one person finally knew what was wrong.

Such a simple thing, as usual! The constructNodeList method re-uses the same node every time! So the same node gets re-written, creating the same "next" node of the inserted node. So, to fix this, the new method is now:

public void constructNodeList() {
    int edgeCount;
    for (int i = 0; i < numNodes; i++) {
        edgeCount = 0;
        for (int j = 0; j < numNodes; j++) {
            //System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
            if (adjMatrix[i][j] == 1 && i != j) edgeCount++;
        }
        GraphNode p = new GraphNode(); // new node every time!
        p.nodeID = i+1;
        p.numEdges = edgeCount;
        System.out.println(p.nodeID + ": " + p.numEdges);
        insertOneNode(p);
    }
}


问:
How can I detect whether an iframe is loaded?
I am trying to check whether an iframe has loaded after the user clicks a button.

I have

```<code>$('#MainPopupIframe').load(function(){
    console.log('load the iframe')
    //the console won't show anything even if the iframe is loaded.
})
</code>```

HTML

```<code><button id='click'>click me</button>

//the iframe is created after the user clicks the button.
<iframe id='MainPopupIframe' src='http://...' />...</iframe>
</code>```

Any suggestions?

By the way, my iframe is created dynamically. It doesn’t load with the initial page load.

答:
You can try onload event as well;</p>

```<code>var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };
</code>```

Body:
I am trying to check whether an iframe has loaded after the user clicks a button.

I have

$('#MainPopupIframe').load(function(){
    console.log('load the iframe')
    //the console won't show anything even if the iframe is loaded.
})

HTML

<button id='click'>click me</button>

//the iframe is created after the user clicks the button.
...

Any suggestions?

By the way, my iframe is created dynamically. It doesn’t load with the initial page load.

Body:
You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };


问:
Make tab switching conditional
I have a basic TAB interface and was wondering if there is a way upon tab click, to check a condition. Depending on the condition we go ahead with the tab change or not.

Looking at the methods available, i could not find anything that would help me.

onChange and onTabClick do not seem to work for what im trying to do, any ideas ?

Thanks!

答:
Whatever element you have focus on, you can use the onKeyDown prop. Then, just check the condition to call preventDefault()

```<code>onKeyDown = (event) => {
  if (condition) event.preventDefault()
}
</code>```

Title: Make tab switching conditional

Body:
Whatever element you have focus on, you can use the onKeyDown prop. Then, just check the condition to call preventDefault()

onKeyDown = (event) => {
  if (condition) event.preventDefault()
}


问:
Verify that all values for a kubernetes helm chart have been used
I'd like to check that my kubernetes helm chart does not define unused values in values.yaml. This should include any subcharts such that if you've defined subchart.foo.bar: ??? in the top-level values.yaml that key is definitely used in the subchart, or possibly as a short-cut mentioned in the subchart/values.yaml.

This is needed to prevent us from shipping bogus "documentation" in the values.yaml, for example if a key in a subchart has been changed or removed.

Ideally there would also be some possibility to report on which subchart values have not been overridden in the top-level chart, though this is less concerning.

Are there any existing tools that can help with this?

答: AFAIK, there isn't a tool for that. However, it shouldn't be that hard to make one, even using bash. For example, you need to export all key/value pairs like this test.test1.test2 and grep for that string recursively in the templates folder. If you want to read yaml using bash, you can install shyaml. If you know how to code in Python, even better.


问:
Storing 3D data with Eigen library
How can I store a 3D data using Eigen C++ library? Vector is for 1D data, Matrix is for 2D data but what is for a 3D data? Or is it possible to create a vector of matrix?</p>

答:
You could use the Tensor module. It is not yet stable though.

```<code>Eigen::Tensor<double, 3> epsilon(4,5,6);  // 3 dimensions (4x5x6)
epsilon.setZero();
epsilon(0,1,2) = 1;
epsilon(0,2,1) = -1;
</code>```

http://eigen.tuxfamily.org/index.php?title=Tensor_support

ContentLicense: CC BY-SA 4.0

Title: Storing 3D data with Eigen library

Body:
You could use the Tensor module. It is not yet stable though.

Eigen::Tensor<double, 3> epsilon(4,5,6);  // 3 dimensions (4x5x6)
epsilon.setZero();
epsilon(0,1,2) = 1;
epsilon(0,2,1) = -1;

http://eigen.tuxfamily.org/index.php?title=Tensor_support


问:
Generate all combination of elements in table (langage C)
i have i table of integer

```<code>int Table[]={1,2,3,....,28};
</code>```

i want to have this combination:

```<code>1 2 3 4 5 6 7 ... 28
</code>```

and after i will have this

```<code>12 13 14 15 16 17 18 19 23 24 24 .....
</code>```

until to have all combination possible without repetition (i.e 12=21)

I want combination like they are made in excel columns for example

```<code>char alp[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'
,'Q','R','S','T','U','V','W','X','Y','Z'};
</code>```

答:
This Problem can be solved like this:

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

void swp(char* array, int index_1, int index_2)
{
    char tmp = array[index_1];
    array[index_1] = array[index_2];
    array[index_2] = tmp;
}

void perm(char* array, int start, int end)
{
    if (start == end)
        printf("%s\n", array);
    else
    {
        for (int i = start; i <= end; i++)
        {
            swp(array, start, i);
            perm(array, start + 1, end);
            swp(array, start, i);
        }
    }
}

void main(void)
{
    char s[] = "Banana";
    perm(s, 0, 5);
}
</code>```

We basically start with swapping the first Elemen with other elements, we use the loop so every choice we could do in the first swap is computed in the end.
When we do one iteration, say swapping the first element with itself in the very first iteration, we call perm() recursively and continue on that decision, after we return from the recursion we have to undo the swap so the untouched array can proceed the iteration.

Body:
i have i table of integer

int Table[]={1,2,3,....,28};

i want to have this combination:

1 2 3 4 5 6 7 ... 28

and after i will have this

12 13 14 15 16 17 18 19 23 24 24 .....

until to have all combination possible without repetition (i.e 12=21)

I want combination like they are made in excel columns for example

char alp[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'
,'Q','R','S','T','U','V','W','X','Y','Z'};

Body:
This Problem can be solved like this:

#include <stdio.h>

void swp(char* array, int index_1, int index_2)
{
    char tmp = array[index_1];
    array[index_1] = array[index_2];
    array[index_2] = tmp;
}

void perm(char* array, int start, int end)
{
    if (start == end)
        printf("%s\n", array);
    else
    {
        for (int i = start; i <= end; i++)
        {
            swp(array, start, i);
            perm(array, start + 1, end);
            swp(array, start, i);
        }
    }
}

void main(void)
{
    char s[] = "Banana";
    perm(s, 0, 5);
}

We basically start with swapping the first Elemen with other elements, we use the loop so every choice we could do in the first swap is computed in the end.
When we do one iteration, say swapping the first element with itself in the very first iteration, we call perm() recursively and continue on that decision, after we return from the recursion we have to undo the swap so the untouched array can proceed the iteration.


问:
How to TDD koa2 with mocha?
I'm trying to get a TDD workflow going with koa2/mocha/chai/chai-http but my problem is that when I run the tests the koa2 server keeps running after the tests are finished. So that I have to Ctrl+C (kill) it every time.

Can anyone tell me how to setup a TDD workflow where the server gets stopped after all tests are run?

Also, I'd like to watch the test files for changes and re-run the tests as soon as changes are detected... can anyone help with that? can't find anything on the net -.-

What I currently have (simplified):

package.json:

```<code>"scripts": {
   "watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node' ./src/server.ts",
   "test": "./node_modules/mocha/bin/mocha --compilers ts:ts-node/register test/**/*.ts"
},
</code>```

server.ts:

```<code>app.use(routes_v1.routes());

export const server = app.listen(3000, () => {
    console.log('Server running on port 3000');
});
</code>```

test:

```<code>process.env.NODE_ENV = 'test';

import * as chai from 'chai';
const chaiHttp = require('chai-http');

const should = chai.should();
chai.use(chaiHttp);

import { server } from '../../../src/server';

describe('routes : login / register', () => {
  describe('POST /sign_in', () => {
    it('should return unauthorized for invalid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: "test@test.de", password: "somePassword"})
      .end((err, res) => {
        res.status.should.eql(401);
        should.exist(err);
        done();
      });
    });

    it('should return authorized for valid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: 'authorized@test.de', password: "authorizedPassword"})
      .end((err, res) => {
        res.status.should.eql(200);
        should.exist(res.body.token);
        done();
      });
    });
  });
</code>```

Thank you.

答:
Starting from version 4.0 Mocha will no longer force the process to exit once all tests complete. You can use CLI parameter -exit to exit from the process when tests are finished:

```<code>"test": "mocha ... -exit"
</code>```

Or another option, which gives you more control over the process, is to use Hooks. So you can start the server before running test(s) and stop it after:

```<code>describe('...', () => {
  let server;

  before(() => {
    server = app.listen()
  });
  after(() => {
    server.close()
  });

  ...
})
</code>```

As an example, you can take a look at this test. It is using Jest and supertest, but idea is the same.

Title: How to TDD koa2 with mocha?

Body:
I'm trying to get a TDD workflow going with koa2/mocha/chai/chai-http but my problem is that when I run the tests the koa2 server keeps running after the tests are finished. So that I have to Ctrl+C (kill) it every time.

Can anyone tell me how to setup a TDD workflow where the server gets stopped after all tests are run?

Also, I'd like to watch the test files for changes and re-run the tests as soon as changes are detected... can anyone help with that? can't find anything on the net -.-

What I currently have (simplified):

package.json:

"scripts": {
   "watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node' ./src/server.ts",
   "test": "./node_modules/mocha/bin/mocha --compilers ts:ts-node/register test/**/*.ts"
},

server.ts:

app.use(routes_v1.routes());

export const server = app.listen(3000, () => {
    console.log('Server running on port 3000');
});

test:

process.env.NODE_ENV = 'test';

import * as chai from 'chai';
const chaiHttp = require('chai-http');

const should = chai.should();
chai.use(chaiHttp);

import { server } from '../../../src/server';

describe('routes : login / register', () => {
  describe('POST /sign_in', () => {
    it('should return unauthorized for invalid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: "test@test.de", password: "somePassword"})
      .end((err, res) => {
        res.status.should.eql(401);
        should.exist(err);
        done();
      });
    });

    it('should return authorized for valid user', (done) => {
      chai.request(server)
      .post('/sign_in')
      .send({email: 'authorized@test.de', password: "authorizedPassword"})
      .end((err, res) => {
        res.status.should.eql(200);
        should.exist(res.body.token);
        done();
      });
    });
  });

Thank you.

Body:
Starting from version 4.0 Mocha will no longer force the process to exit once all tests complete. You can use CLI parameter -exit to exit from the process when tests are finished:

"test": "mocha ... -exit"

Or another option, which gives you more control over the process, is to use Hooks. So you can start the server before running test(s) and stop it after:

describe('...', () => {
  let server;

  before(() => {
    server = app.listen()
  });
  after(() => {
    server.close()
  });

  ...
})

As an example, you can take a look at this test. It is using Jest and supertest, but idea is the same.


问:
applying a rule once only child selector maybe?
```<code>#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

how can only apply those rules to the first div with a class container?

答:
try this:

Please Note: For :first-child to work in IE, a DOCTYPE must be declared.(more info)

```<code>#mainContent .container div:first-child {
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

Body:
#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}

how can only apply those rules to the first div with a class container?

Body:
try this:

Please Note: For :first-child to work in IE, a DOCTYPE must be declared.(more info)

#mainContent .container div:first-child {
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}


问:
MS Access: query only one criteria in multiple criteria lookup field
I have a MS Access database that has a multiple criteria lookup field with entries like:

```<code>ID  Names
1   Carl, Daniel
2   Natalia
3   Carl, Natalia
4   Natalia, Carl
5   Carl
6   Natalia
7   Bob
8   Bob
9   Bob, Natalia
</code>```

I would like to write a query that only results in:

```<code>2   Natalia
6   Natalia
</code>```

I tried this code and it isn't working:

```<code>WHERE (((Table.Name)="Natalia"));
</code>```

This provides all the instances that include Natalia:

```<code>2   Natalia
3   Carl, Natalia
4   Natalia, Carl
6   Natalia
9   Bob, Natalia
</code>```

Thank you very much for your help.

答:
First, you should not be storing lists a delimnited strings.  The right way is a junction table, with one row per name.

Second, your WHERE clause (with the column name fixed) should do what you want:

```<code>WHERE Names = "Natalia"
</code>```

If you wanted all those other rows, you would use LIKE:

```<code>WHERE Names LIKE "*Natalia*"
</code>```

Body:
I have a MS Access database that has a multiple criteria lookup field with entries like:

ID  Names
1   Carl, Daniel
2   Natalia
3   Carl, Natalia
4   Natalia, Carl
5   Carl
6   Natalia
7   Bob
8   Bob
9   Bob, Natalia

I would like to write a query that only results in:

2   Natalia
6   Natalia

I tried this code and it isn't working:

WHERE (((Table.Name)="Natalia"));

This provides all the instances that include Natalia:

2   Natalia
3   Carl, Natalia
4   Natalia, Carl
6   Natalia
9   Bob, Natalia

Thank you very much for your help.

Body:
First, you should not be storing lists a delimnited strings.  The right way is a junction table, with one row per name.

Second, your WHERE clause (with the column name fixed) should do what you want:

WHERE Names = "Natalia"

If you wanted all those other rows, you would use LIKE:

WHERE Names LIKE "*Natalia*"


问:
RXJava Observable executing on main thread instead of background thread
I created an Observable using the Observable.fromCallable method and subscribed to it as shown in the code snippet below.

```<code>Observable<String> stringObservable = Observable.fromCallable(new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            return Thread.currentThread().getName();
        }
});

stringObservable.subscribeOn(Schedulers.io());
stringObservable.observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String aDouble) {
                Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
                Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(SimpleActivity.this)
                        .setTitle("Error")
                        .setMessage(e.toString())
                        .show();
            }

            @Override
            public void onComplete() {

            }
        });
</code>```

The snippet above produced a toast showing that the Callable was run on the main thread instead of the Schedulers.io thread. What's happening?

答:
Every operation on an Observable creates a new instance and does not effect the original one. Therefore

```<code>stringObservable.subscribeOn(Schedulers.io());
</code>```

does not affect your code below.

The correct way of using them would be in a chain instead of using a variable.

```<code>Observable.fromCallable(new Callable<String>() {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return Thread.currentThread().getName();
    }
}).subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String aDouble) {
            Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
            Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(Throwable e) {
            new AlertDialog.Builder(SimpleActivity.this)
                    .setTitle("Error")
                    .setMessage(e.toString())
                    .show();
        }

        @Override
        public void onComplete() {

        }
    });
</code>```

Body:
I created an Observable using the Observable.fromCallable method and subscribed to it as shown in the code snippet below.

Observable<String> stringObservable = Observable.fromCallable(new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            return Thread.currentThread().getName();
        }
});

stringObservable.subscribeOn(Schedulers.io());
stringObservable.observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String aDouble) {
                Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
                Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(SimpleActivity.this)
                        .setTitle("Error")
                        .setMessage(e.toString())
                        .show();
            }

            @Override
            public void onComplete() {

            }
        });

The snippet above produced a toast showing that the Callable was run on the main thread instead of the Schedulers.io thread. What's happening?

Body:
Every operation on an Observable creates a new instance and does not effect the original one. Therefore

stringObservable.subscribeOn(Schedulers.io());

does not affect your code below.

The correct way of using them would be in a chain instead of using a variable.

Observable.fromCallable(new Callable<String>() {
    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return Thread.currentThread().getName();
    }
}).subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String aDouble) {
            Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
            Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(Throwable e) {
            new AlertDialog.Builder(SimpleActivity.this)
                    .setTitle("Error")
                    .setMessage(e.toString())
                    .show();
        }

        @Override
        public void onComplete() {

        }
    });


问:
How to loop through a folder?
I want to loop through a folder and import all the files into Access.

This is my code:

```<code>Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine
Dim TextArray()
Dim x As Double
Dim SQLString

Set fso = CreateObject("Scripting.FileSystemObject")

FileName = "C:\Users\ava\Desktop\TEST_IMPORT\1.txt"

Set MyFile = fso.OpenTextFile(FileName, ForReading)

Do While MyFile.AtEndOfStream <> True
    ReDim Preserve TextArray(x)
    TextLine = MyFile.ReadLine
    TextArray(x) = TextLine
    x = x + 1
Loop

MyFile.Close

SQLString = "INSERT INTO TEST_TAB (Layout, Anzahl_Etiketten, Anzahl_Verpackungseinheiten, Bezeichnung1, Selektionsnummer, Bezeichnung2, Barcode, LA_Nummer, RM_Nummer, Bezeichnung3, Teilenummer) VALUES ('" & TextArray(0) & "','" & TextArray(1) & "','" & TextArray(4) & "','" & TextArray(5) & "','" & TextArray(6) & "','" & TextArray(7) & "','" & TextArray(9) & "','" & TextArray(10) & "','" & TextArray(13) & "','" & TextArray(15) & "','" & TextArray(19) & "');"

DoCmd.SetWarnings (WarningsOff)

DoCmd.RunSQL SQLString

DoCmd.SetWarnings (WarningsOn)

End Sub
</code>```

The code imports a text file from my desktop (1.txt) then imports the data into my Access DB.

This works for my one File. (1.txt)

I found this link how to loop through a folder.

How do I implement that into my code?

答:
I'm not sure why you are using TextArray over and over and over, but consider doing it like this.</p>

```<code>Option Compare Database

Private Sub Command0_Click()

        Dim strPathFile As String, strFile As String, strPath As String
        Dim strTable As String
        Dim blnHasFieldNames As Boolean

        ' Change this next line to True if the first row in EXCEL worksheet
        ' has field names
        blnHasFieldNames = True

        ' Replace C:\Documents\ with the real path to the folder that
        ' contains the EXCEL files
        strPath = "C:\Users\rschuell\Desktop\test\"

        ' Replace tablename with the real name of the table into which
        ' the data are to be imported
        strTable = "tablename"

        strFile = Dir(strPath & "*.txt")
        Do While Len(strFile) > 0
              strPathFile = strPath & strFile

              DoCmd.TransferText _
                TransferType:=acImportDelim, _
                TableName:=strTable, _
                FileName:=strPathFile, _
                HasFieldNames:=blnHasFieldNames

        ' Uncomment out the next code step if you want to delete the
        ' EXCEL file after it's been imported
        '       Kill strPathFile

              strFile = Dir()
        Loop

End Sub
</code>```

Title: How to loop through a folder?

Body:
I want to loop through a folder and import all the files into Access.

This is my code:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine
Dim TextArray()
Dim x As Double
Dim SQLString

Set fso = CreateObject("Scripting.FileSystemObject")

FileName = "C:\Users\ava\Desktop\TEST_IMPORT\1.txt"

Set MyFile = fso.OpenTextFile(FileName, ForReading)

Do While MyFile.AtEndOfStream <> True
    ReDim Preserve TextArray(x)
    TextLine = MyFile.ReadLine
    TextArray(x) = TextLine
    x = x + 1
Loop

MyFile.Close

SQLString = "INSERT INTO TEST_TAB (Layout, Anzahl_Etiketten, Anzahl_Verpackungseinheiten, Bezeichnung1, Selektionsnummer, Bezeichnung2, Barcode, LA_Nummer, RM_Nummer, Bezeichnung3, Teilenummer) VALUES ('" & TextArray(0) & "','" & TextArray(1) & "','" & TextArray(4) & "','" & TextArray(5) & "','" & TextArray(6) & "','" & TextArray(7) & "','" & TextArray(9) & "','" & TextArray(10) & "','" & TextArray(13) & "','" & TextArray(15) & "','" & TextArray(19) & "');"

DoCmd.SetWarnings (WarningsOff)

DoCmd.RunSQL SQLString

DoCmd.SetWarnings (WarningsOn)

End Sub

The code imports a text file from my desktop (1.txt) then imports the data into my Access DB.

This works for my one File. (1.txt)

I found this link how to loop through a folder.

How do I implement that into my code?

Body:
I'm not sure why you are using TextArray over and over and over, but consider doing it like this.

Option Compare Database

Private Sub Command0_Click()

        Dim strPathFile As String, strFile As String, strPath As String
        Dim strTable As String
        Dim blnHasFieldNames As Boolean

        ' Change this next line to True if the first row in EXCEL worksheet
        ' has field names
        blnHasFieldNames = True

        ' Replace C:\Documents\ with the real path to the folder that
        ' contains the EXCEL files
        strPath = "C:\Users\rschuell\Desktop\test\"

        ' Replace tablename with the real name of the table into which
        ' the data are to be imported
        strTable = "tablename"

        strFile = Dir(strPath & "*.txt")
        Do While Len(strFile) > 0
              strPathFile = strPath & strFile

              DoCmd.TransferText _
                TransferType:=acImportDelim, _
                TableName:=strTable, _
                FileName:=strPathFile, _
                HasFieldNames:=blnHasFieldNames

        ' Uncomment out the next code step if you want to delete the
        ' EXCEL file after it's been imported
        '       Kill strPathFile

              strFile = Dir()
        Loop

End Sub


答: All these answer are wrong, I think. You need to use the first-of-type pseudo-class, not first-child.

Title: applying a rule once only child selector maybe?


问:
SQL Server : SELECT * FROM [dbo].[Table] WHERE
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

```<code>SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'
</code>```

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

答:
Gabriel Slomka's answer is close, but uses an incorrect date format. You should be using format 104 (German), according to Microsoft's documentation:</p>

```<code>SELECT *
FROM [dbo].[Table]
WHERE CONVERT(DATETIME, [Column], 104) BETWEEN 'lower date' AND 'max date';
</code>```

Body:
I'm new to SQL Server, and I'm trying to select a range between two dates.

My column is varchar (format: dd.mm.yyyy hh:mm:ss), but if I use

SELECT *
FROM [dbo].[Table]
WHERE [Column] BETWEEN 'lower date' AND 'max date'

the result is every date that begins with the first two search option. In my case "dd" (dd.mm.yyyy hh:mm:ss).

Is there a solution, without changing the column from varchar to datetime?

Body:
Gabriel Slomka's answer is close, but uses an incorrect date format. You should be using format 104 (German), according to Microsoft's documentation:

SELECT *
FROM [dbo].[Table]
WHERE CONVERT(DATETIME, [Column], 104) BETWEEN 'lower date' AND 'max date';


问:
Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime
I've been working through various hurtles toward migrating an existing Symfony3 web app from a local LAMP host up to Goggle's App Engine Standard PHP Environment.  I've taken hints from the appengine-symfony-starter-project to use Memcache for sessions, pre-cache the application code, and connect to a Cloud SQL MySQL database. In have the core pieces working fine.

I added a login form at /login using a TWIG template with a form in it that goes like so:

```<code><form class="form" action="{{ path('security_login') }}" method="post">
  <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
  <div class="form-group">
    <input class="form-control" id="email" type="text" name="_email" placeholder="Email" value="{{ last_username }}"/>
  </div>
  <div class="form-group">
    <input class="form-control" id="password" type="password" name="_password" placeholder="Password"/>
  </div>
  <div class="form-group">
    <input type="checkbox" id="remember_me" name="_remember_me" checked>
    <label for "remember_me">Remember Me</label>
  </div>
  <div class="form-group">
    <button class="btn btn-round btn-b">Login</button>
  </div>
  <div class="form-group"><a href="{{ path('security_reset') }}">Forgot Password?</a></div>
</form>
</code>```

This works fine in the local DEV and TEST environments but when I push this up to GAE, I'm getting the error below:

```<code>Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime.
</code>```

I've been digging for a couple hours now and haven't found a hit as to what's wrong here.  Anyone have any ideas where to look?

Thanks in advance,

答: In my case "twig.strict_variables: true" to "twig.strict_variables: false" fixed an issue. </p>

Body:
I've been working through various hurtles toward migrating an existing Symfony3 web app from a local LAMP host up to Goggle's App Engine Standard PHP Environment.  I've taken hints from the appengine-symfony-starter-project to use Memcache for sessions, pre-cache the application code, and connect to a Cloud SQL MySQL database. In have the core pieces working fine.

I added a login form at /login using a TWIG template with a form in it that goes like so:

<form class="form" action="{{ path('security_login') }}" method="post">
  <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />

    <input class="form-control" id="email" type="text" name="_email" placeholder="Email" value="{{ last_username }}"/>

    <input class="form-control" id="password" type="password" name="_password" placeholder="Password"/>

    <input type="checkbox" id="remember_me" name="_remember_me" checked>
    Remember Me

    <button class="btn btn-round btn-b">Login</button>

Forgot Password?

</form>

This works fine in the local DEV and TEST environments but when I push this up to GAE, I'm getting the error below:

Unable to load the "Symfony\Bridge\Twig\Form\TwigRenderer" runtime.

I've been digging for a couple hours now and haven't found a hit as to what's wrong here.  Anyone have any ideas where to look?

Thanks in advance,


问:
Keras stateful LSTM multi-gpu error Incompatible shapes: [2540] vs. [508] batch size multiplied buy nGPU
I had the same issue but when I tried to apply the same fix I have run into another error. I am however running on 5 gpus. I have read that you need to make sure that your samples are divisible by both the batch sive and number of gpus but I have done that. I have scoured the internet for days and am unable to find anything that has been able to fix the issue I am having. I am running keras v2.0.9 and tensor flow v1.1.0

VARIABLES:
attributeTables[0] is a numpy array shape (35560, 700)
y is a numpy array shape (35560, ) I have also tried using shape (35560, 1) for y but all that happens is the "Incompatible shapes: [2540] vs. [508]" changes from that to "Incompatible shapes: [2540, 1] vs. [508, 1]"

So this says to me that the issue is only with the targetsand that the expected batch size is getting multiplied somewhere in the middle of the process only for the targets and not for attributes causing a mismatch or at least only durring validation I'm not sure.

Here is the code and error in question.

```<code>import numpy as np
from keras.models import Sequential
from keras.utils import multi_gpu_model
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

def baseline_model():
    # create model
    print("Building Layers")
    model = Sequential()
    model.add(LSTM(700, batch_input_shape=(batchSize, X.shape[1], X.shape[2]), activation='tanh', return_sequences=False, stateful=True))
    model.add(Dense(1))
    print("Building Parallel model")
    parallel_model = multi_gpu_model(model, gpus=nGPU)
    # Compile model
    #model.compile(loss='mean_squared_error', optimizer='adam')
    print("Compiling Model")
    parallel_model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
    return parallel_model

def buildModel():
    print("Bulding Model")
    mlp = baseline_model()
    print("Fitting Model")
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))

print("Scaling")
scaler = StandardScaler()
X_Scaled = scaler.fit_transform(attributeTables[0])

print("Finding Batch Size")
nGPU = 5
batchSize = 500
while len(X_Scaled) % (batchSize * nGPU) != 0:
    batchSize += 1

print("Filling Arrays")
X = X_Scaled.reshape((X_Scaled.shape[0], X_Scaled.shape[1], 1))
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=.8)

print("Calling buildModel()")
model = buildModel()

print("Ploting History")
plt.plot(model.history['loss'], label='train')
plt.plot(model.history['val_loss'], label='test')
plt.legend()
plt.show()
</code>```

Here is my complete output.

```<code>Beginning OHLC Load
Time took : 7.571000099182129

Making gloabal copies
Time took : 0.0

Using TensorFlow backend.
Scaling
Finding Batch Size
Filling Arrays
Calling buildModel()
Bulding Model
Building Layers
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_split.py:2010: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.
  FutureWarning)
Building Parallel model
Compiling Model
Fitting Model
Train on 28448 samples, validate on 7112 samples
Epoch 1/1
Traceback (most recent call last):

  File "<ipython-input-2-74c49f05bfbc>", line 1, in <module>
    runfile('C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py', wdir='C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()

  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 57, in buildModel
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1631, in fit
    validation_steps=validation_steps)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1213, in _fit_loop
    outs = f(ins_batch)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2332, in __call__
    **self.session_kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)

InvalidArgumentError: Incompatible shapes: [2540,1] vs. [508,1]
     [[Node: training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@loss/concatenate_1_loss/sub"], _device="/job:localhost/replica:0/task:0/gpu:0"](training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape, training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape_1)]]
     [[Node: replica_1/sequential_1/dense_1/BiasAdd/_313 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:1", send_device_incarnation=1, tensor_name="edge_1355_replica_1/sequential_1/dense_1/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs', defined at:
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 241, in main
    kernel.start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\ioloop.py", line 832, in start
    self._run_callback(self._callbacks.popleft())
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\ioloop.py", line 605, in _run_callback
    ret = callback()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 265, in enter_eventloop
    self.eventloop(self)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 106, in loop_qt5
    return loop_qt4(kernel)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 99, in loop_qt4
    _loop_qt(kernel.app)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 83, in _loop_qt
    app.exec_()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 39, in process_stream_events
    kernel.do_one_iteration()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 298, in do_one_iteration
    stream.flush(zmq.POLLIN, 1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 352, in flush
    self._handle_recv()
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2808, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-74c49f05bfbc>", line 1, in <module>
    runfile('C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py', wdir='C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor')
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 57, in buildModel
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1608, in fit
    self._make_train_function()
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 990, in _make_train_function
    loss=self.total_loss)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\optimizers.py", line 415, in get_updates
    grads = self.get_gradients(loss, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\optimizers.py", line 73, in get_gradients
    grads = K.gradients(loss, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2369, in gradients
    return tf.gradients(loss, variables, colocate_gradients_with_ops=True)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 560, in gradients
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 368, in _MaybeCompile
    return grad_fn()  # Exit early
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 560, in <lambda>
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_grad.py", line 609, in _SubGrad
    rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 411, in _broadcast_gradient_args
    name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

...which was originally created as op 'loss/concatenate_1_loss/sub', defined at:
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
[elided 27 identical lines from previous traceback]
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 55, in buildModel
    mlp = baseline_model()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 29, in baseline_model
    parallel_model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 860, in compile
    sample_weight, mask)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 460, in weighted
    score_array = fn(y_true, y_pred)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 13, in mean_absolute_error
    return K.mean(K.abs(y_pred - y_true), axis=-1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 821, in binary_op_wrapper
    return func(x, y, name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 2627, in _sub
    result = _op_def_lib.apply_op("Sub", x=x, y=y, name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Incompatible shapes: [2540,1] vs. [508,1]
     [[Node: training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@loss/concatenate_1_loss/sub"], _device="/job:localhost/replica:0/task:0/gpu:0"](training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape, training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape_1)]]
     [[Node: replica_1/sequential_1/dense_1/BiasAdd/_313 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:1", send_device_incarnation=1, tensor_name="edge_1355_replica_1/sequential_1/dense_1/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

答:
I just published an experimental utility, stateful_multi_gpu, to handle stateful model training of multiple GPUs. I'm interested to know if it is of use to you.

Please also see my answer for the same question Daniel Möller referred to.

Body:
I had the same issue but when I tried to apply the same fix I have run into another error. I am however running on 5 gpus. I have read that you need to make sure that your samples are divisible by both the batch sive and number of gpus but I have done that. I have scoured the internet for days and am unable to find anything that has been able to fix the issue I am having. I am running keras v2.0.9 and tensor flow v1.1.0

VARIABLES:
attributeTables[0] is a numpy array shape (35560, 700)
y is a numpy array shape (35560, ) I have also tried using shape (35560, 1) for y but all that happens is the "Incompatible shapes: [2540] vs. [508]" changes from that to "Incompatible shapes: [2540, 1] vs. [508, 1]"

So this says to me that the issue is only with the targetsand that the expected batch size is getting multiplied somewhere in the middle of the process only for the targets and not for attributes causing a mismatch or at least only durring validation I'm not sure.

Here is the code and error in question.

import numpy as np
from keras.models import Sequential
from keras.utils import multi_gpu_model
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

def baseline_model():
    # create model
    print("Building Layers")
    model = Sequential()
    model.add(LSTM(700, batch_input_shape=(batchSize, X.shape[1], X.shape[2]), activation='tanh', return_sequences=False, stateful=True))
    model.add(Dense(1))
    print("Building Parallel model")
    parallel_model = multi_gpu_model(model, gpus=nGPU)
    # Compile model
    #model.compile(loss='mean_squared_error', optimizer='adam')
    print("Compiling Model")
    parallel_model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
    return parallel_model

def buildModel():
    print("Bulding Model")
    mlp = baseline_model()
    print("Fitting Model")
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))

print("Scaling")
scaler = StandardScaler()
X_Scaled = scaler.fit_transform(attributeTables[0])

print("Finding Batch Size")
nGPU = 5
batchSize = 500
while len(X_Scaled) % (batchSize * nGPU) != 0:
    batchSize += 1

print("Filling Arrays")
X = X_Scaled.reshape((X_Scaled.shape[0], X_Scaled.shape[1], 1))
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=.8)

print("Calling buildModel()")
model = buildModel()

print("Ploting History")
plt.plot(model.history['loss'], label='train')
plt.plot(model.history['val_loss'], label='test')
plt.legend()
plt.show()

Here is my complete output.

Beginning OHLC Load
Time took : 7.571000099182129

Making gloabal copies
Time took : 0.0

Using TensorFlow backend.
Scaling
Finding Batch Size
Filling Arrays
Calling buildModel()
Bulding Model
Building Layers
C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_split.py:2010: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.
  FutureWarning)
Building Parallel model
Compiling Model
Fitting Model
Train on 28448 samples, validate on 7112 samples
Epoch 1/1
Traceback (most recent call last):

  File "<ipython-input-2-74c49f05bfbc>", line 1, in <module>
    runfile('C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py', wdir='C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()

  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 57, in buildModel
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1631, in fit
    validation_steps=validation_steps)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1213, in _fit_loop
    outs = f(ins_batch)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2332, in __call__
    **self.session_kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)

InvalidArgumentError: Incompatible shapes: [2540,1] vs. [508,1]
     [[Node: training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@loss/concatenate_1_loss/sub"], _device="/job:localhost/replica:0/task:0/gpu:0"](training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape, training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape_1)]]
     [[Node: replica_1/sequential_1/dense_1/BiasAdd/_313 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:1", send_device_incarnation=1, tensor_name="edge_1355_replica_1/sequential_1/dense_1/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs', defined at:
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 241, in main
    kernel.start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\ioloop.py", line 832, in start
    self._run_callback(self._callbacks.popleft())
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\ioloop.py", line 605, in _run_callback
    ret = callback()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 265, in enter_eventloop
    self.eventloop(self)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 106, in loop_qt5
    return loop_qt4(kernel)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 99, in loop_qt4
    _loop_qt(kernel.app)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 83, in _loop_qt
    app.exec_()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\eventloops.py", line 39, in process_stream_events
    kernel.do_one_iteration()
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 298, in do_one_iteration
    stream.flush(zmq.POLLIN, 1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 352, in flush
    self._handle_recv()
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2808, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-74c49f05bfbc>", line 1, in <module>
    runfile('C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py', wdir='C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor')
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 57, in buildModel
    return mlp.fit(X_train, y_train, epochs=1, batch_size=batchSize, shuffle=False, validation_data=(X_test, y_test))
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1608, in fit
    self._make_train_function()
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 990, in _make_train_function
    loss=self.total_loss)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\optimizers.py", line 415, in get_updates
    grads = self.get_gradients(loss, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\optimizers.py", line 73, in get_gradients
    grads = K.gradients(loss, params)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2369, in gradients
    return tf.gradients(loss, variables, colocate_gradients_with_ops=True)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 560, in gradients
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 368, in _MaybeCompile
    return grad_fn()  # Exit early
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gradients_impl.py", line 560, in <lambda>
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_grad.py", line 609, in _SubGrad
    rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 411, in _broadcast_gradient_args
    name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

...which was originally created as op 'loss/concatenate_1_loss/sub', defined at:
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
[elided 27 identical lines from previous traceback]
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 77, in <module>
    model = buildModel()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 55, in buildModel
    mlp = baseline_model()
  File "C:/Users/BeeAndTurtle/Documents/Programming/Python/Kraken_API_Market_Prediction/predictor/test.py", line 29, in baseline_model
    parallel_model.compile(loss='mae', optimizer='adam', metrics=['accuracy'])
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 860, in compile
    sample_weight, mask)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 460, in weighted
    score_array = fn(y_true, y_pred)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 13, in mean_absolute_error
    return K.mean(K.abs(y_pred - y_true), axis=-1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\math_ops.py", line 821, in binary_op_wrapper
    return func(x, y, name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 2627, in _sub
    result = _op_def_lib.apply_op("Sub", x=x, y=y, name=name)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Incompatible shapes: [2540,1] vs. [508,1]
     [[Node: training/Adam/gradients/loss/concatenate_1_loss/sub_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@loss/concatenate_1_loss/sub"], _device="/job:localhost/replica:0/task:0/gpu:0"](training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape, training/Adam/gradients/loss/concatenate_1_loss/sub_grad/Shape_1)]]
     [[Node: replica_1/sequential_1/dense_1/BiasAdd/_313 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:1", send_device_incarnation=1, tensor_name="edge_1355_replica_1/sequential_1/dense_1/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]


问:
How to search for functions in module?
I want to have a search function like a man page inside a Python module.

Is there a built-in or module function to search a string/wildcard char in function name/class name/object name or function of class?

e.g. find(get_*)?

This would find all get_* functions, such as get_height, get_weight, get_area, get_volume as well as square.get_area,rectange.get_area
or have a find(get?int) to find get_int, etc.

I can have a list in help(module) but there is too much clutter and no search function I can find.
If not, how can I write a function to do the same?

答:
You can use the re module to do this as illustrated below. You need to learn how to write regular expressions to use it, but that's extensively documented. For a good start see the Regular Expression HOWTO in the documentation.

```<code>import re

def find(module, regex):
    return [name for name in dir(module) if re.match(regex, name)]

# Sample usage

import some_module
print(find(some_module, r'get_\.*'))  # Search for things prefixed with "get_".
</code>```

Title: How to search for functions in module?

Body:
You can use the re module to do this as illustrated below. You need to learn how to write regular expressions to use it, but that's extensively documented. For a good start see the Regular Expression HOWTO in the documentation.

import re

def find(module, regex):
    return [name for name in dir(module) if re.match(regex, name)]

# Sample usage

import some_module
print(find(some_module, r'get_\.*'))  # Search for things prefixed with "get_".


问:
Multiple threads and performance on a single CPU
Is here any performance benefit to using multiple threads on a computer with a single CPU that does not having hyperthreading?  </p>

答:
In terms of speed of computation, No.  In fact things will slow down due to the overhead of managing the threads.

In terms of responsiveness, yes.  You can for example have one thread wait on an IO operation and have another run a GUI at the same time.

OwnerDisplayName: Tim

OwnerDisplayName: MontyGomery


问:
apache2 mod_headers not working
Question Description: I want to set my site "Access-Control-Allow-Origin", so I set it in apache's config (almost anywhere), but it's not working. I also set other headers for testing, but it's still not working too.

Apache version: 2.2.22

Apache modules: http://www.anwcl.com/test/show_modules.php

My target url:

```<code>http://www.anwcl.com/test/test_only_div.html
</code>```

And it's linked to my local file:

```<code>e:\wamp\www\test\test_only_div.html
</code>```

And here's my apache's configurations:

E:\wamp\bin\apache\apache2.2.22\conf\httpd.conf

```<code>...
LoadModule headers_module modules/mod_headers.so
...
Include conf/extra/httpd-vhosts.conf
...
</code>```

E:\wamp\bin\apache\apache2.2.22\conf\extra\httpd-vhosts.conf

```<code>NameVirtualHost *:80
<VirtualHost *:80>
    Header add Access-Control-Allow-Origin "*"
    Header echo ^TS
    Header add MyHeader "Hello Joe. It took %D microseconds for Apache to serve this request."
    ServerAdmin xxx@gmail.com
    DocumentRoot "E:/wamp/www/"
    ServerName www.anwcl.com
    ErrorLog "logs/xxx.log"
    CustomLog "logs/xxx.log" common
    <Directory "E:/wamp/www/">
        Header add Access-Control-Allow-Origin "*"
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
</code>```

E:\wamp\www\.htaccess

```<code>Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</code>```

E:\wamp\www\test\.htaccess

```<code>Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</code>```

And here's Wireshark's caps, there are no expected headers :

```<code>http://www.anwcl.com/question/apache-mod-headers-not-working.jpg
http://www.anwcl.com/question/apache-mod-headers-not-working-304.jpg
</code>```

答:
The changes could have possibly taken place and you aren't seeing the changes within your browser. This is especially typical if you're serving static files like the images you're trying to alter the headers of.

You can even have chrome disable cache while viewing the page with the Javascript console open and still not see the changes take effect.

What you'll want to look for is the response code. If it's a 304, the server has recognized that your browser already has a valid representation of the requested file, and will serve that file. If it does, you will not see the headers you've added after your browser initially downloaded that page.

To see if this is the case, change the url to http://myexample.com/myimage.jpg?t=1, or any other random query parameter and see if that works.

Title: apache2 mod_headers not working

Body:
Question Description: I want to set my site "Access-Control-Allow-Origin", so I set it in apache's config (almost anywhere), but it's not working. I also set other headers for testing, but it's still not working too.

Apache version: 2.2.22

Apache modules: http://www.anwcl.com/test/show_modules.php

My target url:

http://www.anwcl.com/test/test_only_div.html

And it's linked to my local file:

e:\wamp\www\test\test_only_div.html

And here's my apache's configurations:

E:\wamp\bin\apache\apache2.2.22\conf\httpd.conf

...
LoadModule headers_module modules/mod_headers.so
...
Include conf/extra/httpd-vhosts.conf
...

E:\wamp\bin\apache\apache2.2.22\conf\extra\httpd-vhosts.conf

NameVirtualHost *:80
<VirtualHost *:80>
    Header add Access-Control-Allow-Origin "*"
    Header echo ^TS
    Header add MyHeader "Hello Joe. It took %D microseconds for Apache to serve this request."
    ServerAdmin xxx@gmail.com
    DocumentRoot "E:/wamp/www/"
    ServerName www.anwcl.com
    ErrorLog "logs/xxx.log"
    CustomLog "logs/xxx.log" common
    <Directory "E:/wamp/www/">
        Header add Access-Control-Allow-Origin "*"
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

E:\wamp\www\.htaccess

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

E:\wamp\www\test\.htaccess

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

And here's Wireshark's caps, there are no expected headers :

http://www.anwcl.com/question/apache-mod-headers-not-working.jpg
http://www.anwcl.com/question/apache-mod-headers-not-working-304.jpg


问:
Add scale bar (in meters) to scatterplot of GPS coordinates in Stata

I am graphing a series of GPS points using twoway scatter in Stata. This is just to visualize where the points are for some quick validation. I would like to add a scale bar for both the x and y axes to get a sense of how far apart the points actually are.

Here is some code to input a few coordinates and graph a scatterplot, specifying the axis ranges:

```<code>* Input example data
    clear
    input key lat lon
    1   -17.01639   36.11884
    2   -17.01669   36.11916
    3   -17.01692   36.11666
    4   -17.01575   36.11607
    5   -17.01551   36.11619
    6   -17.01543   36.11665
    7   -17.01581   36.11706
    8   -17.01665   36.11672
    9   -17.01543   36.11612
    10  -17.01724   36.11668
    end

* Install Geodist (we will need this later)
    cap which geodist
        if _rc == 111 ssc install geodist   // Installs geodist if necessary

* Create y/x axis ranges using min and max latitude and longitude
    sort lat
    local ymin = lat[1]
    local ymax = lat[_N]
    local ydelta = (`ymax' - `ymin')/3

    sort lon
    local xmin = lon[1]
    local xmax = lon[_N]
    local xdelta = (`xmax' - `xmin')/3

* Graph points
    twoway scatter lat lon,                                 ///
        ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
        xlabel(`xmin'(`xdelta')`xmax')
</code>```

You should get a lovely basic scatterplot. This is great, but I have no idea how far the points actually are from each other. Now, we can get a sense of the distance between the minimum and maximum latitude/longitude using the following:

```<code>* Store x and y ranges in locals
    geodist `ymin' `xmin' `ymax' `xmin'
    local yrange = `r(distance)'

    geodist `ymin' `xmin' `ymin' `xmax'
    local xrange = `r(distance)'
</code>```

For this data, y spans 0.2km and x spans 0.329km.

Note: I know that on a spherical projection of the earth the distance between ymin and ymax may not map perfectly onto subsets of that distance (e.g. the distance from ymin to ymax/2 may not be precisely the same as half the distance between ymin and ymax). But for what I need this visualization for, and the fact that these data are usally clustered within 2km of each other, its accurate enough.

So, how can I create a scale bar for each of x and y to show what, for example, 100m looks like? In this example, the y scale would look different than the x scale, so maybe I need to find a way to change the y-ranges and x-ranges so that they can represent the same scale?

答:
If you are going to create a map with geographic coordinates, you first need to convert these to planar (x,y) coordinates. With geo2xy (from SSC), you can use the same projection that Google Maps uses so the map you create will have exactly the same proportion that you would observe on Google Maps. Since you want coordinates that are based on distance units, I chose a true Mercator projection which creates (x,y) coordinates in meters. The projection is centered at mid-longitude by default which means that x-coordinates will be in meters from the center of the map. The y-coordinates are in meters from the equator. To center them on the middle of the map, all you need is to offset them from the mean.

When creating a map in Stata, you need to be sure to create a map region that has the correct proportions (xsize() and ysize() are proportional to the distance).

```<code>* Input example data
clear
input key lat lon
1   -17.01639   36.11884
2   -17.01669   36.11916
3   -17.01692   36.11666
4   -17.01575   36.11607
5   -17.01551   36.11619
6   -17.01543   36.11665
7   -17.01581   36.11706
8   -17.01665   36.11672
9   -17.01543   36.11612
10  -17.01724   36.11668
end

* project lat/lon to (x,y) in meters using a Mercator projection
geo2xy lat lon, gen(ylat xlon) project(mercator)

* show the projection details and compute the plot's height
return list
local yheight = 6 * `r(aspect)'

* the projection is in meters, centered on mid-longitude, center y coor as well
sum ylat, meanonly
replace ylat = ylat - r(mean)

scatter ylat xlon,  ///
        xsize(6) ysize(`yheight') ///
        ylabel(minmax, nogrid) yscale(off) ///
        xlabel(minmax, nogrid) xscale(off) ///
        plotregion(margin(small)) graphregion(margin(small)) ///
        legend(off) name(mercator_us, replace)

graph export my_map.png, width(600) replace
</code>```

Here's the resulting map:

If you want to display axis units (in meters), you can remove the xlabel() and ylabel() lines. If you do so, Stata will likely rescale each axis to fit nice intervals and will therefore change the proportions a bit. Here's what the map looks like if I let Stata decide on the labels:

Body:
I am graphing a series of GPS points using twoway scatter in Stata. This is just to visualize where the points are for some quick validation. I would like to add a scale bar for both the x and y axes to get a sense of how far apart the points actually are.

Here is some code to input a few coordinates and graph a scatterplot, specifying the axis ranges:

* Input example data
    clear
    input key lat lon
    1   -17.01639   36.11884
    2   -17.01669   36.11916
    3   -17.01692   36.11666
    4   -17.01575   36.11607
    5   -17.01551   36.11619
    6   -17.01543   36.11665
    7   -17.01581   36.11706
    8   -17.01665   36.11672
    9   -17.01543   36.11612
    10  -17.01724   36.11668
    end

* Install Geodist (we will need this later)
    cap which geodist
        if _rc == 111 ssc install geodist   // Installs geodist if necessary

* Create y/x axis ranges using min and max latitude and longitude
    sort lat
    local ymin = lat[1]
    local ymax = lat[_N]
    local ydelta = (`ymax' - `ymin')/3

    sort lon
    local xmin = lon[1]
    local xmax = lon[_N]
    local xdelta = (`xmax' - `xmin')/3

* Graph points
    twoway scatter lat lon,                                 ///
        ylabel(`ymin'(`ydelta')`ymax', angle(forty_five))   ///
        xlabel(`xmin'(`xdelta')`xmax')

You should get a lovely basic scatterplot. This is great, but I have no idea how far the points actually are from each other. Now, we can get a sense of the distance between the minimum and maximum latitude/longitude using the following:

* Store x and y ranges in locals
    geodist `ymin' `xmin' `ymax' `xmin'
    local yrange = `r(distance)'

    geodist `ymin' `xmin' `ymin' `xmax'
    local xrange = `r(distance)'

For this data, y spans 0.2km and x spans 0.329km.

Note: I know that on a spherical projection of the earth the distance between ymin and ymax may not map perfectly onto subsets of that distance (e.g. the distance from ymin to ymax/2 may not be precisely the same as half the distance between ymin and ymax). But for what I need this visualization for, and the fact that these data are usally clustered within 2km of each other, its accurate enough.

So, how can I create a scale bar for each of x and y to show what, for example, 100m looks like? In this example, the y scale would look different than the x scale, so maybe I need to find a way to change the y-ranges and x-ranges so that they can represent the same scale?

Body:
If you are going to create a map with geographic coordinates, you first need to convert these to planar (x,y) coordinates. With geo2xy (from SSC), you can use the same projection that Google Maps uses so the map you create will have exactly the same proportion that you would observe on Google Maps. Since you want coordinates that are based on distance units, I chose a true Mercator projection which creates (x,y) coordinates in meters. The projection is centered at mid-longitude by default which means that x-coordinates will be in meters from the center of the map. The y-coordinates are in meters from the equator. To center them on the middle of the map, all you need is to offset them from the mean.

When creating a map in Stata, you need to be sure to create a map region that has the correct proportions (xsize() and ysize() are proportional to the distance).

* Input example data
clear
input key lat lon
1   -17.01639   36.11884
2   -17.01669   36.11916
3   -17.01692   36.11666
4   -17.01575   36.11607
5   -17.01551   36.11619
6   -17.01543   36.11665
7   -17.01581   36.11706
8   -17.01665   36.11672
9   -17.01543   36.11612
10  -17.01724   36.11668
end

* project lat/lon to (x,y) in meters using a Mercator projection
geo2xy lat lon, gen(ylat xlon) project(mercator)

* show the projection details and compute the plot's height
return list
local yheight = 6 * `r(aspect)'

* the projection is in meters, centered on mid-longitude, center y coor as well
sum ylat, meanonly
replace ylat = ylat - r(mean)

scatter ylat xlon,  ///
        xsize(6) ysize(`yheight') ///
        ylabel(minmax, nogrid) yscale(off) ///
        xlabel(minmax, nogrid) xscale(off) ///
        plotregion(margin(small)) graphregion(margin(small)) ///
        legend(off) name(mercator_us, replace)

graph export my_map.png, width(600) replace

Here's the resulting map:

If you want to display axis units (in meters), you can remove the xlabel() and ylabel() lines. If you do so, Stata will likely rescale each axis to fit nice intervals and will therefore change the proportions a bit. Here's what the map looks like if I let Stata decide on the labels: