问:
Is this well defined code?
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

```<code>*d = ~(*d);
d++;
</code>```

Assembly:

```<code>*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4
</code>```

vs

```<code>*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4
</code>```

Thanks!

答:
Your expression has undefined (as opposed to unspecified) behavior. The assembly code could as well play Beethoven 9th and still conform to the standard.

From the Holy Standard, Chapter 5, Verse 4:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

Therefore, the code is ill-formed. I don't know whether a standard conforming compiler is required to issue a diagnostic, but I have been bitten enough times by this that I'm ready to bet it is not.

Refer to @Prasoon Saurav's excellent exposition there for more details.

Title: Is this well defined code?

Body:
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it.

I see a slight difference in the generated assembly when I compare it to:

*d = ~(*d);
d++;

Assembly:

*d++ = ~(*d);
0x83384    LDR           R3,[R0 <d>,4]        <<diff
0x83388    ADD           R1 <c>, R1 <c>, 1
0x8338c    MVN           R3, R3
0x83390    STR           R3,[R0 <d>],4

vs

*d = ~(*d);
d++;
0x83384   LDR           R3,[R0 <d>]
0x83388   ADD           R1 <c>, R1 <c>, 1
0x8338c   MVN           R3, R3
0x83390   STR           R3,[R0 <d>],4

Thanks!


来源: stackexchange

问:
How to stream trades from Binance web socket API in Node.js?
I am trying to use the Binance API to get the latest trades on a crypto-currency pair. Here is the endpoint to the API, say for BTC/USDT: wss://stream.binance.com:9443/ws/btcusdt@trade

I tested this API on https://www.websocket.org/echo.html, and was successful in getting a continuous stream of new trades.

How do I use this API in Node.js to continuously output the trades on the console? Is there any specific library or package you recommend?

答:
And this is how to stream Futures trades from Binance today:

```<code>import {WebSocket} from 'ws';

const coin = 'btcusdt';

const ws = new WebSocket(`wss://fstream.binance.com/ws/${coin}@trade`);

ws.on('message', (data?: string) => {
    if (data) {
        const trade = JSON.parse(data); // parsing a single-trade record
        console.log(trade);
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
And this is how to stream Futures trades from Binance today:

import {WebSocket} from 'ws';

const coin = 'btcusdt';

const ws = new WebSocket(`wss://fstream.binance.com/ws/${coin}@trade`);

ws.on('message', (data?: string) => {
    if (data) {
        const trade = JSON.parse(data); // parsing a single-trade record
        console.log(trade);
    }
});


问:
Css gradient where color values are derived from element props
I'm rendering data cards for Pokemon. Each pokemon type has an associated color. Fire is red, water is blue, grass is green. Some pokemon have one type, some pokemon have 2 types.

I want the background color to be either solid if the pokemon has one type, but the tricky part is I want the background to be a gradient if the pokemon has two types. For example, a Fire pokemon would have a solid red background, whereas a water/grass pokemon would be a blue/green gradient.

There are 18 pokemon types. For a total of 324 combinations. I know I could hardcode classes for each combination .fire-ice{colors} but there has to be a better solution.

How can achieve this programatically? I'm using sass and react

答:
1 - Setup an object to map power:color.

2 - Turn the pokemon powers array into colors array and join it to a string

3 - put the colors string inside background:linear-gradient(...) inline style

Take a look at the below code:

 const colors = {
  grass: 'green',
  fire: 'red',
  water: 'blue'
 }
 function getColor(powers){
  if(powers.length === 1) return colors[powers[0]];
  return 'linear-gradient('+powers.map(p=> colors[p]).join()+')';
 }

 // testing..
 const powers = [
  ['grass'],
  ['fire','water'],
  ['fire'],
  ['fire','water','grass']
 ];
 powers.forEach(p => console.log(getColor(p)));```

for react, use

Body:
1 - Setup an object to map power:color.

2 - Turn the pokemon powers array into colors array and join it to a string

3 - put the colors string inside background:linear-gradient(...) inline style

Take a look at the below code:

 const colors = {
  grass: 'green',
  fire: 'red',
  water: 'blue'
 }
 function getColor(powers){
  if(powers.length === 1) return colors[powers[0]];
  return 'linear-gradient('+powers.map(p=> colors[p]).join()+')';
 }

 // testing..
 const powers = [
  ['grass'],
  ['fire','water'],
  ['fire'],
  ['fire','water','grass']
 ];
 powers.forEach(p => console.log(getColor(p)));

for react, use <div style={{background: getColor(this.props.powers)}}/>


问:
HAProxy SSL-termination with redirect http to https is losing X-Client-IP information with send-proxy to NGINX
ISSUE

I can't see the original remote-ip coming from outside, when I use SSL-Termination in HAProxy and force HTTPS. If I do not force HTTP to HTTPS redirect, I can see from nginx-logs that send-proxy is in fact working with HTTP. I can see the same thing from HAProxy-logs too.

THEORY

If I remove all cookies of the site, switch redirect off and open the HTTP version, HAProxy will show the remote-ip correctly. After switching redirect to HTTPS and opening the same HTTP-site, logs will first show a connection from remote-ip to backend:

```
    176.93.182.162:49300 [14/Feb/2020:23:40:30.254] 80_443_frontend 80_443_frontend/(NOSRV)
```

and then a connection from localhost (127.0.0.1):

```
    127.0.0.1:35304 [14/Feb/2020:23:40:30.776] 80_443_frontend~ 80_443_backend/git 0/0/0/1/1 200
```

CONCLUSION

My thoughts are, that HAProxy will direct internal traffic from 443 back to port 80 towards the backend, and at the same time switch the header IP to it's own IP. Hopefully someone will have an idea.

HAProxy is inside it's own lxd container, as is NGINX!! If this changes something?

This is the configuration in HAProxy:

```

    frontend 80_443_frontend
        bind *:80
        bind *:443 ssl crt /etc/ssl/git.domain.org/git.domain.org.pem alpn h2,http/1.1
        redirect scheme https code 301 if !{ ssl_fc }
        timeout client 1m
        option forwardfor
        option http-server-close
        acl letsencrypt-acl path_beg /.well-known/acme-challenge/
        use_backend letsencrypt_backend if letsencrypt-acl
        acl git_host hdr(host) -i git.domain.org

        use_backend 80_443_backend if git_host

    backend letsencrypt_backend
        server letsencrypt 127.0.0.1:8888

    backend 80_443_backend
        http-request set-header X-Client-IP %[src]
        server git git.lxd:80 send-proxy

```

答:
Well, f*ck me sideways!

One needs to remember what ports are forwarded to containers!!

This is what was missing:

```<code>sudo iptables -t nat -I PREROUTING -i eth0 -p TCP -d PUBLIC_IP/32 --dport 443 -j DNAT --to-destination 10.4.21.53:443
</code>```

Body:
ISSUE

I can't see the original remote-ip coming from outside, when I use SSL-Termination in HAProxy and force HTTPS. If I do not force HTTP to HTTPS redirect, I can see from nginx-logs that send-proxy is in fact working with HTTP. I can see the same thing from HAProxy-logs too.

THEORY

If I remove all cookies of the site, switch redirect off and open the HTTP version, HAProxy will show the remote-ip correctly. After switching redirect to HTTPS and opening the same HTTP-site, logs will first show a connection from remote-ip to backend:

    176.93.182.162:49300 [14/Feb/2020:23:40:30.254] 80_443_frontend 80_443_frontend/(NOSRV)

and then a connection from localhost (127.0.0.1):

    127.0.0.1:35304 [14/Feb/2020:23:40:30.776] 80_443_frontend~ 80_443_backend/git 0/0/0/1/1 200

CONCLUSION

My thoughts are, that HAProxy will direct internal traffic from 443 back to port 80 towards the backend, and at the same time switch the header IP to it's own IP. Hopefully someone will have an idea.

HAProxy is inside it's own lxd container, as is NGINX!! If this changes something?

This is the configuration in HAProxy:

    frontend 80_443_frontend
        bind *:80
        bind *:443 ssl crt /etc/ssl/git.domain.org/git.domain.org.pem alpn h2,http/1.1
        redirect scheme https code 301 if !{ ssl_fc }
        timeout client 1m
        option forwardfor
        option http-server-close
        acl letsencrypt-acl path_beg /.well-known/acme-challenge/
        use_backend letsencrypt_backend if letsencrypt-acl
        acl git_host hdr(host) -i git.domain.org

        use_backend 80_443_backend if git_host

    backend letsencrypt_backend
        server letsencrypt 127.0.0.1:8888

    backend 80_443_backend
        http-request set-header X-Client-IP %[src]
        server git git.lxd:80 send-proxy

Body:
Well, f*ck me sideways!

One needs to remember what ports are forwarded to containers!!

This is what was missing:

sudo iptables -t nat -I PREROUTING -i eth0 -p TCP -d PUBLIC_IP/32 --dport 443 -j DNAT --to-destination 10.4.21.53:443


问:
Efficient algorithm or method for shuffling a list with many duplicates?
Let's say I have 5 marbles, 3 are red and 2 are blue.
The marbles of the same color are numbered from 1 to n, where n is the number of marbles of that color.

What I need is way to shuffle the list ['red', 'red', 'red','blue', 'blue'] , where the permutations of the individual marbles does not matter.

E.g
['red1', 'red2', 'red3','blue', 'blue'] and
['red2', 'red1', 'red3','blue', 'blue']
are only one solution.

Because my original problem has a lot more marbles of one color, compared to the others, the normal shuffle of the list results in a high bias for certain orders.

One idea I had would be:

Start with a new empty list,

Generate 2 random integers (the first integer to choose a color, the second integer to determine how many marbles to pick of that color)

Append the picked marbles to the new list

Repeat until all marbles have been used up

I'm wondering if there are some better ways to solve this, maybe with a more guaranteed unbiased result.

Edit:
A small scaled scenario would be 4 different colors with 2 to 5 marbles per color.
A realistic scenario would be 20 diff. colors, with between 5 and 50 marbles per color.

答:
This will give a uniform distribution of the uniques combinations:

```<code>from random import randrange
from collections import Counter
def marblePick(marbles):
    remaining = list(Counter(marbles).elements())
    return [remaining.pop(randrange(r)) for r in range(len(remaining),0,-1)]
</code>```

The performance seems to be linear and I tested the distribution by sampling as follows:

```<code>marbles = {"R":3,"B":2}

N = 1000000
dist = Counter()
for _ in range(N):
    combo = marblePick(marbles)
    dist[tuple(combo)]+=1

for s,c in dist.items():
    print(s,c/N)

import statistics as stats
prop = [c/N for c in dist.values()]
mean = stats.mean(prop)
stdev = stats.stdev(prop)
print("mean:",mean,"stdDev:",f"{100*stdev/mean:.1f}%",N,"samples",len(dist),"combos")
</code>```

the results are conclusive for this sample (and a few others I tried):

```<code>('B', 'R', 'B', 'R', 'R') 0.100245
('R', 'R', 'R', 'B', 'B') 0.099789
('R', 'R', 'B', 'B', 'R') 0.099952
('B', 'R', 'R', 'B', 'R') 0.100579
('R', 'R', 'B', 'R', 'B') 0.099732
('R', 'B', 'R', 'R', 'B') 0.100033
('B', 'B', 'R', 'R', 'R') 0.099861
('B', 'R', 'R', 'R', 'B') 0.099941
('R', 'B', 'R', 'B', 'R') 0.100103
('R', 'B', 'B', 'R', 'R') 0.099765
mean: 0.1 stdDev: 0.3% 1000000 samples 10 combos
</code>```

Body:
This will give a uniform distribution of the uniques combinations:

from random import randrange
from collections import Counter
def marblePick(marbles):
    remaining = list(Counter(marbles).elements())
    return [remaining.pop(randrange(r)) for r in range(len(remaining),0,-1)]

The performance seems to be linear and I tested the distribution by sampling as follows:

marbles = {"R":3,"B":2}

N = 1000000
dist = Counter()
for _ in range(N):
    combo = marblePick(marbles)
    dist[tuple(combo)]+=1

for s,c in dist.items():
    print(s,c/N)

import statistics as stats
prop = [c/N for c in dist.values()]
mean = stats.mean(prop)
stdev = stats.stdev(prop)
print("mean:",mean,"stdDev:",f"{100*stdev/mean:.1f}%",N,"samples",len(dist),"combos")

the results are conclusive for this sample (and a few others I tried):

('B', 'R', 'B', 'R', 'R') 0.100245
('R', 'R', 'R', 'B', 'B') 0.099789
('R', 'R', 'B', 'B', 'R') 0.099952
('B', 'R', 'R', 'B', 'R') 0.100579
('R', 'R', 'B', 'R', 'B') 0.099732
('R', 'B', 'R', 'R', 'B') 0.100033
('B', 'B', 'R', 'R', 'R') 0.099861
('B', 'R', 'R', 'R', 'B') 0.099941
('R', 'B', 'R', 'B', 'R') 0.100103
('R', 'B', 'B', 'R', 'R') 0.099765
mean: 0.1 stdDev: 0.3% 1000000 samples 10 combos


问:
How to change color of pagination in bootstrap-vue?
I tried to change it with bootstrap examples but failed.</p>

```<code>        <b-pagination
            v-model="currentPage"
            :total-rows="users.length"
            :per-page="perPage"
            align="fill"
            size='lg'
            first-number
            last-number
            class="my-0"
        ></b-pagination>
</code>```

答:
SCSS

As Troy pointed out in a comment, bootstrap has various SCSS variables you can use to customize the pagination. So if you're using SCSS this would be the preferred way.

View the variables.

CSS

You can add a class to b-pagination and use that class to target the a tags inside the pagination. Check the snippet for an example of this.

You can also use the following props (requires v2.3.0+) to place specific classes on the various types of buttons.
Note these will place the class on the li, so you'll still need CSS to target the a tag.
For more information about the class props check the reference section

```<code>page-class
first-class
last-class
prev-class
next-class
ellipsis-class
</code>```

If you're using a scoped style tag in your components, note you might have to use a deep selector to target that a tags correctly.

new Vue({
  el: '#app'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.customPagination > li > a {
  color: red;
}

.customPagination > li.active > a,
.customPagination > li > a:hover
{
  color: white;
  background-color: green!important;
}</code>```

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.1/dist/bootstrap-vue.css" rel="stylesheet"/>

```

Body:
SCSS

As Troy pointed out in a comment, bootstrap has various SCSS variables you can use to customize the pagination. So if you're using SCSS this would be the preferred way.

View the variables.

CSS

You can add a class to b-pagination and use that class to target the a tags inside the pagination. Check the snippet for an example of this.

You can also use the following props (requires v2.3.0+) to place specific classes on the various types of buttons.
Note these will place the class on the li, so you'll still need CSS to target the a tag.
For more information about the class props check the reference section

page-class
first-class
last-class
prev-class
next-class
ellipsis-class

If you're using a scoped style tag in your components, note you might have to use a deep selector to target that a tags correctly.

new Vue({
  el: '#app'
})

.customPagination > li > a {
  color: red;
}

.customPagination > li.active > a,
.customPagination > li > a:hover
{
  color: white;
  background-color: green!important;
}

<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.4.1/dist/bootstrap-vue.js"></script>

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.1/dist/bootstrap-vue.css" rel="stylesheet"/>

<div id="app">
  <b-pagination
    :total-rows="50"
    :per-page="5"
    class="customPagination"
  >
  </b-pagination>
</div>


问:
google appengine searching buckets to find a particular "content_type" text/csv
I have multiple buckets and i would like to find a the buckets that store the csv files.  I do not know how to search buckets to find what i need. Is there a method to query the buckets to only find content type "text/csv."  Ultimately i am attempting to find the csv files blobkey that begins with "encoded_gs_file:"  Also, what is the relationship between the datastore and storage?

The blobstore viewer that i am running in localhost only shows the encoded_gs_file for images.  But i know that there should be a encoded_gs_file for the csv files.

When i visit the following url:

```<code>http://localhost:8000/datastore?kind=__GsFileInfo__
</code>```

i can see the csv file type, but when i go to this url:

```<code>http://localhost:8000/datastore?kind=__BlobInfo__
</code>```

the csv file does not appear.  I think if i can get the csv file to appear in the ____blobInfo____ endpoint, then i can download it

答:
There is not a specific method to search objects into a bucket, but what you can do is to search using different API methods for example using the JSON API:

1.List all the buckets on your project. https://cloud.google.com/storage/docs/json_api/v1/buckets/list?apix_params=%7B%22project%22%3A%22edp44591%22%7D

2.Then, having the list of buckets you can list all the object in each one
https://cloud.google.com/storage/docs/json_api/v1/objects/list

3.Once you have the list of objects inside the bucket you can filter with you preferred programming language.

Basically you can do the same with the XML API here is the reference to it:
https://cloud.google.com/storage/docs/xml-api/reference-methods

Or using the gsutil tool:
gsutil list  :to list all the bucket on your project: https://cloud.google.com/storage/docs/listing-buckets

gsutil ls -r gs://[BUCKET_NAME]/** : to list all the objects inside your project.
https://cloud.google.com/storage/docs/listing-objects

If you want to see examples about how to use the API with different code-languages go to the document Cloud Storage Client Libraries https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-nodejs

Body:
I have multiple buckets and i would like to find a the buckets that store the csv files.  I do not know how to search buckets to find what i need. Is there a method to query the buckets to only find content type "text/csv."  Ultimately i am attempting to find the csv files blobkey that begins with "encoded_gs_file:"  Also, what is the relationship between the datastore and storage?

The blobstore viewer that i am running in localhost only shows the encoded_gs_file for images.  But i know that there should be a encoded_gs_file for the csv files.

When i visit the following url:

http://localhost:8000/datastore?kind=__GsFileInfo__

i can see the csv file type, but when i go to this url:

http://localhost:8000/datastore?kind=__BlobInfo__

the csv file does not appear.  I think if i can get the csv file to appear in the ____blobInfo____ endpoint, then i can download it


问:
Why is my program skipping my first loop?
I am working on an assignment in C, trying to create a program that simulates a "Rock, Paper, Scissors" match between the user and the computer. Everything is working fine except the for loop I have created is skipping the first iteration of the loop and going straight to my second match. Is there any way to fix this? Code and compilation below

main.c

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

int main(void) {
    srand(time(0)); // This gives the random function a new seedallows me to use time in order to create "random" numbers. //
    time_t t; // Allows the program to store system time values. //

    int R; // This statement declares the variable for the move "Rock". //
    int P; // This statement declares the variable for the move "Paper". //
    int S; // This statement declares the variable for the move "Scissors". //

    int numMatches; // This statement declares the variable for the number of matches that are to be played. //
    int roundNumber; // This statement declares the variable for the current round of the match that is being played. //
    int compMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the computer makes. //
    char userMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the user of the program chooses. //
    int randNumber; // This statement declares the variable for the random number that will be generated. //

    printf("Starting the Rock, Paper, Scissors Game!\n");

    printf("Enter the number of matches to play: ");
    scanf(" %d", &numMatches); // This statement allows the user to input the number of matches he/she wishes to play. //

    for (roundNumber = 1; roundNumber <= numMatches; roundNumber++) { // This for statement first initializes the number of rounds to 1. Then, the statement sets a parameter that the for loop will only continue as long as the number of matches completed is less that than the total matches that are to played. The last statement increments

        printf("\nMatch %d: Enter R for rock, P for paper, or S for scissors: ", roundNumber);
        fflush(stdin);
        userMove = getchar();

        randNumber = (rand() % 3) + 1; //1 to 3//
        compMove = randNumber == 0 ? 'R' : randNumber == 1 ? 'P' : 'S';

        if ((userMove == 'R') && (compMove == 'S')) { // These statements state the result of the game depending on the user's move and the computer's move. //
            printf("The computer chose scissors. You won \n");
        } else
        if ((userMove == 'P') && (compMove == 'R')) {
            printf("The computer chose rock. You won \n");
        } else
        if ((userMove == 'S') && (compMove == 'P')) {
            printf("The computer chose paper. You won \n");
        } else
        if ((userMove == 'R') && (compMove == 'R')) {
            printf("The computer chose rock. You tied \n");
        } else
        if ((userMove == 'P') && (compMove == 'P')) {
            printf("The computer chose paper. You tied \n");
        } else
        if ((userMove == 'S') && (compMove == 'S')) {
            printf("The computer chose scissors. You tied \n");
        } else
        if ((userMove == 'R') && (compMove == 'P')) {
            printf("The computer chose paper. You lose \n");
        } else
        if ((userMove == 'P') && (compMove == 'S')) {
            printf("The computer chose scissors. You lose \n");
        } else
        if ((userMove == 'S') && (compMove == 'R')) {
            printf("The computer chose rock. You lose \n");
        }
    }
    return 0;
}
</code>```

compile

答:
The line:

```<code>userMove = getchar();
</code>```

Catches the char but lets a newline character \n in the buffer caused by pressing Enter, you need to discard it.

You can do, for instance, this:

```<code>userMove = getchar();
getchar(); // <-- catches and discards '\n'
</code>```

I would also get rid of fflush(stdin), it causes undefined behaviour, reasons in Why should I use fflush(stdin) in this program?.

Replace it also with getchar(). Or use type specifier with discard in your scanf function like scanf(" %d%*c", &numMatches);
Here is a working sample

Another thing that is not very good is the fact that none these variables is being used:

```<code>time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //
</code>```

Body:
I am working on an assignment in C, trying to create a program that simulates a "Rock, Paper, Scissors" match between the user and the computer. Everything is working fine except the for loop I have created is skipping the first iteration of the loop and going straight to my second match. Is there any way to fix this? Code and compilation below

main.c

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

int main(void) {
    srand(time(0)); // This gives the random function a new seedallows me to use time in order to create "random" numbers. //
    time_t t; // Allows the program to store system time values. //

    int R; // This statement declares the variable for the move "Rock". //
    int P; // This statement declares the variable for the move "Paper". //
    int S; // This statement declares the variable for the move "Scissors". //

    int numMatches; // This statement declares the variable for the number of matches that are to be played. //
    int roundNumber; // This statement declares the variable for the current round of the match that is being played. //
    int compMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the computer makes. //
    char userMove; // This statement declares the variable that represents the move (rock, paper, or scissors) that the user of the program chooses. //
    int randNumber; // This statement declares the variable for the random number that will be generated. //

    printf("Starting the Rock, Paper, Scissors Game!\n");

    printf("Enter the number of matches to play: ");
    scanf(" %d", &numMatches); // This statement allows the user to input the number of matches he/she wishes to play. //

    for (roundNumber = 1; roundNumber <= numMatches; roundNumber++) { // This for statement first initializes the number of rounds to 1. Then, the statement sets a parameter that the for loop will only continue as long as the number of matches completed is less that than the total matches that are to played. The last statement increments

        printf("\nMatch %d: Enter R for rock, P for paper, or S for scissors: ", roundNumber);
        fflush(stdin);
        userMove = getchar();

        randNumber = (rand() % 3) + 1; //1 to 3//
        compMove = randNumber == 0 ? 'R' : randNumber == 1 ? 'P' : 'S';

        if ((userMove == 'R') && (compMove == 'S')) { // These statements state the result of the game depending on the user's move and the computer's move. //
            printf("The computer chose scissors. You won \n");
        } else
        if ((userMove == 'P') && (compMove == 'R')) {
            printf("The computer chose rock. You won \n");
        } else
        if ((userMove == 'S') && (compMove == 'P')) {
            printf("The computer chose paper. You won \n");
        } else
        if ((userMove == 'R') && (compMove == 'R')) {
            printf("The computer chose rock. You tied \n");
        } else
        if ((userMove == 'P') && (compMove == 'P')) {
            printf("The computer chose paper. You tied \n");
        } else
        if ((userMove == 'S') && (compMove == 'S')) {
            printf("The computer chose scissors. You tied \n");
        } else
        if ((userMove == 'R') && (compMove == 'P')) {
            printf("The computer chose paper. You lose \n");
        } else
        if ((userMove == 'P') && (compMove == 'S')) {
            printf("The computer chose scissors. You lose \n");
        } else
        if ((userMove == 'S') && (compMove == 'R')) {
            printf("The computer chose rock. You lose \n");
        }
    }
    return 0;
}

compile

Body:
The line:

userMove = getchar();

Catches the char but lets a newline character \n in the buffer caused by pressing Enter, you need to discard it.

You can do, for instance, this:

userMove = getchar();
getchar(); // <-- catches and discards '\n'

I would also get rid of fflush(stdin), it causes undefined behaviour, reasons in Why should I use fflush(stdin) in this program?.

Replace it also with getchar(). Or use type specifier with discard in your scanf function like scanf(" %d%*c", &numMatches);
Here is a working sample

Another thing that is not very good is the fact that none these variables is being used:

time_t t; // Allows the program to store system time values. //
int R; // This statement declares the variable for the move "Rock". //
int P; // This statement declares the variable for the move "Paper". //
int S; // This statement declares the variable for the move "Scissors". //


问:
Python ctypes: doesn't load dll as expected
I am trying to load a library in python in Windows 10 (x64).

The cpp file used to generate the library for testing is:

```<code>extern "C" int check() {
  return(1);
}
</code>```

Then I generate the dll with the commands (in x64 Native Tools Command Prompt):

```<code>cl /c mylib.cpp
link /dll /machine:x64 mylib.obj
</code>```

The file mylib.dll is generated.
Then in python, which initializes showing the following string:

```<code>Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
</code>```

I run the following commands:

```<code>import ctypes
lib=ctypes.CDLL("mylib.dll")
lib.check.restype=(ctypes.c_int,)
</code>```

and the last command fails, saying that doesn't recognize check.
I also tried lib._check and using a test C file instead of cpp, with the same result, and also tried using ctypes.WinDLL instead of ctypes.CDLL.

What's wrong? Python is x64 as well as the library mylib.dll...

If I do:

```<code>ctypes.windll.msvcrt.getchar()
</code>```

the functions works ok… Here I use the MSVCRT library, which is automatically accessible when I load ctypes.

Should I compile my library differently?

答:
You need to export your API:

```<code>extern "C" __declspec(dllexport) int check() {
  return 1;
}
</code>```

Also lib.check.restype should not be a tuple.  .argtypes takes a tuple:

```<code>lib.check.argtypes = ()
lib.check.restype = ctypes.c_int
</code>```

FYI, cl /LD mylib.cpp will compile and link a DLL in one step.

Also FYI, CDLL and WinDLL don't matter on x64, but correspond to __cdecl and __stdcall calling convention, respectively, on x86.  x64 has only one calling convention so either will work.

Body:
I am trying to load a library in python in Windows 10 (x64).

The cpp file used to generate the library for testing is:

extern "C" int check() {
  return(1);
}

Then I generate the dll with the commands (in x64 Native Tools Command Prompt):

cl /c mylib.cpp
link /dll /machine:x64 mylib.obj

The file mylib.dll is generated.
Then in python, which initializes showing the following string:

Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32

I run the following commands:

import ctypes
lib=ctypes.CDLL("mylib.dll")
lib.check.restype=(ctypes.c_int,)

and the last command fails, saying that doesn't recognize check.
I also tried lib._check and using a test C file instead of cpp, with the same result, and also tried using ctypes.WinDLL instead of ctypes.CDLL.

What's wrong? Python is x64 as well as the library mylib.dll...

If I do:

ctypes.windll.msvcrt.getchar()

the functions works ok… Here I use the MSVCRT library, which is automatically accessible when I load ctypes.

Should I compile my library differently?

Body:
You need to export your API:

extern "C" __declspec(dllexport) int check() {
  return 1;
}

Also lib.check.restype should not be a tuple.  .argtypes takes a tuple:

lib.check.argtypes = ()
lib.check.restype = ctypes.c_int

FYI, cl /LD mylib.cpp will compile and link a DLL in one step.

Also FYI, CDLL and WinDLL don't matter on x64, but correspond to __cdecl and __stdcall calling convention, respectively, on x86.  x64 has only one calling convention so either will work.


问:
How to compare documents in the same collection?
I am a novice when it comes to mongo as I have traditionally only worked with Oracle database.
I have a mongo database that's storing bitbucket data in columns like so:

```<code>_id | _class | collectorItemId| firstEverCommit | scmUrl | scmBranch | scmAuthor | scmCommitTimestamp
</code>```

There are a few more columns in there that I've omitted for the sake of time. For the scmBranch column, the column is populated with one of two strings: "master" or "develop".
Here is a sample of what the data looks like:

Here is the document view of one of the rows:

```<code>{
"_id" : ObjectId("5e39d6a0330c130006a042c6"),
"collectorItemId" : ObjectId("5e33a6b9887ef5000620a0c0"),
"firstEverCommit" : false,
"scmUrl" : "sampleRepo1",
"scmBranch" : "master",
"scmRevisionNumber" : "a2ad6842468eb55bffcbe7d700b6addd3eb11629",
"scmAuthor" : "son123",
"scmCommitTimestamp" : NumberLong(1580841662000)
}
</code>```

I am now trying to formulate mongo queries that will get me the following data:

```<code> 1. For each scmUrl, If max(scmCommitTimestamp) where scmBranch =
    "develop" > max(scmCommitTimestamp) where scmBranch = "master" THEN
    count the number of rows (i.e commits) where scmBranch = "develop"
    AND scmCommitTimestamp > max(scmCommitTimestamp) where scmBranch =
    "master"

 2. For the results found in #1, find the oldest commit and newest
    commit
</code>```

So far, the best mongo query I've been able to come up with is the following:

```<code>db.bitbucket.aggregate([{
    "$group": {
        "_id": {
            "scmUrl": "$scmUrl",
            "scmBranch": "$scmBranch"
        },
        "MostRecentCommit": {
            "$max": {"$toDate":"$scmCommitTimestamp"}
        }
    }
},{
    "$project": {
        "RepoName": {"$substr": ["$_id.scmUrl",39,-1]},
        "Branch": "$_id.scmBranch",
        "MostRecentCommit": "$MostRecentCommit"
    }
},{
   "$sort":{
       "RepoName":1,
       "Branch":1
       }

}
])
</code>```

But this only gets me back the most recent commit for the develop branch and the master branch of each scmUrl (i.e repo), like so:

Ideally, I'd like to get back a table of results with the following columns:

```<code>scmUrl/RepoName | Number of commits on develop branch that are not on master branch| oldest commit in develop branch that's not in master branch | newest commit in develop branch that's not in master branch
</code>```

How can I modify my mongo query to extract the data that I want?

答:
You could try something like this.

Below query will grab the latest commit date from master for each repo. After you have the latest commit date you will join back to the same collection to pull all commits where branch is develop and has newer commits than master branch for each repo.

```<code>db.bitbucket.aggregate([
  {"$match":{"scmBranch":"master"}},
  {"$group":{"_id":"$scmUrl","recentcommitdate":{"$max":"$scmCommitTimestamp"}}},
  {"$lookup":{
   "from":"bitbucket",
    "let":{"scmUrl":"$_id","recentcommitdate":"$recentcommitdate"},
    "pipeline":[
      {"$match":{"$expr":
        {"$and":[
          {"$eq":["$scmBranch","develop"]},
          {"$eq":["$scmUrl","$$scmUrl"]},
          {"$gte":["$scmCommitTimestamp", "$$recentcommitdate"]}
        ]}
      }},
      {"$sort":{"scmCommitTimestamp":-1}}
    ],
  "as":"commits"
  }},
  {"$match":{"commits.0":{"$exists":true}}},
  {"$project":{
     "commits":{"$size":"$commits"},
     "lastcommit":{"$arrayElemAt":["$commits",0]},
     "firstcommit":{"$arrayElemAt":["$commits",-1]}
  }}
])
</code>```

Sample added here https://mongoplayground.net/p/wLnFY0H_nJz

Update for revision ids

```<code>db.bitbucket.aggregate([
  {"$match":{"scmBranch":"master"}},
  {"$group":{"_id":"$scmUrl","revisionIds":{"$push":"$scmRevisionNumber"}}},
  {"$lookup":{
   "from":"bitbucket",
    "let":{"scmUrl":"$_id","revisionIds":"$revisionIds"},
    "pipeline":[
      {"$match":{"$expr":
        {"$and":[
          {"$eq":["$scmBranch","develop"]},
          {"$eq":["$scmUrl","$$scmUrl"]},
          {"$not":[{"$in":["$scmRevisionNumber","$$revisionIds"]}]}
        ]}
      }},
      {"$sort":{"scmCommitTimestamp":-1}}
    ],
  "as":"commits"
  }},
  {"$match":{"commits.0":{"$exists":true}}},
  {"$project":{
     "commits":{"$size":"$commits"},
     "lastcommit":{"$arrayElemAt":["$commits",0]},
     "firstcommit":{"$arrayElemAt":["$commits",-1]}
  }}
])
</code>```

Body:
I am a novice when it comes to mongo as I have traditionally only worked with Oracle database.
I have a mongo database that's storing bitbucket data in columns like so:

_id | _class | collectorItemId| firstEverCommit | scmUrl | scmBranch | scmAuthor | scmCommitTimestamp

There are a few more columns in there that I've omitted for the sake of time. For the scmBranch column, the column is populated with one of two strings: "master" or "develop".
Here is a sample of what the data looks like:

Here is the document view of one of the rows:

{
"_id" : ObjectId("5e39d6a0330c130006a042c6"),
"collectorItemId" : ObjectId("5e33a6b9887ef5000620a0c0"),
"firstEverCommit" : false,
"scmUrl" : "sampleRepo1",
"scmBranch" : "master",
"scmRevisionNumber" : "a2ad6842468eb55bffcbe7d700b6addd3eb11629",
"scmAuthor" : "son123",
"scmCommitTimestamp" : NumberLong(1580841662000)
}

I am now trying to formulate mongo queries that will get me the following data:

 1. For each scmUrl, If max(scmCommitTimestamp) where scmBranch =
    "develop" > max(scmCommitTimestamp) where scmBranch = "master" THEN
    count the number of rows (i.e commits) where scmBranch = "develop"
    AND scmCommitTimestamp > max(scmCommitTimestamp) where scmBranch =
    "master"

 2. For the results found in #1, find the oldest commit and newest
    commit

So far, the best mongo query I've been able to come up with is the following:

db.bitbucket.aggregate([{
    "$group": {
        "_id": {
            "scmUrl": "$scmUrl",
            "scmBranch": "$scmBranch"
        },
        "MostRecentCommit": {
            "$max": {"$toDate":"$scmCommitTimestamp"}
        }
    }
},{
    "$project": {
        "RepoName": {"$substr": ["$_id.scmUrl",39,-1]},
        "Branch": "$_id.scmBranch",
        "MostRecentCommit": "$MostRecentCommit"
    }
},{
   "$sort":{
       "RepoName":1,
       "Branch":1
       }

}
])

But this only gets me back the most recent commit for the develop branch and the master branch of each scmUrl (i.e repo), like so:

Ideally, I'd like to get back a table of results with the following columns:

scmUrl/RepoName | Number of commits on develop branch that are not on master branch| oldest commit in develop branch that's not in master branch | newest commit in develop branch that's not in master branch

How can I modify my mongo query to extract the data that I want?

Body:
You could try something like this.

Below query will grab the latest commit date from master for each repo. After you have the latest commit date you will join back to the same collection to pull all commits where branch is develop and has newer commits than master branch for each repo.

db.bitbucket.aggregate([
  {"$match":{"scmBranch":"master"}},
  {"$group":{"_id":"$scmUrl","recentcommitdate":{"$max":"$scmCommitTimestamp"}}},
  {"$lookup":{
   "from":"bitbucket",
    "let":{"scmUrl":"$_id","recentcommitdate":"$recentcommitdate"},
    "pipeline":[
      {"$match":{"$expr":
        {"$and":[
          {"$eq":["$scmBranch","develop"]},
          {"$eq":["$scmUrl","$$scmUrl"]},
          {"$gte":["$scmCommitTimestamp", "$$recentcommitdate"]}
        ]}
      }},
      {"$sort":{"scmCommitTimestamp":-1}}
    ],
  "as":"commits"
  }},
  {"$match":{"commits.0":{"$exists":true}}},
  {"$project":{
     "commits":{"$size":"$commits"},
     "lastcommit":{"$arrayElemAt":["$commits",0]},
     "firstcommit":{"$arrayElemAt":["$commits",-1]}
  }}
])

Sample added here https://mongoplayground.net/p/wLnFY0H_nJz

Update for revision ids

db.bitbucket.aggregate([
  {"$match":{"scmBranch":"master"}},
  {"$group":{"_id":"$scmUrl","revisionIds":{"$push":"$scmRevisionNumber"}}},
  {"$lookup":{
   "from":"bitbucket",
    "let":{"scmUrl":"$_id","revisionIds":"$revisionIds"},
    "pipeline":[
      {"$match":{"$expr":
        {"$and":[
          {"$eq":["$scmBranch","develop"]},
          {"$eq":["$scmUrl","$$scmUrl"]},
          {"$not":[{"$in":["$scmRevisionNumber","$$revisionIds"]}]}
        ]}
      }},
      {"$sort":{"scmCommitTimestamp":-1}}
    ],
  "as":"commits"
  }},
  {"$match":{"commits.0":{"$exists":true}}},
  {"$project":{
     "commits":{"$size":"$commits"},
     "lastcommit":{"$arrayElemAt":["$commits",0]},
     "firstcommit":{"$arrayElemAt":["$commits",-1]}
  }}
])


问:
HTTP Event Cloud Function: request body value is undefined
When sending {"identifiant": "iJXB5E0PsoKq2XrU26q6"} to the below Cloud Function, I cannot get the identifiant value in the request body and it will always return PROBLEMAS NO REQUEST.

```<code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

exports.meusCandidatos = functions.https.onRequest((req, res) => {
    const identifiant = req.body.identifiant;

    if(identifiant) res.status(200).json('ok').end();

    res.status(500).json('PROBLEMAS NO REQUEST').end();

});
</code>```

答:
Unlike a Callable function, the body of a request is not parsed automatically and needs to be parsed before you can use it.

In addition, json(...) will call end() internally so you don't need both. Also make sure that you don't call end(), send(), json(), etc. multiple times, as this will lead to errors.

```<code>const jsonParser = require('body-parser').json();

exports.meusCandidatos = functions.https.onRequest((req, res) => {
    jsonParser(req, res, (err) => {
      if (err) {
        res.status(500).json({error: err.message});
        return; // stop here
      }

      const identifiant = req.body.identifiant;

      if (!identifiant) {
        res.status(500).json({error: 'PROBLEMAS NO REQUEST'});
        return; // stop here
      }

      // continue
      res.status(200).json({ status: 'ok' });
  })
});
</code>```

Body:
When sending {"identifiant": "iJXB5E0PsoKq2XrU26q6"} to the below Cloud Function, I cannot get the identifiant value in the request body and it will always return PROBLEMAS NO REQUEST.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

exports.meusCandidatos = functions.https.onRequest((req, res) => {
    const identifiant = req.body.identifiant;

    if(identifiant) res.status(200).json('ok').end();

    res.status(500).json('PROBLEMAS NO REQUEST').end();

});

Body:
Unlike a Callable function, the body of a request is not parsed automatically and needs to be parsed before you can use it.

In addition, json(...) will call end() internally so you don't need both. Also make sure that you don't call end(), send(), json(), etc. multiple times, as this will lead to errors.

const jsonParser = require('body-parser').json();

exports.meusCandidatos = functions.https.onRequest((req, res) => {
    jsonParser(req, res, (err) => {
      if (err) {
        res.status(500).json({error: err.message});
        return; // stop here
      }

      const identifiant = req.body.identifiant;

      if (!identifiant) {
        res.status(500).json({error: 'PROBLEMAS NO REQUEST'});
        return; // stop here
      }

      // continue
      res.status(200).json({ status: 'ok' });
  })
});


问:
Simple web app of Bidi, Ring and Lein gives a 500 error
I am learning Clojure for the web. I am trying to implement Bidi and Ring in Lein app. When I open the site I get a 500 error:

HTTP ERROR: 500

Problem accessing /. Reason:

Response map is nil

Powered by Jetty://

My files are the following:

./project.clj

```<code>(defproject bidi-ring "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :dependencies [[org.clojure/clojure "1.10.0"]
                 [bidi "2.1.6"]
                 [ring/ring-core "1.6.3"]
                 [ring/ring-jetty-adapter "1.6.3"]]
  :repl-options {:init-ns my.app}
  :main my.app)
</code>```

./src/my/handler.clj

```<code>(ns my.handler (:gen-class)
    (:require [bidi.ring :refer (make-handler)]
              [ring.util.response :as res]))
(defn index-handler
  [request]
  (res/response "Homepage"))
(defn article-handler
  [{:keys [route-params]}]
  (res/response (str "You are viewing article: " (:id route-params))))
(def handler
  (make-handler ["/" {"index.html" index-handler
                      ["articles/" :id "/article.html"] article-handler}]))
</code>```

./src/my/app.clj

```<code>(ns my.app (:gen-class)
    (:require [my.handler :refer [handler]]
              [ring.middleware.session :refer [wrap-session]]
              [ring.middleware.flash :refer [wrap-flash]]))
(use 'ring.adapter.jetty)

(defn -main []

  (def app
    (-> handler
        wrap-session
        wrap-flash))

  (run-jetty app {:port 3000}))
</code>```

How to fix it?

答:
You have made a mistake in your routes.  Look at this Bidi demo repo:

https://github.com/io-tupelo-demo/bidi

The code on line 16 of tst.demo.core shows what is happening.  In bidi, a route "/index.html" does not include the degenerate route "/":

```<code>  (let [routes   ["/" ; common prefix
                  {"index.html"   :index
                   "article.html" :article}]

        routes-2 ["/" ; common prefix
                  {""             :index ; add a default route so "/" and "/index.html" both => `:index` handler
                   "index.html"   :index
                   "article.html" :article}]]
    (is= (bidi/match-route routes "/index.html") {:handler :index}) ; normal case

    (is= (bidi/match-route routes "/") nil) ; plain "/" route is not available, has no default

    (is= (bidi/match-route routes-2 "/") {:handler :index})) ; Now we get the :index route
</code>```

When no route matches, match-route returns a nil, which the server then translates into a 500 not-found that is sent to the browser.

Body:
I am learning Clojure for the web. I am trying to implement Bidi and Ring in Lein app. When I open the site I get a 500 error:

HTTP ERROR: 500

Problem accessing /. Reason:

Response map is nil

Powered by Jetty://

My files are the following:

./project.clj

(defproject bidi-ring "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :dependencies [[org.clojure/clojure "1.10.0"]
                 [bidi "2.1.6"]
                 [ring/ring-core "1.6.3"]
                 [ring/ring-jetty-adapter "1.6.3"]]
  :repl-options {:init-ns my.app}
  :main my.app)

./src/my/handler.clj

(ns my.handler (:gen-class)
    (:require [bidi.ring :refer (make-handler)]
              [ring.util.response :as res]))
(defn index-handler
  [request]
  (res/response "Homepage"))
(defn article-handler
  [{:keys [route-params]}]
  (res/response (str "You are viewing article: " (:id route-params))))
(def handler
  (make-handler ["/" {"index.html" index-handler
                      ["articles/" :id "/article.html"] article-handler}]))

./src/my/app.clj

(ns my.app (:gen-class)
    (:require [my.handler :refer [handler]]
              [ring.middleware.session :refer [wrap-session]]
              [ring.middleware.flash :refer [wrap-flash]]))
(use 'ring.adapter.jetty)

(defn -main []

  (def app
    (-> handler
        wrap-session
        wrap-flash))

  (run-jetty app {:port 3000}))

How to fix it?

Body:
You have made a mistake in your routes.  Look at this Bidi demo repo:

https://github.com/io-tupelo-demo/bidi

The code on line 16 of tst.demo.core shows what is happening.  In bidi, a route "/index.html" does not include the degenerate route "/":

  (let [routes   ["/" ; common prefix
                  {"index.html"   :index
                   "article.html" :article}]

        routes-2 ["/" ; common prefix
                  {""             :index ; add a default route so "/" and "/index.html" both => `:index` handler
                   "index.html"   :index
                   "article.html" :article}]]
    (is= (bidi/match-route routes "/index.html") {:handler :index}) ; normal case

    (is= (bidi/match-route routes "/") nil) ; plain "/" route is not available, has no default

    (is= (bidi/match-route routes-2 "/") {:handler :index})) ; Now we get the :index route

When no route matches, match-route returns a nil, which the server then translates into a 500 not-found that is sent to the browser.


问:
FullCalendar v4 - fullCalendar is not a function
I'm using FullCalendar 4.3.1 . Calendar is displayed correctly but, I can´t add event dynamically. And I get this error:
When using JQuery:

TypeError: $(...).fullCalendar is not a function

I try it without JQuery and still not working:

TypeError: document.getElementById(...).fullCalendar is not a function

I have this page:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title></title>

        <link href = 'libs/fullcalendar/core/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/daygrid/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/timegrid/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/list/main.css' rel = 'stylesheet' />

                 Add event

```

Where is the problem?

答:
I don't think you're accessing the calendar object correctly.

<!DOCTYPE html>

<meta charset='utf-8' />

  <title>
    Add an event dynamically - Demos | FullCalendar
  </title>

<link href='/assets/demo-to-codepen.css' rel='stylesheet' />

<link href='https://unpkg.com/@fullcalendar/core@4.3.1/main.min.css' rel='stylesheet' />

  <link href='https://unpkg.com/@fullcalendar/daygrid@4.3.0/main.min.css' rel='stylesheet' />

```

Review the source code on this demo page:
https://fullcalendar.io/docs/Calendar-addEvent-demo

Body:
I'm using FullCalendar 4.3.1 . Calendar is displayed correctly but, I can´t add event dynamically. And I get this error:
When using JQuery:

TypeError: $(...).fullCalendar is not a function

I try it without JQuery and still not working:

TypeError: document.getElementById(...).fullCalendar is not a function

I have this page:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title></title>

        <link href = 'libs/fullcalendar/core/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/daygrid/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/timegrid/main.css' rel = 'stylesheet' />
        <link href = 'libs/fullcalendar/list/main.css' rel = 'stylesheet' />

                 Add event

Where is the problem?

Body:
I don't think you're accessing the calendar object correctly.

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />

  <title>
    Add an event dynamically - Demos | FullCalendar
  </title>

<link href='/assets/demo-to-codepen.css' rel='stylesheet' />

  <style>

    html, body {
      margin: 0;
      padding: 0;
      font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
      font-size: 14px;
    }

    #calendar {
      max-width: 900px;
      margin: 40px auto;
    }

  </style>

<link href='https://unpkg.com/@fullcalendar/core@4.3.1/main.min.css' rel='stylesheet' />

  <link href='https://unpkg.com/@fullcalendar/daygrid@4.3.0/main.min.css' rel='stylesheet' />

<script src='/assets/demo-to-codepen.js'></script>

<script src='https://unpkg.com/@fullcalendar/core@4.3.1/main.min.js'></script>

  <script src='https://unpkg.com/@fullcalendar/daygrid@4.3.0/main.min.js'></script>

  <script>

  document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
      plugins: [ 'dayGrid' ],
      defaultView: 'dayGridMonth',
      header: {
        center: 'addEventButton'
      },
      customButtons: {
        addEventButton: {
          text: 'add event...',
          click: function() {
            var dateStr = prompt('Enter a date in YYYY-MM-DD format');
            var date = new Date(dateStr + 'T00:00:00'); // will be in local time

            if (!isNaN(date.valueOf())) { // valid?
              calendar.addEvent({
                title: 'dynamic event',
                start: date,
                allDay: true
              });
              alert('Great. Now, update your database...');
            } else {
              alert('Invalid date.');
            }
          }
        }
      }
    });

    calendar.render();
  });

</script>

</head>
<body>
  <div class='demo-topbar'>

</div>

  <div id='calendar'></div>
</body>

</html>

Review the source code on this demo page:
https://fullcalendar.io/docs/Calendar-addEvent-demo


问:
Modelling message queues
I've this system that consists of lots of different stages piped together.
Specifically, I've got lots of different processes that communicate via tcp-ip; messages are exchanged
via a packet oriented protocol (more messages can be stuffed together in a single wire-protocol data unit
if certains conditions are met); I've control flow queues too - sockets are non blocking, if I fail to send
I queue messages or even coalesce them in the send queue;
of course what happens at runtime depends on tcp ip control flow underneath, so I'd like to model the tcp ip queues, too.
So the question is - can anyone share their thoughts on how to make a simulation for my system?
I've thought to make a simulator for it - that is: a program with a queue data structure for every queue
I have in my model, for each time tick I make the model evolve according to my understanding of the sytstem
i.e. if the data structure for the tcp buffer in my model says it has space enough I decrement the message number
in the output queue and decrease the available space counter in the tcp buffer model by the size of the message, and so on - then I make the
tcp buffer empty at a rate based on the bandwidth for the tcp link
(of course I'm making the hypothesis that I'm pumping lots of data and that the only parameter for the tcp link
is bandwidth).
Building such a thing seems a lot of effort and I'm not sure it is what I need.
Maybe I'd better off with some kind of excel spreadsheet model, but I'm not sure how to structure it.</p>

答: You might get a still useful but simpler to create model by using a discrete event simulation tool or library. You still have to duplicate most of the structure of your application in the form the model understands, but get tools for injecting different distributions of message rates and maybe can play with different scenarios more easily.</p>

OwnerDisplayName: vlvlvlvlvl

ContentLicense: CC BY-SA 2.5

Title: Modelling message queues

OwnerDisplayName: Pete Kirkham


问:
Join one row with last foregoing date in Vertica
I want to get the status in table B that was current on the date of an event in table A.

```<code>Table A
Person: Date:       Event
Bob     2020-01-05  Party

Table B
Person:  Date: Status
Bob      2020-01-08     Awake
Bob      2020-01-03     Dinner
Bob      2020-01-01     Cycling
</code>```

So the right result will be

```<code>Bob     2020-01-05  Party Dinner
</code>```

I tried this but got error 'Correlated subquery expression without aggregates and with limit is not supported'.

```<code>SELECT
    A.Person,
    A.Date,
    A.Event,
    (
        SELECT Status FROM B
        WHERE A.Person = B.Person AND B.Date <= A.Date
        ORDER BY B.Date desc
        LIMIT 1
    ) AS Status
FROM A
</code>```

Can anyone tell me what I should do instead? I tried a few other ideas but keep running into other errors.

答:
Vertica has the "Event Series Join" !

left, right or full outer join two tables with the INTERPOLATE PREVIOUS value predicate, which joins the current row with the immediately preceding row of the other table, according to the join column:

```<code>WITH
a(person, dt,Event) AS (
SELECT 'Bob',DATE '2020-01-05','Party'
)
,
b(person,dt,status) AS (
          SELECT 'Bob', DATE '2020-01-08','Awake'
UNION ALL SELECT 'Bob', DATE '2020-01-03','Dinner'
UNION ALL SELECT 'Bob', DATE '2020-01-01','Cycling'
)
SELECT
  a.person
, a.dt
, a.event
, b.status
FROM a
LEFT OUTER JOIN b
 ON a.person = b.person
AND a.dt INTERPOLATE PREVIOUS VALUE b.dt
;
-- out  person |     dt     | event | status
-- out --------+------------+-------+--------
-- out  Bob    | 2020-01-05 | Party | Dinner
</code>```

Body:
I want to get the status in table B that was current on the date of an event in table A.

Table A
Person: Date:       Event
Bob     2020-01-05  Party

Table B
Person:  Date: Status
Bob      2020-01-08     Awake
Bob      2020-01-03     Dinner
Bob      2020-01-01     Cycling

So the right result will be

Bob     2020-01-05  Party Dinner

I tried this but got error 'Correlated subquery expression without aggregates and with limit is not supported'.

SELECT
    A.Person,
    A.Date,
    A.Event,
    (
        SELECT Status FROM B
        WHERE A.Person = B.Person AND B.Date <= A.Date
        ORDER BY B.Date desc
        LIMIT 1
    ) AS Status
FROM A

Can anyone tell me what I should do instead? I tried a few other ideas but keep running into other errors.

Body:
Vertica has the "Event Series Join" !

left, right or full outer join two tables with the INTERPOLATE PREVIOUS value predicate, which joins the current row with the immediately preceding row of the other table, according to the join column:

WITH
a(person, dt,Event) AS (
SELECT 'Bob',DATE '2020-01-05','Party'
)
,
b(person,dt,status) AS (
          SELECT 'Bob', DATE '2020-01-08','Awake'
UNION ALL SELECT 'Bob', DATE '2020-01-03','Dinner'
UNION ALL SELECT 'Bob', DATE '2020-01-01','Cycling'
)
SELECT
  a.person
, a.dt
, a.event
, b.status
FROM a
LEFT OUTER JOIN b
 ON a.person = b.person
AND a.dt INTERPOLATE PREVIOUS VALUE b.dt
;
-- out  person |     dt     | event | status
-- out --------+------------+-------+--------
-- out  Bob    | 2020-01-05 | Party | Dinner


问:
call to pure virtual function from base class constructor
I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

I want each derived class to call it in their constructor

then I put it in base class(MyBase) constructor

```<code> class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }
</code>```

but I get a linker error.

```<code> this is error message :

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)
</code>```

I want force to all derived classes to...

```<code>A- implement it

B- call it in their constructor
</code>```

How I must do it?

答:
I can offer a work around / "companion" to your abstract base class using MACROS rather than templates, or staying purely within the "natural" constraints of the language.

Create a base class with an init function e.g.:

```<code>class BaseClass
{
public:
    BaseClass(){}
    virtual ~BaseClass(){}
    virtual void virtualInit( const int i=0 )=0;
};
</code>```

Then, add a macro for a constructor.  Note there is no reason to not add multiple constructor definitions here, or have multiple macros to choose from.

```<code>#define BASECLASS_INT_CONSTRUCTOR( clazz ) \
    clazz( const int i ) \
    { \
        virtualInit( i ); \
    }
</code>```

Finally, add the macro to your derivation:

```<code>class DervivedClass : public BaseClass
{
public:
    DervivedClass();
    BASECLASS_INT_CONSTRUCTOR( DervivedClass )
    virtual ~DervivedClass();

    void virtualInit( const int i=0 )
    {
        x_=i;
    }

    int x_;
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

I want each derived class to call it in their constructor

then I put it in base class(MyBase) constructor

 class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }

but I get a linker error.

 this is error message :

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)

I want force to all derived classes to...

A- implement it

B- call it in their constructor

How I must do it?

Body:
I can offer a work around / "companion" to your abstract base class using MACROS rather than templates, or staying purely within the "natural" constraints of the language.

Create a base class with an init function e.g.:

class BaseClass
{
public:
    BaseClass(){}
    virtual ~BaseClass(){}
    virtual void virtualInit( const int i=0 )=0;
};

Then, add a macro for a constructor.  Note there is no reason to not add multiple constructor definitions here, or have multiple macros to choose from.

#define BASECLASS_INT_CONSTRUCTOR( clazz ) \
    clazz( const int i ) \
    { \
        virtualInit( i ); \
    }

Finally, add the macro to your derivation:

class DervivedClass : public BaseClass
{
public:
    DervivedClass();
    BASECLASS_INT_CONSTRUCTOR( DervivedClass )
    virtual ~DervivedClass();

    void virtualInit( const int i=0 )
    {
        x_=i;
    }

    int x_;
};


问:
Array function for calculating Option prices
I'm trying to implement my first BS option model in Python.Instead of passing one Underlying price at a time however, I would like to pass an array. Here's the code and the error message:

```<code>xS=np.arange(10,110,10)

C=np.maximum(xS-K,0)

def bsm_call(S,K,T,r,sigma):

    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]

    d2=[d1-sigma*pow(T,0.5)]

    vC=[S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)]

    return np.array(vC)

extC=bsm_call(xS,K,T,r,sigma)
</code>```

generates: TypeError: unsupported operand type(s) for -: 'list' and 'float'

Not sure what this means, but I think it doesn't like the way I'm passing the xS array. So just to test, I tried:

```<code>def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    return np.array(d1)

test1=test(xS,K,T,r,sigma)
print(test1)
</code>```

This gave me some values for d1 (not sure if they are correct....but at-least the code worked). So, encouraged by this, I tried adding a second line:

```<code>def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    d2=[d1-sigma*pow(T,0.5) for S in xS]
    return np.array(d1+d2)

test1=test(xS,K,T,r,sigma)
print(test1)
</code>```

The error message is now:

I'm trying to avoid looping through the xS array "directly". Obviously, not nuanced enough in Python to to do it....would appreciate some suggestions. Thanks,C

答:
```<code>d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
</code>```

d1 is a simple Python list.

```<code>d2=[d1-sigma*pow(T,0.5) for S in xS]
</code>```

Here, you're trying to subtract a float value from an entire list, and do it len(xS) times.  What functionality do you think you should get from this?  It's certainly not legal.

You can subtract a float from a NumPy array, but not from a list.

Body:
I'm trying to implement my first BS option model in Python.Instead of passing one Underlying price at a time however, I would like to pass an array. Here's the code and the error message:

xS=np.arange(10,110,10)

C=np.maximum(xS-K,0)

def bsm_call(S,K,T,r,sigma):

    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]

    d2=[d1-sigma*pow(T,0.5)]

    vC=[S * stats.norm.cdf(d1,0,1) - K * exp(-r*T) * stats.norm.cdf(d2,0,1)]

    return np.array(vC)

extC=bsm_call(xS,K,T,r,sigma)

generates: TypeError: unsupported operand type(s) for -: 'list' and 'float'

Not sure what this means, but I think it doesn't like the way I'm passing the xS array. So just to test, I tried:

def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    return np.array(d1)

test1=test(xS,K,T,r,sigma)
print(test1)

This gave me some values for d1 (not sure if they are correct....but at-least the code worked). So, encouraged by this, I tried adding a second line:

def test(S,K,T,r,sigma):
    d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]
    d2=[d1-sigma*pow(T,0.5) for S in xS]
    return np.array(d1+d2)

test1=test(xS,K,T,r,sigma)
print(test1)

The error message is now:

I'm trying to avoid looping through the xS array "directly". Obviously, not nuanced enough in Python to to do it....would appreciate some suggestions. Thanks,C

Body:
d1=[(log(S/K) + 0.5 * pow(sigma,2)*T)/(sigma*pow(T,0.5)) for S in xS ]

d1 is a simple Python list.

d2=[d1-sigma*pow(T,0.5) for S in xS]

Here, you're trying to subtract a float value from an entire list, and do it len(xS) times.  What functionality do you think you should get from this?  It's certainly not legal.

You can subtract a float from a NumPy array, but not from a list.


问:
Validate if 2 elements have same attribute value
In my e-commerce environment, I need a jQuery validation between 2 product attributes. Simplified it needs to check if the cart has a product which is present on the same page:

```<code><! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
    <li class="woocommerce-mini-cart-item mini_cart_item">
        <a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6735" data-cart_item_key="..." ></a>
    </li>
</ul>

<! –– Product ––>
<article class="post-6735 product" data-id="6735">
    <div class="product_wrapper">
        <a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
    </div>
</article>
</code>```

I would like to be able to check if the attribute and its value from data-product_id within the cart is the exact same as in article a.button element. My approach:

```<code>jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id').each( function() {
    if( jQuery('article a.button')/*check if it is the same*/){
        // do something here
    }
});
</code>```

As you can see the ID number 6735 is in more attributes. So perhaps a different way is also possible?

答:
To get current_ProductId, You just need to get from $('article').data('id')

To loop through all mini cart items, You just need mini_cart_item

As you can see, we can get data attribute value by using data

var current_ProductId = $('article').data('id');

$('.mini_cart_item').each(function() {
   var productId_MiniCartItem = $(this).find('a').data('product_id');

   if(productId_MiniCartItem == current_ProductId){
        // do something here
        console.log("ProductId: " + productId_MiniCartItem + " has been ordered");
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
    <li class="woocommerce-mini-cart-item mini_cart_item">
        6735
    </li>
    <li class="woocommerce-mini-cart-item mini_cart_item">
        6736
    </li>
</ul>

<! –– Product ––>
<article class="post-6735 product" data-id="6735">
    <div class="product_wrapper">
        href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
    </div>
</article></code>```

Body:
In my e-commerce environment, I need a jQuery validation between 2 product attributes. Simplified it needs to check if the cart has a product which is present on the same page:

<! –– Cart ––>

<! –– Product ––>

        <a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"

I would like to be able to check if the attribute and its value from data-product_id within the cart is the exact same as in article a.button element. My approach:

jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id').each( function() {
    if( jQuery('article a.button')/*check if it is the same*/){
        // do something here
    }
});

As you can see the ID number 6735 is in more attributes. So perhaps a different way is also possible?

Body:
To get current_ProductId, You just need to get from $('article').data('id')

To loop through all mini cart items, You just need mini_cart_item

As you can see, we can get data attribute value by using data

var current_ProductId = $('article').data('id');

$('.mini_cart_item').each(function() {
   var productId_MiniCartItem = $(this).find('a').data('product_id');

   if(productId_MiniCartItem == current_ProductId){
        // do something here
        console.log("ProductId: " + productId_MiniCartItem + " has been ordered");
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
    <li class="woocommerce-mini-cart-item mini_cart_item">
        <a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6735" data-cart_item_key="..." >6735</a>
    </li>
    <li class="woocommerce-mini-cart-item mini_cart_item">
        <a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6736" data-cart_item_key="..." >6736</a>
    </li>
</ul>

<! –– Product ––>
<article class="post-6735 product" data-id="6735">
    <div class="product_wrapper">
        <a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
    </div>
</article>


问:
.net core COM with Excel range
I have an issue where I am unable to access the Name object of a range. So, I am calling Excel.Application.get_Range() and passing in a name. It returns a non-null object and I can access methods. However, Range.Name returns a System.__ComObject(). If I try to access Range.Name.Name I get an exception similar to the following

```<code>Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for "Name"
</code>```

Also, this project is one that I migrated from .net Framework to .net Core. The exact same code works in Framework. I have tried various methods of trying to determine what the underlying type is (because it does not appear to be a Name object). ITypeInfo returns that the typename is Name so it does appear to be a name object.

I'm at a loss as to why I'm unable to access Name.Name in .net core. When I check the .net Core Excel sample they never access a name object.

Also, I am able to access other COM objects like ListObject just fine.

答:
I figured out what the issue is. For anyone else running into this with .net Core, the problem is that .net core appears to not support dynamic types through COM automatically. This is discussed in the following github issue Github issue about dynamic not working. Where it talks about why this doesn't work.

Basically, for my specific case I needed to cast the type manually and then it worked. This also impacts use of IEnumerable COM types needing to be cast directly to IEnumerable before iterating through them.

Assuming you have the following using statement.

```<code>using Excel = Microsoft.Office.Interop.Excel;
</code>```

I had to turn the following:

```<code>return range.Name.Name;
</code>```

into

```<code>return ((Excel.Name)range.Name).Name;
</code>```

As an aside, I also noticed that if you copy/paste the cast above into the debug watch window it does not display properly and instead shows an exception about an invalid cast.

Title: .net core COM with Excel range

Body:
I have an issue where I am unable to access the Name object of a range. So, I am calling Excel.Application.get_Range() and passing in a name. It returns a non-null object and I can access methods. However, Range.Name returns a System.__ComObject(). If I try to access Range.Name.Name I get an exception similar to the following

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.__ComObject' does not contain a definition for "Name"

Also, this project is one that I migrated from .net Framework to .net Core. The exact same code works in Framework. I have tried various methods of trying to determine what the underlying type is (because it does not appear to be a Name object). ITypeInfo returns that the typename is Name so it does appear to be a name object.

I'm at a loss as to why I'm unable to access Name.Name in .net core. When I check the .net Core Excel sample they never access a name object.

Also, I am able to access other COM objects like ListObject just fine.

Body:
I figured out what the issue is. For anyone else running into this with .net Core, the problem is that .net core appears to not support dynamic types through COM automatically. This is discussed in the following github issue Github issue about dynamic not working. Where it talks about why this doesn't work.

Basically, for my specific case I needed to cast the type manually and then it worked. This also impacts use of IEnumerable COM types needing to be cast directly to IEnumerable before iterating through them.

Assuming you have the following using statement.

using Excel = Microsoft.Office.Interop.Excel;

I had to turn the following:

return range.Name.Name;

into

return ((Excel.Name)range.Name).Name;

As an aside, I also noticed that if you copy/paste the cast above into the debug watch window it does not display properly and instead shows an exception about an invalid cast.


问:
How to customize error pages served via the default backend of an nginx ingress controller?
I'm running an Nginx Ingress Controller installed via Helm on my Kubernetes cluster. I would like to change the HTML/CSS in the default backend service for some specific errors (e.g. 404). </p>

<p>This link provides  some general information about the default backend. However, there is no mention of how to actually customize the served HTML/CSS files. </p>

答:
The project provides the Go custom error application that can be built into a container image to replace default-backend. The errorHandler function does the magic.

In the end it's a web server that responds to any request with 404 content, except /healthz and /metrics. You could do it with an nginx instance and html error pages if you want.

You probably don't want to use the full custom error handling, this is slightly different where the ingress controller will look for certain HTTP status codes from a regular app backend, and pass them to the default backend for handling. This causes issues for most application unless they were designed to use this from the outset.

Body:
I'm running an Nginx Ingress Controller installed via Helm on my Kubernetes cluster. I would like to change the HTML/CSS in the default backend service for some specific errors (e.g. 404).

This link provides  some general information about the default backend. However, there is no mention of how to actually customize the served HTML/CSS files.


问:
How to use dynamic key for `parameter-store` in AWS CodeBuild spec file?
I have a buildspec.yml file in my CodeBuild that I want to read values out of EC2 Systems Manager Parameter Store.  CodeBuild supports doing this via the parameter-store attribute in your spec file.

Problem is, I can't figure out how to use enviornment Variables that are set BEFORE the buidlspec executes.

Here is an example:

```<code>version: 0.2
env:
  variables:
    RUNTIME: "nodejs8.10"
  #parameter-store vars are in the format /[stage]/[repo]/[branch]/[eyecatcher]/key
  parameter-store: #see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-syntax
    LAMBDA_EXECUTION_ROLE_ARN: "/${STAGE}/deep-link/${BRANCH}/GetUri/lambdaExecutionRoleArn"
    ENV_SAMPLE_KEY: "/${STAGE}/deep-link/${BRANCH}/GetUri/key1"

phases:
  install:
    commands:
      ...
</code>```

As you can see I'm doing the AWS best practice for name-spacing the EC2 Systems Manager Parameter Store keys.  I want to re-use this build spec for all my stages, so hard coding is not an option.  The vars I use in the Value string are populated as EnvironmentVariables in my CodeBuild project - so they are available before the spec runs.

How do I dynamically populate the Value of the parameter-store Keys with something that is not hard coded?

答:
This variable expansion is now supported in CodeBuild for parameter-store use case. You can define any environment variable in your buildspec and have that referenced in the path to fetch the parameter store. For example, if you have an environment variable called $stage you could use it like this:

version: 0.2
env:
  variables:
    stage: PRE_PROD
  parameter-store:
    encryptedVar: CodeBuild-$stage
phases:
  build:
    commands:
      - echo $encryptedVar
```

Body:
I have a buildspec.yml file in my CodeBuild that I want to read values out of EC2 Systems Manager Parameter Store.  CodeBuild supports doing this via the parameter-store attribute in your spec file.

Problem is, I can't figure out how to use enviornment Variables that are set BEFORE the buidlspec executes.

Here is an example:

version: 0.2
env:
  variables:
    RUNTIME: "nodejs8.10"
  #parameter-store vars are in the format /[stage]/[repo]/[branch]/[eyecatcher]/key
  parameter-store: #see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-syntax
    LAMBDA_EXECUTION_ROLE_ARN: "/${STAGE}/deep-link/${BRANCH}/GetUri/lambdaExecutionRoleArn"
    ENV_SAMPLE_KEY: "/${STAGE}/deep-link/${BRANCH}/GetUri/key1"

phases:
  install:
    commands:
      ...

As you can see I'm doing the AWS best practice for name-spacing the EC2 Systems Manager Parameter Store keys.  I want to re-use this build spec for all my stages, so hard coding is not an option.  The vars I use in the Value string are populated as EnvironmentVariables in my CodeBuild project - so they are available before the spec runs.

How do I dynamically populate the Value of the parameter-store Keys with something that is not hard coded?


问:
Query to get number of rows based on condition
In my application,I need to get the total number of rows count that has particular value in "status"column.This is the code I tried,

```<code>String unreadquery="(SELECT COUNT(*)FROM TABLE_MESSAGES WHERE KEY_STATUS="0")";
Cursor cursor = db.rawQuery(unreadquery, null);

int a=cursor.getCount();
</code>```

But it was showing error in query statement.How can I get the number of rows count that has 0 value in particular column?

Thanks!

This is code to create table:

```<code>public static final String TABLE_MESSAGES = "Messages";

String CREATE_MESSAGES_TABLE = "CREATE TABLE " + TABLE_MESSAGES + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FROM + " TEXT," + KEY_TO + " TEXT,"
            + KEY_BODY + " TEXT," + KEY_DATE + " TEXT," + KEY_STATUS + " TEXT" + ")";
            db.execSQL(CREATE_MESSAGES_TABLE);
</code>```

答:
Do exactly what you did, just get rid of "COUNT" in the query and just in case create beforehand the argument for rawQuery() like this:

```<code>String [] keyStatusValue = {"0"};
String unreadquery="(SELECT * FROM TABLE_MESSAGES WHERE KEY_STATUS =?");
// Notice I didn't add COUNT
// and created a String array no matter if keystatus was set as Integer

Cursor cursor = db.rawQuery(unreadquery, keyStatusValue);

int a=cursor.getCount();
</code>```

That's my advice as it worked fine this way for me.

Body:
In my application,I need to get the total number of rows count that has particular value in "status"column.This is the code I tried,

String unreadquery="(SELECT COUNT(*)FROM TABLE_MESSAGES WHERE KEY_STATUS="0")";
Cursor cursor = db.rawQuery(unreadquery, null);

int a=cursor.getCount();

But it was showing error in query statement.How can I get the number of rows count that has 0 value in particular column?

Thanks!

This is code to create table:

public static final String TABLE_MESSAGES = "Messages";

String CREATE_MESSAGES_TABLE = "CREATE TABLE " + TABLE_MESSAGES + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FROM + " TEXT," + KEY_TO + " TEXT,"
            + KEY_BODY + " TEXT," + KEY_DATE + " TEXT," + KEY_STATUS + " TEXT" + ")";
            db.execSQL(CREATE_MESSAGES_TABLE);

Body:
Do exactly what you did, just get rid of "COUNT" in the query and just in case create beforehand the argument for rawQuery() like this:

String [] keyStatusValue = {"0"};
String unreadquery="(SELECT * FROM TABLE_MESSAGES WHERE KEY_STATUS =?");
// Notice I didn't add COUNT
// and created a String array no matter if keystatus was set as Integer

Cursor cursor = db.rawQuery(unreadquery, keyStatusValue);

int a=cursor.getCount();

That's my advice as it worked fine this way for me.


问:
Counting 2 Querysets Deep within Django Template
Is there a way to count within a Django template on a 2nd deep queryset connected via FK's/M2M's? For instance,

Model A is FK'd to Model B, and Model B is M2M'd to Model C

```<code>    {% for C in Cs %}
       {% for B in C %)
         {% if B.A.all.count >= 2 %} B Has multiple A's!
         {% else %} B only has 1 A! {% endif %}
       {% endfor %}
    {% endfor %}
</code>```

Basically, I want to count the number of A's within B, and if it's 2 or more, just display "Multiple," as actually listing them out is disrupting my template. But I can't seem to get it to work. At the same time, the below DOES work for me:

```<code>    {% for C in Cs %}
         {% if C.B.all.count >= 2 %} C has multiple B's!
         {% else %} C only has 1 B! {% endif %}
    {% endfor %}
</code>```

I just can't get it to go one queryset deeper. Any help? Do I have to do this within the views?

答:
You should just count it in the views.py and send it to your page in dict form.

```<code>count = B.A.all().count()
return render(request, 'page.html', {'count':count})
</code>```

But if you insist on using template, try: {% if B.A.count >= 2 %} no need for "all"

Body:
Is there a way to count within a Django template on a 2nd deep queryset connected via FK's/M2M's? For instance,

Model A is FK'd to Model B, and Model B is M2M'd to Model C

    {% for C in Cs %}
       {% for B in C %)
         {% if B.A.all.count >= 2 %} B Has multiple A's!
         {% else %} B only has 1 A! {% endif %}
       {% endfor %}
    {% endfor %}

Basically, I want to count the number of A's within B, and if it's 2 or more, just display "Multiple," as actually listing them out is disrupting my template. But I can't seem to get it to work. At the same time, the below DOES work for me:

    {% for C in Cs %}
         {% if C.B.all.count >= 2 %} C has multiple B's!
         {% else %} C only has 1 B! {% endif %}
    {% endfor %}

I just can't get it to go one queryset deeper. Any help? Do I have to do this within the views?

Body:
You should just count it in the views.py and send it to your page in dict form.

count = B.A.all().count()
return render(request, 'page.html', {'count':count})

But if you insist on using template, try: {% if B.A.count >= 2 %} no need for "all"


问:
AI Algorithm Design: Card game
Currently I'm working on implementing a spanish card game called Briscas, or Briscola,http://en.wikipedia.org/wiki/Briscola

In a nutshell, it's a card game where two teams of 2 players play against each other (they can't see each others hand, not even team members), only at the beginning cards are shuffled, then three cards are handed to each player. In a clockwise manner everyone throws one card to try to win that turn. Who ever wins that turn take the points. Then, still in a clockwise manner, the player who won the last round, takes a card from the top of deck, and the player next to his/her left, and so on. Then you will keep playing rounds until the deck is empty. Who ever team has more points wins.

Details:

Deck Size: 40

Players: 4 (2 teams of 2)

Cards have specific value. (from 0 to 11)

The Question

  I know that straight MiniMax would be to expensive. What algorithms are typically used
for these kind of card games?

Also any literature that you can point to will also be beneficial.

Thanks

答:
This depends on how ambitious you want to get, but as a start you need a fast engine for simulating play.

Then you need a fast, and thus probably simple, model player.

This model player will not have time to calculate forward. It can only react on a pre-defined state. So your first step is to construct a good enough game state. The game state should include your hand and some statistics of the history of which cards have been discarded and maybe how players have played their hands.

Next you construct a model player that acts on the state. Either

A)
write one by hand, that plays according to some heuristics that you define. But remember - no heavy calculation yet!

B)
write a general player, but leave out constants and cut-off values. Use your simulation engine and genetic algorithms with tournament selection to evolve good parameters for said values. For bonus points, evolve your players in teams of two, so that they complement each other nicely.

C)
use even more AI and let a genetic programming system (there are a few mature ones. Find one that can do tournaments. You can even implement one yourself, but let's not get carried away :) write the entire player for you, using your state as input.

The next step:

Either you already have a great player and can consider yourself done, or you want to make it better. If you want to make it better your in luck!

Use Monte Carlo simulation to play out a large amount of hands, with each of your choices in a certain situation (there are always three choices if I understand correctly). Let your model player make the decisions each time you have a choice, and let your Monte Carlo simulation shuffle the deck randomly between each time that you play out a simulation.

Now you should have a great card player!

Title: AI Algorithm Design: Card game


问:
Rectangle won't stop moving
I'm using pygame.key.get_pressed() in my code in order to make a rectangle move up and down but when I let go of the key the rectangle continues moving. I'm wondering how to make the rectangle stop moving when the key is released.

```<code>    import pygame, random, sys
    from pygame.locals import *
    fpsClock=pygame.time.Clock()
    pygame.init()

    WINDOWWIDTH = 600
    WINDOWHEIGHT = 600
    TEXTCOLOR = (255, 255, 255)
    BACKGROUNDCOLOR = (0, 0, 255)
    FPS = 40
    BLACK = (0,0,0)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    rectY1 = 300
    rectY2 = 300
    Y1change = 0
    Y2change = 0

    def moveup():
        rectY1 -= 10
    pygame.display.set_caption('Pong')
    def drawshapes():
        pygame.init()
        DISPLAY=pygame.display.set_mode((600,600),0,32)
        DISPLAY.fill(BLACK)
        pygame.draw.rect(DISPLAY,RED,(18,rectY1,10,120))
        pygame.draw.rect(DISPLAY,RED,(580,rectY2,10,120))
        pygame.draw.ellipse(DISPLAY,BLUE,(300,300,30,30))
    drawshapes()

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        keys = pygame.key.get_pressed()
        if keys[K_UP]:
            Y1change -= 10
        if keys[K_DOWN]:
            Y1change += 10

        rectY1 += Y1change
        rectY2 += Y2change
        drawshapes()
        pygame.display.update()

        fpsClock.tick(FPS)
        pygame.display.update()
</code>```

答:
You have to reset it before every test

```<code>Y1change = 0

if keys[K_UP]:
    Y1change -= 10

if keys[K_DOWN]:
    Y1change += 10
</code>```

```<code>import random
import sys
import pygame

# --- constants (UPPERCASE_NAMES) ---

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 255)
FPS = 40
BLACK = (0,0,0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# --- classes (CamelCaseNames)---

# empty

# --- functions (lower_case_names)---

def move_up():
    global rectY1

    rectY1 -= 10

def draw_shapes():
    pygame.draw.rect(DISPLAY, RED, (18, rectY1, 10, 120)) # spaces
    pygame.draw.rect(DISPLAY, RED, (580, rectY2, 10, 120)) # spaces
    pygame.draw.ellipse(DISPLAY, BLUE, (300, 300, 30, 30)) # spaces

# --- main ---

rectY1 = 300
rectY2 = 300
Y1change = 0
Y2change = 0

# - init -

pygame.init()
DISPLAY = pygame.display.set_mode((600, 600), 0, 32) # spaces
pygame.display.set_caption('Pong')

#TODO: use pygame.Rect() to keep size and position of paddles and ball

# - mainloop -

fpsClock = pygame.time.Clock()

while True:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # - changes -

    keys = pygame.key.get_pressed()

    Y1change = 0

    if keys[pygame.K_UP]:
        Y1change -= 10

    if keys[pygame.K_DOWN]:
        Y1change += 10

    # - updates -

    rectY1 += Y1change
    rectY2 += Y2change

    # - draws -

    DISPLAY.fill(BLACK)
    draw_shapes()
    pygame.display.update() # only once in loop

    # - FPS -

    fpsClock.tick(FPS)
</code>```

Title: Rectangle won't stop moving

Body:
I'm using pygame.key.get_pressed() in my code in order to make a rectangle move up and down but when I let go of the key the rectangle continues moving. I'm wondering how to make the rectangle stop moving when the key is released.

    import pygame, random, sys
    from pygame.locals import *
    fpsClock=pygame.time.Clock()
    pygame.init()

    WINDOWWIDTH = 600
    WINDOWHEIGHT = 600
    TEXTCOLOR = (255, 255, 255)
    BACKGROUNDCOLOR = (0, 0, 255)
    FPS = 40
    BLACK = (0,0,0)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)
    rectY1 = 300
    rectY2 = 300
    Y1change = 0
    Y2change = 0

    def moveup():
        rectY1 -= 10
    pygame.display.set_caption('Pong')
    def drawshapes():
        pygame.init()
        DISPLAY=pygame.display.set_mode((600,600),0,32)
        DISPLAY.fill(BLACK)
        pygame.draw.rect(DISPLAY,RED,(18,rectY1,10,120))
        pygame.draw.rect(DISPLAY,RED,(580,rectY2,10,120))
        pygame.draw.ellipse(DISPLAY,BLUE,(300,300,30,30))
    drawshapes()

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        keys = pygame.key.get_pressed()
        if keys[K_UP]:
            Y1change -= 10
        if keys[K_DOWN]:
            Y1change += 10

        rectY1 += Y1change
        rectY2 += Y2change
        drawshapes()
        pygame.display.update()

        fpsClock.tick(FPS)
        pygame.display.update()

Body:
You have to reset it before every test

Y1change = 0

if keys[K_UP]:
    Y1change -= 10

if keys[K_DOWN]:
    Y1change += 10

import random
import sys
import pygame

# --- constants (UPPERCASE_NAMES) ---

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 255)
FPS = 40
BLACK = (0,0,0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# --- classes (CamelCaseNames)---

# empty

# --- functions (lower_case_names)---

def move_up():
    global rectY1

    rectY1 -= 10

def draw_shapes():
    pygame.draw.rect(DISPLAY, RED, (18, rectY1, 10, 120)) # spaces
    pygame.draw.rect(DISPLAY, RED, (580, rectY2, 10, 120)) # spaces
    pygame.draw.ellipse(DISPLAY, BLUE, (300, 300, 30, 30)) # spaces

# --- main ---

rectY1 = 300
rectY2 = 300
Y1change = 0
Y2change = 0

# - init -

pygame.init()
DISPLAY = pygame.display.set_mode((600, 600), 0, 32) # spaces
pygame.display.set_caption('Pong')

#TODO: use pygame.Rect() to keep size and position of paddles and ball

# - mainloop -

fpsClock = pygame.time.Clock()

while True:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # - changes -

    keys = pygame.key.get_pressed()

    Y1change = 0

    if keys[pygame.K_UP]:
        Y1change -= 10

    if keys[pygame.K_DOWN]:
        Y1change += 10

    # - updates -

    rectY1 += Y1change
    rectY2 += Y2change

    # - draws -

    DISPLAY.fill(BLACK)
    draw_shapes()
    pygame.display.update() # only once in loop

    # - FPS -

    fpsClock.tick(FPS)


问:
How do I add placeholder text to TinyMCE?
For standard textareas, I use placeholder="" . How can I extend tinymce so that it also works in this way.

Similar to this for CKEditor: http://alfonsoml.blogspot.com.es/2012/04/placeholder-text-in-ckeditor.html

答:
There is a new feature for inline placeholders in TinyMCE 5.2.
An example of what could be done now to give it a custom placeholder:

```<code><script type="text/javascript">
tinymce.init({
    selector: "textarea#classic"
});
tinymce.init({
    selector: "div#inline",
    inline: true,
    placeholder: "Type here..."
});
</script>
</code>```

source:
https://github.com/tinymce/tinymce/issues/4813

Body:
There is a new feature for inline placeholders in TinyMCE 5.2.
An example of what could be done now to give it a custom placeholder:

<script type="text/javascript">
tinymce.init({
    selector: "textarea#classic"
});
tinymce.init({
    selector: "div#inline",
    inline: true,
    placeholder: "Type here..."
});
</script>

source:
https://github.com/tinymce/tinymce/issues/4813


问:
What's the difference between a mock & stub?
I've read various articles about mocking vs stubbing in testing, including Martin Fowler's Mocks Aren't Stubs, but still don't understand the difference.</p>

答:
Plus useful answers, One of the most powerful point of using Mocks than Subs

If the collaborator [which the main code depend on it] is not under our control (e.g. from a third-party library),

In this case, stub is more difficult to write rather than mock.


问:
Standard Deviation of One Variable Weighted By Second Variable
I would like to calculate standard deviation of a variable that weighs each observation by a second variable.

```<code>values <- c(100, 200, 300, 400, 200)
sizes <- c(12, 54, 1, 218, 63)
</code>```

How do I find the standard deviation of values with weighting applied based on sizes?

答:
We can use wtd.var from Hmisc to get the variance and then take the square root of it

```<code>sqrt(Hmisc::wtd.var(values, sizes))
#[1] 102.696
</code>```

As @AaronMontgomery mentioned, the normwt = TRUE may be needed to make the weights sum to the length of 'values' after deletion of NAs (By default, it is FALSE)

```<code>sqrt(Hmisc::wtd.var(values, sizes, normwt = TRUE))
#[1] 138.3356v
</code>```

Body:
I would like to calculate standard deviation of a variable that weighs each observation by a second variable.

values <- c(100, 200, 300, 400, 200)
sizes <- c(12, 54, 1, 218, 63)

How do I find the standard deviation of values with weighting applied based on sizes?

Body:
We can use wtd.var from Hmisc to get the variance and then take the square root of it

sqrt(Hmisc::wtd.var(values, sizes))
#[1] 102.696

As @AaronMontgomery mentioned, the normwt = TRUE may be needed to make the weights sum to the length of 'values' after deletion of NAs (By default, it is FALSE)

sqrt(Hmisc::wtd.var(values, sizes, normwt = TRUE))
#[1] 138.3356v


问:
How to send a command to SQL Server complete a batch started from a select query sent by a VB.Net program?
I'm trying to execute a select query (with joins) and when there are a small number of records to return, I can see in SQL Server Profiler the following EventClass:
SQL:BatchStarting and after that SQL:BatchCompleted.
I'm using the ExecuteReader from ADO.NET.
So far, so good, I can use the information and make some inserts in the same table I retrieved the information in the select query.

But when the select query returns more rows (I can't specify how much, but I believe it is irrelevant) the SQL Server Profiler doesn't show the SQL:BatchCompleted event and the insert I need to do can't run because the batch is still running.

How do I send a command to execute and return all the rows and then complete the batch.

I'm using VB.NET but I believe C# answers can help me too.

答:
The batch request is not complete until the client fetches the rows.

Al you need to call SqlDataReader.Read() for each row in the result and then SqlDataReader.Close(), or SqlDataReader.Dispose() to complete the batch request.