问:
POSIX FIFO freezes when opened in blocking mode
By default a POSIX FIFO is opened in blocking mode.  My problem is that when I open it in blocking mode it just freezes (blocks) and nothing else happens.

Originally I opened both sides with the RDWR flag and I had no problems because RDWR makes it nonblocking because "Under Linux, opening a FIFO for read and write will succeed both in blocking and nonblocking mode" (https://linux.die.net/man/7/fifo).  But in nonblocking mode I sometimes get dropped records, so I need to open it in blocking mode.

Here's how I call mkfifo:

```<code>int64_t fifo_setup(char * fifo_name)
{
    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

   return 0; }
</code>```

My original call to open:

```<code>int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_RDWR);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDWR);}

    perror("open");

    return (c);
}
</code>```

Then I changed it to:

```<code>int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_WRONLY);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDONLY);}

    perror("open");

    return (c);
}
</code>```

My program reaches the open call for the writer threads (this is a NASM call to C):

```<code>Open_FIFO_Write:
lea rdi,[fifo_name]
mov rsi,1
call fifo_open wrt ..plt
mov [fifo_write_fd],rax
</code>```

But then the Putty terminal freezes (blocks) and nothing else happens.  I never get to the block that opens the reading side.  Specifically it blocks just before it reaches perror("open") in the fifo_open code above:

According to the Linux man page at https://www.man7.org/linux/man-pages/man7/fifo.7.html, "Normally, opening the FIFO blocks until the other end is opened also."  That's great but I can't get to the code that opens the writer because the reader blocks all further progress.  It's like a Mexican standoff.

Of course there must be a way but my research hasn't found it yet.

Thanks for any help on this.

答:
Three options:

FIFOs themselves don't drop messages in nonblocking mode. If your code is dropping messages, fix your code to stop doing that, and then just use nonblocking mode.

Open the FIFO in nonblocking mode, then once you get both ends open, use fcntl to change it to blocking mode.

Use a separate thread or process to open each half of the FIFO.

Body:
By default a POSIX FIFO is opened in blocking mode.  My problem is that when I open it in blocking mode it just freezes (blocks) and nothing else happens.

Originally I opened both sides with the RDWR flag and I had no problems because RDWR makes it nonblocking because "Under Linux, opening a FIFO for read and write will succeed both in blocking and nonblocking mode" (https://linux.die.net/man/7/fifo).  But in nonblocking mode I sometimes get dropped records, so I need to open it in blocking mode.

Here's how I call mkfifo:

int64_t fifo_setup(char * fifo_name)
{
    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

   return 0; }

My original call to open:

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_RDWR);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDWR);}

    perror("open");

    return (c);
}

Then I changed it to:

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_WRONLY);}
    if (read_write == 2) {
        c = open(fifo_name, O_RDONLY);}

    perror("open");

    return (c);
}

My program reaches the open call for the writer threads (this is a NASM call to C):

Open_FIFO_Write:
lea rdi,[fifo_name]
mov rsi,1
call fifo_open wrt ..plt
mov [fifo_write_fd],rax

But then the Putty terminal freezes (blocks) and nothing else happens.  I never get to the block that opens the reading side.  Specifically it blocks just before it reaches perror("open") in the fifo_open code above:

According to the Linux man page at https://www.man7.org/linux/man-pages/man7/fifo.7.html, "Normally, opening the FIFO blocks until the other end is opened also."  That's great but I can't get to the code that opens the writer because the reader blocks all further progress.  It's like a Mexican standoff.

Of course there must be a way but my research hasn't found it yet.

Thanks for any help on this.


来源: stackexchange

问:
Go map of functions
I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?

I have tried this, but this doesn't work.

```
func a(param string) {

}

m := map[string] func {
    'a_func': a,
}

for key, value := range m {
   if key == 'a_func' {
    value(param)
   }
}
```

答:
I used a map[string]func (a type, b *type) I passed a string to search the map and a pointer to modify the slice.

Hope that helps!

```<code>var Exceptions map[string]func(step string, item *structs.Item)

func SetExceptions() {
    Exceptions = map[string]func(a string, i *structs.Item){
        "step1": step1,
    }
}

func RunExceptions(state string, item *structs.Item) {
    method, methBool := Exceptions[state]
    if methBool {
        method(state, item)
    }
}

func step1(step string, item *structs.Item) {
    item.Title = "Modified"
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Go map of functions

Body:
I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?

I have tried this, but this doesn't work.

func a(param string) {

}

m := map[string] func {
    'a_func': a,
}

for key, value := range m {
   if key == 'a_func' {
    value(param)
   }
}

Body:
I used a map[string]func (a type, b *type) I passed a string to search the map and a pointer to modify the slice.

Hope that helps!

var Exceptions map[string]func(step string, item *structs.Item)

func SetExceptions() {
    Exceptions = map[string]func(a string, i *structs.Item){
        "step1": step1,
    }
}

func RunExceptions(state string, item *structs.Item) {
    method, methBool := Exceptions[state]
    if methBool {
        method(state, item)
    }
}

func step1(step string, item *structs.Item) {
    item.Title = "Modified"
}

ContentLicense: CC BY-SA 4.0


问:
Setting up SSL on a Raspbian Apache Server
I have a domain and SSL bought from godaddy. I successfully pointed the domain to my Raspberry Pi's ip address. However, the SSL is having some issues. When I download the SSL from godaddy I get two .crt files and one .pem file. Godaddy's instructions only mention a .key file and two .crt's.

in my apache config file I put in a VirtualHost tag following the format from godaddy with all appropriate info replaced:

```<code><VirtualHost xxx.xxx.x.x:443>
DocumentRoot /var/www/coolexample
ServerName coolexample.com www.coolexample.com
    SSLEngine on
    SSLCertificateFile /path/to/coolexample.crt
    SSLCertificateKeyFile /path/to/privatekey.key
    SSLCertificateChainFile /path/to/intermediate.crt
</VirtualHost>
</code>```

However, as you can see this requires a private key. When launching my apache server the error log tells me the private key cannot be found. My question is, within the VirtualHost tag how can I properly set up my SSL with the files given to me by godaddy?

答:
Here is an implementation of TLS 1.2 that can go in your vhost:

```<code>    SSLEngine On
    SSLCertificateFile  /etc/ssl/localcerts/xxxxxxx.crt
    SSLCertificateKeyFile /etc/ssl/localcerts/mysite.key
    SSLCertificateChainFile /etc/ssl/localcerts/bundle.crt
    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS"

</code>```

Further, you must ensure that mod_ssl is enabled.  In the corresponding configuration file, you can do something like this (which is mostly stock)

```<code><IfModule mod_ssl.c>

    # Pseudo Random Number Generator (PRNG):
    # Configure one or more sources to seed the PRNG of the SSL library.
    # The seed data should be of good random quality.
    # WARNING! On some platforms /dev/random blocks if not enough entropy
    # is available. This means you then cannot use the /dev/random device
    # because it would lead to very long connection times (as long as
    # it requires to make more entropy available). But usually those
    # platforms additionally provide a /dev/urandom device which doesn't
    # block. So, if available, use this one instead. Read the mod_ssl User
    # Manual for more details.
    #
    SSLRandomSeed startup builtin
    SSLRandomSeed startup file:/dev/urandom 512
    SSLRandomSeed connect builtin
    SSLRandomSeed connect file:/dev/urandom 512

    ##
    ##  SSL Global Context
    ##
    ##  All SSL configuration in this context applies both to
    ##  the main server and all SSL-enabled virtual hosts.
    ##

    #
    #   Some MIME-types for downloading Certificates and CRLs
    #
    AddType application/x-x509-ca-cert .crt
    AddType application/x-pkcs7-crl .crl

    #   Pass Phrase Dialog:
    #   Configure the pass phrase gathering process.
    #   The filtering dialog program (`builtin' is a internal
    #   terminal dialog) has to provide the pass phrase on stdout.
    SSLPassPhraseDialog  exec:/usr/share/apache2/ask-for-passphrase

    #   Inter-Process Session Cache:
    #   Configure the SSL Session Cache: First the mechanism
    #   to use and second the expiring timeout (in seconds).
    #   (The mechanism dbm has known memory leaks and should not be used).
    #SSLSessionCache         dbm:${APACHE_RUN_DIR}/ssl_scache
    SSLSessionCache     shmcb:${APACHE_RUN_DIR}/ssl_scache(512000)
    SSLSessionCacheTimeout  300

    #   Semaphore:
    #   Configure the path to the mutual exclusion semaphore the
    #   SSL engine uses internally for inter-process synchronization.
    #   (Disabled by default, the global Mutex directive consolidates by default
    #   this)
    #Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache

    #   SSL Cipher Suite:
    #   List the ciphers that the client is permitted to negotiate. See the
    #   ciphers(1) man page from the openssl package for list of all available
    #   options.
    #   Enable only secure ciphers:
    SSLCipherSuite HIGH:!aNULL:!MD5

    # SSL server cipher order preference:
    # Use server priorities for cipher algorithm choice.
    # Clients may prefer lower grade encryption.  You should enable this
    # option if you want to enforce stronger encryption, and can afford
    # the CPU cost, and did not override SSLCipherSuite in a way that puts
    # insecure ciphers first.
    # Default: Off
    #SSLHonorCipherOrder on

    #   The protocols to enable.
    #   Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2
    #   SSL v2  is no longer supported
    SSLProtocol all -SSLv2 -SSLv3

    #   Allow insecure renegotiation with clients which do not yet support the
    #   secure renegotiation protocol. Default: Off
    #SSLInsecureRenegotiation on

    #   Whether to forbid non-SNI clients to access name based virtual hosts.
    #   Default: Off
    #SSLStrictSNIVHostCheck On
</IfModule>
</code>```

These changes should get you going with TLS 1.2.

It is incredibly important that you research your configuration files and vhosts if your server is for production "business use".

Body:
I have a domain and SSL bought from godaddy. I successfully pointed the domain to my Raspberry Pi's ip address. However, the SSL is having some issues. When I download the SSL from godaddy I get two .crt files and one .pem file. Godaddy's instructions only mention a .key file and two .crt's.

in my apache config file I put in a VirtualHost tag following the format from godaddy with all appropriate info replaced:

<VirtualHost xxx.xxx.x.x:443>
DocumentRoot /var/www/coolexample
ServerName coolexample.com www.coolexample.com
    SSLEngine on
    SSLCertificateFile /path/to/coolexample.crt
    SSLCertificateKeyFile /path/to/privatekey.key
    SSLCertificateChainFile /path/to/intermediate.crt
</VirtualHost>

However, as you can see this requires a private key. When launching my apache server the error log tells me the private key cannot be found. My question is, within the VirtualHost tag how can I properly set up my SSL with the files given to me by godaddy?

Body:
Here is an implementation of TLS 1.2 that can go in your vhost:

    SSLEngine On
    SSLCertificateFile  /etc/ssl/localcerts/xxxxxxx.crt
    SSLCertificateKeyFile /etc/ssl/localcerts/mysite.key
    SSLCertificateChainFile /etc/ssl/localcerts/bundle.crt
    SSLProtocol all -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    SSLCipherSuite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS"

Further, you must ensure that mod_ssl is enabled.  In the corresponding configuration file, you can do something like this (which is mostly stock)

<IfModule mod_ssl.c>

    # Pseudo Random Number Generator (PRNG):
    # Configure one or more sources to seed the PRNG of the SSL library.
    # The seed data should be of good random quality.
    # WARNING! On some platforms /dev/random blocks if not enough entropy
    # is available. This means you then cannot use the /dev/random device
    # because it would lead to very long connection times (as long as
    # it requires to make more entropy available). But usually those
    # platforms additionally provide a /dev/urandom device which doesn't
    # block. So, if available, use this one instead. Read the mod_ssl User
    # Manual for more details.
    #
    SSLRandomSeed startup builtin
    SSLRandomSeed startup file:/dev/urandom 512
    SSLRandomSeed connect builtin
    SSLRandomSeed connect file:/dev/urandom 512

    ##
    ##  SSL Global Context
    ##
    ##  All SSL configuration in this context applies both to
    ##  the main server and all SSL-enabled virtual hosts.
    ##

    #
    #   Some MIME-types for downloading Certificates and CRLs
    #
    AddType application/x-x509-ca-cert .crt
    AddType application/x-pkcs7-crl .crl

    #   Pass Phrase Dialog:
    #   Configure the pass phrase gathering process.
    #   The filtering dialog program (`builtin' is a internal
    #   terminal dialog) has to provide the pass phrase on stdout.
    SSLPassPhraseDialog  exec:/usr/share/apache2/ask-for-passphrase

    #   Inter-Process Session Cache:
    #   Configure the SSL Session Cache: First the mechanism
    #   to use and second the expiring timeout (in seconds).
    #   (The mechanism dbm has known memory leaks and should not be used).
    #SSLSessionCache         dbm:${APACHE_RUN_DIR}/ssl_scache
    SSLSessionCache     shmcb:${APACHE_RUN_DIR}/ssl_scache(512000)
    SSLSessionCacheTimeout  300

    #   Semaphore:
    #   Configure the path to the mutual exclusion semaphore the
    #   SSL engine uses internally for inter-process synchronization.
    #   (Disabled by default, the global Mutex directive consolidates by default
    #   this)
    #Mutex file:${APACHE_LOCK_DIR}/ssl_mutex ssl-cache

    #   SSL Cipher Suite:
    #   List the ciphers that the client is permitted to negotiate. See the
    #   ciphers(1) man page from the openssl package for list of all available
    #   options.
    #   Enable only secure ciphers:
    SSLCipherSuite HIGH:!aNULL:!MD5

    # SSL server cipher order preference:
    # Use server priorities for cipher algorithm choice.
    # Clients may prefer lower grade encryption.  You should enable this
    # option if you want to enforce stronger encryption, and can afford
    # the CPU cost, and did not override SSLCipherSuite in a way that puts
    # insecure ciphers first.
    # Default: Off
    #SSLHonorCipherOrder on

    #   The protocols to enable.
    #   Available values: all, SSLv3, TLSv1, TLSv1.1, TLSv1.2
    #   SSL v2  is no longer supported
    SSLProtocol all -SSLv2 -SSLv3

    #   Allow insecure renegotiation with clients which do not yet support the
    #   secure renegotiation protocol. Default: Off
    #SSLInsecureRenegotiation on

    #   Whether to forbid non-SNI clients to access name based virtual hosts.
    #   Default: Off
    #SSLStrictSNIVHostCheck On
</IfModule>

These changes should get you going with TLS 1.2.

It is incredibly important that you research your configuration files and vhosts if your server is for production "business use".


问:
Why don't variables work with "instance" in Django signals?
This works:

```<code>@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):

    instance.field_name = 'foo'

    return None
</code>```

...this will save 'foo' as the field_name.  Simple enough.

But why doesn't this work:

```<code>@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):

    foo = 'field_name'
    instance.foo = 'bar'

    return None
</code>```

In the second case, django ignores the variable "foo" or treats it as a literal.  Using string method on the variable doesn't help.  Not finding anything in the docs.

答:
In the second case, django ignores the variable "foo" or treats it as a literal.

It does not ignore that, you simply set the attribute with the name .foo, the fact that a variable with the name foo exists, and somehow has a string, that does not matter. This is how Python works.

What you can do is make use of the setattr builtin function [Pyton-doc]:

```<code>@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):
    foo = 'field_name'
    <b>setattr(</b>instance, foo, 'bar'<b>)</b></code>```

So setattr(x, 'y', z) is equivalent to x.y = z.

Body:
This works:

@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):

    instance.field_name = 'foo'

    return None

...this will save 'foo' as the field_name.  Simple enough.

But why doesn't this work:

@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):

    foo = 'field_name'
    instance.foo = 'bar'

    return None

In the second case, django ignores the variable "foo" or treats it as a literal.  Using string method on the variable doesn't help.  Not finding anything in the docs.

Body:
In the second case, django ignores the variable "foo" or treats it as a literal.

It does not ignore that, you simply set the attribute with the name .foo, the fact that a variable with the name foo exists, and somehow has a string, that does not matter. This is how Python works.

What you can do is make use of the setattr builtin function [Pyton-doc]:

@receiver(pre_save, sender=MyModel)
def some_signal_function(sender, instance, *args, **kwargs):
    foo = 'field_name'
    setattr(instance, foo, 'bar')

So setattr(x, 'y', z) is equivalent to x.y = z.


问:
Can't uninstall and reinstall Truffle?
Pls help me with command unstall/ install Truffle.

```<code>ubuntu@ubuntu-vbox:~$ sudo npm uninstall -g truffle
[sudo] password for ubuntu:
removed 82 packages in 1.793s

ubuntu@ubuntu-vbox:~$ truffle v
Truffle v4.0.4 (core: 4.0.4)
Solidity v0.4.18 (solc-js)

ubuntu@ubuntu-vbox:~$ sudo npm install -g truffle@4.1.15
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
/home/ubuntu/.npm-global/bin/truffle -> /home/ubuntu/.npm-global/lib/node_modules/truffle/build/cli.bundled.js
+ truffle@4.1.15
added 82 packages in 9.783s

ubuntu@ubuntu-vbox:~$ truffle v
Truffle v4.0.4 (core: 4.0.4)
Solidity v0.4.18 (solc-js)
</code>```

It's still version Truffle v4.0.4 after reinstall version 4.1.15

答:
https://ethereum.stackexchange.com/a/62956

I have used this in the past.

You will need to:

```<code>which truffle
</code>```

will return:

/usr/local/bin/truffle

```<code>rm -f /usr/local/bin/truffle
</code>```

Then proceed with the re-installation procedure.
I hope this helps.

Title: Can't uninstall and reinstall Truffle?

Body:
Pls help me with command unstall/ install Truffle.

ubuntu@ubuntu-vbox:~$ sudo npm uninstall -g truffle
[sudo] password for ubuntu:
removed 82 packages in 1.793s

ubuntu@ubuntu-vbox:~$ truffle v
Truffle v4.0.4 (core: 4.0.4)
Solidity v0.4.18 (solc-js)

ubuntu@ubuntu-vbox:~$ sudo npm install -g truffle@4.1.15
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
/home/ubuntu/.npm-global/bin/truffle -> /home/ubuntu/.npm-global/lib/node_modules/truffle/build/cli.bundled.js
+ truffle@4.1.15
added 82 packages in 9.783s

ubuntu@ubuntu-vbox:~$ truffle v
Truffle v4.0.4 (core: 4.0.4)
Solidity v0.4.18 (solc-js)

It's still version Truffle v4.0.4 after reinstall version 4.1.15

Body:
https://ethereum.stackexchange.com/a/62956

I have used this in the past.

You will need to:

which truffle

will return:

/usr/local/bin/truffle

rm -f /usr/local/bin/truffle

Then proceed with the re-installation procedure.
I hope this helps.


问:
how do make this show/hide more concise?
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

```<code>jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});
</code>```

Each show/hide uses its own ID, so I simply group ids like so:

```<code>jQuery('#show-hide1, #show-hide2').hide();
</code>```

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

```<code>jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});
</code>```

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

答:
start by giving each of the areas the same class.

```<code>jQuery('.hider').click(function() {
    jQuery(this).toggle(400);
    return false;
});
</code>```

This will cause only the "hider" you clicked on to toggle. Each one will work independently.

Body:
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});

Each show/hide uses its own ID, so I simply group ids like so:

jQuery('#show-hide1, #show-hide2').hide();

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

Body:
start by giving each of the areas the same class.

jQuery('.hider').click(function() {
    jQuery(this).toggle(400);
    return false;
});

This will cause only the "hider" you clicked on to toggle. Each one will work independently.


问:
Finding the difference between client time and server time
I have a server that stores events happening in different parts of the world. They all save UNIX timestamps of the time when the event will occur and end.

At the same time I have a script that queries the database and compares the server time minus the end time of the event.

If the result of the comparison is greater than, or equal to 0. Then it means that the event already occurred and should be removed from the database.

But my problem is that:

If an event is created in UK (GMT+1) and set to end at 7:00 PM, and the server being in Germany (GMT+2).  The event will be deleted an hour earlier, that is: 6:00 PM in the UK and 7:00 PM in Germany.

What I want is that:

If the created event ends at 7:00 PM in UK, it should be deleted at 8:00 PM in Germany.

I've look around for a solution but I'm not sure if this would be the correct solution?

答:
I hope I got the question right.

In the data base you store unix time stamps,

Then why don't you compare the unix time stamps from the data base with the current unix time stamp to decide which entry should be deleted.

In python you get the current time stamp with

time.time()

So something like that should work:

```<code>import time

now = time.time()
query = "select primarykey, timestamp from table"
for primary_key, timestamp in yourfuncttoexecutequeryandreturnrows(query):
    if timestamp < now:
        print("I could delete entry ", primary_key)
</code>```

Body:
I hope I got the question right.

In the data base you store unix time stamps,

Then why don't you compare the unix time stamps from the data base with the current unix time stamp to decide which entry should be deleted.

In python you get the current time stamp with

time.time()

So something like that should work:

import time

now = time.time()
query = "select primarykey, timestamp from table"
for primary_key, timestamp in yourfuncttoexecutequeryandreturnrows(query):
    if timestamp < now:
        print("I could delete entry ", primary_key)


问:
How to model editing approved resources to create draft resources in a REST API
The use case is handling a Configuration which needs to be reviewed and approved by users before it can be used.  The problem is modelling the edit case for an already approved Configuration.

As further background, versioning and keeping track of a history of drafts is out of scope, users would collectively approve a single outstanding draft.  An approved Configuration could be updated again with another pending draft so both approved and pending Configurations can be available side by side.

This is subtly different from  this question (Architectural REST: How do I design a REST API for request+approval, 2 resources or 1?) as it doesn't cover updating an already approved resource.

One approach is to have a configuration resource with pending and approved sub-resources e.g.

```<code>/configurations/A/pending
/configurations/A/approved
</code>```

(First /configurations/A/pending can be created, /configurations/A/pending can be patched such that /configurations/A/approved exists and /configurations/A/pending is removed.  It seems legal for  patch operation to have side effects on other resources(https://www.rfc-editor.org/rfc/rfc5789#section-2))

The question is then how to handle the edit case for an approved Configuration, which should create a pending configuration.

If we were to edit A, a PUT operation could be applied to /configurations/A/approved, but this seems strange as the result would be to create /configurations/A/pending.  But a PUT operation should be idempotent and have no side effects.

We could have a PUT operation on /configurations/A/pending but that also seems strange as logically we want to perform an operation on an approved resource.

Rather than having a singular Configuration with subresources, we could model separate pending and approved resources like so:

```<code>/configurations/pending/A
/configurations/approved/A

or we could go a step further and decouple the two and have different ids
/configurations/pending/123
/configurations/approved/A
</code>```

But the same problem as listed above still remains.

Would like to hear other thoughts on how to model editing an approved resource.

答:
But a PUT operation should be idempotent and have no side effects.

According to RFC 7231 PUT may have side effects as well, i.e. if you design a commit-like system similar to Git where a commit creates a new commit entry in the branch-tree while also moving the HEAD to the most recent version.

As further background, versioning and keeping track of a history of drafts is out of scope, users would collectively approve a single outstanding draft. An approved Configuration could be updated again with another pending draft so both approved and pending Configurations can be available side by side.

If we would design this for the Web, we probably should have a page to list all configurations and drafts and have links for each entry to edit and remove such a configuration/draft. As only drafts can be accepted/rejected, depending whether the resource at hand is a draft or not may contain the possibility to accept/reject it.

As mentioned accepting a draft should lead to the removal of the draft and the creation/replacement of the actual configuration. There are actually a couple of ways you might achieve this, depending on how you design things. In general, a URI as a whole is, as its name suggest, a unique resource identifier. Segments within that URI do not necessarily state a parent-child relationship automatically. One might create a set of URIs though that map such an ancestor tree onto resources that a server treats as parents and children.

PATCH is basically an operation where a client should calculate a set of instructions the server should apply to transform the target resource from its current form to a desired form atomically. So, either all of the instructions succeed or none at all. Depending on the chosen representation type (Hint: negotiated media type) such an operation might be doable.

With  JSON Patch (application/json-patch+json) you need to target an ancestor resource that you address to move that resource to a different location. Such a payload may look like this:

PATCH /configurations HTTP/1.1
Host: www.acme.com
Content-Type: application/json-patch+json; charset="utf-8"
ETag: 33a64df551425fcc55e4d42a148795d9f25f89d4
...

[
  {
    "op": "move",
    "from": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67",
    "path": "/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67"
  }
]
```
<p>This basically tasks the server to move the specified draft resource and move it to the approved configuration resources. I've just taken your suggested names here. In a REST architecture they don't really matter. As this request should be created by the client, ideally the server is already providing the client with all the data it needs to create such a request. On the Web HTML supports such a feature through the help of Web forms that defines the admissible syntax and semantics of each of the elements and attributes. For JSON HAL-FORMS and Ion may be used to support you in this task.</p>
<p>In contrast to JSON Patch, JSON Merge-Patch, that defines a set of default rules to apply on a document, however, won't allow you to move a document unless you apply custom logic on the server.</p>
<p>Moving a resource through patching may interfere with caching though as the request here is not directed towards the actual draft resource but an, in terms of the cache, unrelated one. As caches should invalidate stored representations when an unsafe operation is performed on the target URI, not using the same URI that was used for retrieving that resource state representation therefore won't invalidate a stored representation for that draft resource upon accepting or rejecting and thus may lead to stale response data upon requesting the current state.</p>
<p>While <code>PUT</code> may have side effects, these are more or less limited to creating new resources as a consequence of the document replacement. You might "bend your design" in a way to send an empty PUT request to the current draft that leads to the server copying the current content to the accepted configurations. As PUT is an unsafe operation performed on the same URI the representation state was requested from, caches should invalidate any stored representations for that URI. However, depending on your server design this may lead to unwanted "empty" drafts being still available. This operation, however, still fulfills the idempotent requirements. Upon resending a request the effective outcome should be the same on each request, an "empty" resource.</p>
<p>As <code>POST</code> is the general-purpose tool of HTTP, by processing a request according to the resource's own semantics, you can use it anyway you like. If you, however, use a different URI so send that request to you may end up with the same caching issues PATCH struggles.</p>
<p>WebDAV specifies an idempotent, but not safe, <code>MOVE</code> operation, which can also be found in IANAs HTTP method registry. This method does what its name suggests. If moves the target resource to the destination location by performing a copy step, followed by a consistency maintenance step which ends with a deletion step of the target resource. These three steps will be performed atomically as well. A request here just looks like this, assuming the same URIs from above.</p>
<pre class="lang-http prettyprint-override"><code>MOVE /configurations/drafs/eaff31bd-5291-4287-a7dd-fbe5b1e47b67
Host: www.acme.com
Destination: /configurations/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67

...
</code>```

As this operation is unsafe any cached representation will be invalidated automatically.

An other possibility is to not expose the state of the configuration within the URI mapping but keep it within the resource itself. This would also only operate on the same URI for that configuration itself. Internally you'd have to store the current active configuration as well as any draft version within the same resource. The downside here though is that you basically send plenty more data within a single response, i.e. the stored current version and all of the admissible draft version. You may introduce certain filters though to only retrieve accepted, rejected or pending configurations. The representation format such a payload is returned for should possibly support a client to easily identify the current and draft versions here.

The question is then how to handle the edit case for an approved Configuration, which should create a pending configuration.

In case of JSON Patch you might try something like this:

PATCH /configurations HTTP/1.1
Host: www.acme.com
Content-Type: application/json-patch+json; charset="utf-8"
ETag: 33a64df551425fcc55e4d42a148795d9f25f89d4
...

[
  {
    "op": "copy",
    "from": "/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67",
    "path": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67"
  },
  {
    "op": "replace",
    "path": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67/field1",
    "value": "new value"
  },
  ...
]
```

that first creates a copy of the current approved configuration version and then starts editing it. The atomic requirement of PATCH ensures that either all or none of the changes are applied.

In regards to updates of approved configurations via PUT, ideally the server issues a form-like representation to the client that teaches it how the resource state can be updated. Such representation would contain the necessary fields pre-filled with the current state that quickly allows a user to change the state of the resource. As editing an approved resource should resemble in the creation of a draft-resource first, the server should know about that and already instruct the client to send a PUT request to the draft endpoint rather than the original approved endpoint. Upon processing the response on the serve side it just needs to figure out whether there is content available or an empty payload to decide whether a draft was edited or accepted/rejected.

Via POST you are allowed to do whatever you want, so I don't think you need explanations in that case ...

On utilizing WebDAV methods you might need to split the instructions into multiple ones unfortunately. COPY will as its name implies copy the target resource to some location defined in the Destination header. Afterwards you can simply edit that file. If comparing it to a typical Web interaction, the resource could be copied already once a user clicks the edit button. The response to clicking the edit button will be a form representation containing the pre-filled data of the copied resource that upon clicking the submit button just performs a regular resource update on the draft resource. This interaction model needs to be mapped to a more generic layer though. Though the concepts remain the same. First a client needs to declare its interest in editing an already approved configuration, which leads to the creation of the copy in the draft space and afterwards returning a form representation allowing an application to supports its user to update the data.

In the last case, where you kept everything in one resource, creating a new draft on "editing" an accepted configuration only requires to add that modified version to the set of drafts. A server should compare the current configuration with the one provided in the request and if they differ, the provided payload needs to be added to the drafts.

As you can see, you have a couple of possibilities you can choose from. While patching seems to be a good choice, it doesn't coop with caching well and is also dependent on the media type negotiated. PUT demands a bit of "bending the rules" though could potentially be used to get the job done by also to invalidating any stored cache representation. POST is an all-purpose, general operation that can be used for literally anything you want or need. Last but not least redesigning your configurations and drafts into one single resource can also work.

Body:
The use case is handling a Configuration which needs to be reviewed and approved by users before it can be used.  The problem is modelling the edit case for an already approved Configuration.

As further background, versioning and keeping track of a history of drafts is out of scope, users would collectively approve a single outstanding draft.  An approved Configuration could be updated again with another pending draft so both approved and pending Configurations can be available side by side.

This is subtly different from  this question (Architectural REST: How do I design a REST API for request+approval, 2 resources or 1?) as it doesn't cover updating an already approved resource.

One approach is to have a configuration resource with pending and approved sub-resources e.g.

/configurations/A/pending
/configurations/A/approved

(First /configurations/A/pending can be created, /configurations/A/pending can be patched such that /configurations/A/approved exists and /configurations/A/pending is removed.  It seems legal for  patch operation to have side effects on other resources(https://www.rfc-editor.org/rfc/rfc5789#section-2))

The question is then how to handle the edit case for an approved Configuration, which should create a pending configuration.

If we were to edit A, a PUT operation could be applied to /configurations/A/approved, but this seems strange as the result would be to create /configurations/A/pending.  But a PUT operation should be idempotent and have no side effects.

We could have a PUT operation on /configurations/A/pending but that also seems strange as logically we want to perform an operation on an approved resource.

Rather than having a singular Configuration with subresources, we could model separate pending and approved resources like so:

/configurations/pending/A
/configurations/approved/A

or we could go a step further and decouple the two and have different ids
/configurations/pending/123
/configurations/approved/A

But the same problem as listed above still remains.

Would like to hear other thoughts on how to model editing an approved resource.

Body:
But a PUT operation should be idempotent and have no side effects.

According to RFC 7231 PUT may have side effects as well, i.e. if you design a commit-like system similar to Git where a commit creates a new commit entry in the branch-tree while also moving the HEAD to the most recent version.

As further background, versioning and keeping track of a history of drafts is out of scope, users would collectively approve a single outstanding draft. An approved Configuration could be updated again with another pending draft so both approved and pending Configurations can be available side by side.

If we would design this for the Web, we probably should have a page to list all configurations and drafts and have links for each entry to edit and remove such a configuration/draft. As only drafts can be accepted/rejected, depending whether the resource at hand is a draft or not may contain the possibility to accept/reject it.

As mentioned accepting a draft should lead to the removal of the draft and the creation/replacement of the actual configuration. There are actually a couple of ways you might achieve this, depending on how you design things. In general, a URI as a whole is, as its name suggest, a unique resource identifier. Segments within that URI do not necessarily state a parent-child relationship automatically. One might create a set of URIs though that map such an ancestor tree onto resources that a server treats as parents and children.

PATCH is basically an operation where a client should calculate a set of instructions the server should apply to transform the target resource from its current form to a desired form atomically. So, either all of the instructions succeed or none at all. Depending on the chosen representation type (Hint: negotiated media type) such an operation might be doable.

With  JSON Patch (application/json-patch+json) you need to target an ancestor resource that you address to move that resource to a different location. Such a payload may look like this:

PATCH /configurations HTTP/1.1
Host: www.acme.com
Content-Type: application/json-patch+json; charset="utf-8"
ETag: 33a64df551425fcc55e4d42a148795d9f25f89d4
...

[
  {
    "op": "move",
    "from": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67",
    "path": "/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67"
  }
]

This basically tasks the server to move the specified draft resource and move it to the approved configuration resources. I've just taken your suggested names here. In a REST architecture they don't really matter. As this request should be created by the client, ideally the server is already providing the client with all the data it needs to create such a request. On the Web HTML supports such a feature through the help of Web forms that defines the admissible syntax and semantics of each of the elements and attributes. For JSON HAL-FORMS and Ion may be used to support you in this task.

In contrast to JSON Patch, JSON Merge-Patch, that defines a set of default rules to apply on a document, however, won't allow you to move a document unless you apply custom logic on the server.

Moving a resource through patching may interfere with caching though as the request here is not directed towards the actual draft resource but an, in terms of the cache, unrelated one. As caches should invalidate stored representations when an unsafe operation is performed on the target URI, not using the same URI that was used for retrieving that resource state representation therefore won't invalidate a stored representation for that draft resource upon accepting or rejecting and thus may lead to stale response data upon requesting the current state.

While PUT may have side effects, these are more or less limited to creating new resources as a consequence of the document replacement. You might "bend your design" in a way to send an empty PUT request to the current draft that leads to the server copying the current content to the accepted configurations. As PUT is an unsafe operation performed on the same URI the representation state was requested from, caches should invalidate any stored representations for that URI. However, depending on your server design this may lead to unwanted "empty" drafts being still available. This operation, however, still fulfills the idempotent requirements. Upon resending a request the effective outcome should be the same on each request, an "empty" resource.

As POST is the general-purpose tool of HTTP, by processing a request according to the resource's own semantics, you can use it anyway you like. If you, however, use a different URI so send that request to you may end up with the same caching issues PATCH struggles.

WebDAV specifies an idempotent, but not safe, MOVE operation, which can also be found in IANAs HTTP method registry. This method does what its name suggests. If moves the target resource to the destination location by performing a copy step, followed by a consistency maintenance step which ends with a deletion step of the target resource. These three steps will be performed atomically as well. A request here just looks like this, assuming the same URIs from above.

MOVE /configurations/drafs/eaff31bd-5291-4287-a7dd-fbe5b1e47b67
Host: www.acme.com
Destination: /configurations/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67

...

As this operation is unsafe any cached representation will be invalidated automatically.

An other possibility is to not expose the state of the configuration within the URI mapping but keep it within the resource itself. This would also only operate on the same URI for that configuration itself. Internally you'd have to store the current active configuration as well as any draft version within the same resource. The downside here though is that you basically send plenty more data within a single response, i.e. the stored current version and all of the admissible draft version. You may introduce certain filters though to only retrieve accepted, rejected or pending configurations. The representation format such a payload is returned for should possibly support a client to easily identify the current and draft versions here.

The question is then how to handle the edit case for an approved Configuration, which should create a pending configuration.

In case of JSON Patch you might try something like this:

PATCH /configurations HTTP/1.1
Host: www.acme.com
Content-Type: application/json-patch+json; charset="utf-8"
ETag: 33a64df551425fcc55e4d42a148795d9f25f89d4
...

[
  {
    "op": "copy",
    "from": "/approved/eaff31bd-5291-4287-a7dd-fbe5b1e47b67",
    "path": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67"
  },
  {
    "op": "replace",
    "path": "/drafts/eaff31bd-5291-4287-a7dd-fbe5b1e47b67/field1",
    "value": "new value"
  },
  ...
]

that first creates a copy of the current approved configuration version and then starts editing it. The atomic requirement of PATCH ensures that either all or none of the changes are applied.

In regards to updates of approved configurations via PUT, ideally the server issues a form-like representation to the client that teaches it how the resource state can be updated. Such representation would contain the necessary fields pre-filled with the current state that quickly allows a user to change the state of the resource. As editing an approved resource should resemble in the creation of a draft-resource first, the server should know about that and already instruct the client to send a PUT request to the draft endpoint rather than the original approved endpoint. Upon processing the response on the serve side it just needs to figure out whether there is content available or an empty payload to decide whether a draft was edited or accepted/rejected.

Via POST you are allowed to do whatever you want, so I don't think you need explanations in that case ...

On utilizing WebDAV methods you might need to split the instructions into multiple ones unfortunately. COPY will as its name implies copy the target resource to some location defined in the Destination header. Afterwards you can simply edit that file. If comparing it to a typical Web interaction, the resource could be copied already once a user clicks the edit button. The response to clicking the edit button will be a form representation containing the pre-filled data of the copied resource that upon clicking the submit button just performs a regular resource update on the draft resource. This interaction model needs to be mapped to a more generic layer though. Though the concepts remain the same. First a client needs to declare its interest in editing an already approved configuration, which leads to the creation of the copy in the draft space and afterwards returning a form representation allowing an application to supports its user to update the data.

In the last case, where you kept everything in one resource, creating a new draft on "editing" an accepted configuration only requires to add that modified version to the set of drafts. A server should compare the current configuration with the one provided in the request and if they differ, the provided payload needs to be added to the drafts.

As you can see, you have a couple of possibilities you can choose from. While patching seems to be a good choice, it doesn't coop with caching well and is also dependent on the media type negotiated. PUT demands a bit of "bending the rules" though could potentially be used to get the job done by also to invalidating any stored cache representation. POST is an all-purpose, general operation that can be used for literally anything you want or need. Last but not least redesigning your configurations and drafts into one single resource can also work.


问:
C++ Function that takes an array, a predicate and a operator as arguments and apply the operator to array's element where predicate is satisfied
I'm trying to write a function as described in title.
I made a template custom dynamic array called queue, and i need to create a function that checks for every element of this queue if a predicate passed by argument is satisfied; if it is, i need to apply an operator to that element also passed by argument.

First of all I probably need an explanation.. the predicate should be unary so it could be something like "isdigit" or "isalpha", right? and as operator it could be something like a simple post-increment ++.
The main problem is that I really don't have any idea how can I pass operators and predicates as parameters in function.

If I understood the request, here what I tried to do but of course is not working... anyone helping out?

```<code>template<typename L, typename OPERATOR>

void change_if(queue<L> &que, bool (*f)(L), OPERATOR op) {

    for(int i=0; i<que._size-1; i++) {
        if ((*f)(que._queue[i]))
            que._queue[i] = op(que._queue[i]);
    }
}

int main(){
    //as constructor, 3 is referred to size of the queue and 99 to the values.
    queue<int> q(3, 99);

    change_if(q, isdigit, ++);

}
</code>```

答:
First I would suggest to pass the predicate also with a inferred type, so you can also pass lambdas, i.e.

```<code>template<typename L, typename P, typename OP>
void change_if(queue<L> &que, P pred, OP op) {
  for(...)
    if(pred(que._queue[i]))
       que._queue[i] = op(que._queue[i]);
}
</code>```

Your idea is a bit inconsistent, as you do the assignment (que._queue[i] = op(que._queue[i]);) and then come up with the idea that op should be something like the post-increment operator.

Both together would boil down to a = a++ which has no effect.

You could go one of two ways:

think of "op" as a function, getting an element and returning an altered one, i.e. L op(const L&l) { return l+1; }. Then use the code above and call

change_if(q, [](auto && l) { return std::isdigit(l); }, [](auto && l) { return l + 1});

think of "op" as a function, changing the element it got, i.e. void op(L&l) { l++;}. Then use if(pred(...)) op(que._queue[i]) and call

change_if(q, [](auto && l) { return std::isdigit(l); }, [](auto && l) { l++; });

As a side note: you cannot simply take the address of std::isdigit as it is overloaded so I wrapped the call in a lambda here.

Another side note: I don't know your queue implementation but < size-1 in the for loop's condition looks a bit like you're missing the last element.

Body:
I'm trying to write a function as described in title.
I made a template custom dynamic array called queue, and i need to create a function that checks for every element of this queue if a predicate passed by argument is satisfied; if it is, i need to apply an operator to that element also passed by argument.

First of all I probably need an explanation.. the predicate should be unary so it could be something like "isdigit" or "isalpha", right? and as operator it could be something like a simple post-increment ++.
The main problem is that I really don't have any idea how can I pass operators and predicates as parameters in function.

If I understood the request, here what I tried to do but of course is not working... anyone helping out?

template<typename L, typename OPERATOR>

void change_if(queue<L> &que, bool (*f)(L), OPERATOR op) {

    for(int i=0; i<que._size-1; i++) {
        if ((*f)(que._queue[i]))
            que._queue[i] = op(que._queue[i]);
    }
}

int main(){
    //as constructor, 3 is referred to size of the queue and 99 to the values.
    queue<int> q(3, 99);

    change_if(q, isdigit, ++);

}

Body:
First I would suggest to pass the predicate also with a inferred type, so you can also pass lambdas, i.e.

template<typename L, typename P, typename OP>
void change_if(queue<L> &que, P pred, OP op) {
  for(...)
    if(pred(que._queue[i]))
       que._queue[i] = op(que._queue[i]);
}

Your idea is a bit inconsistent, as you do the assignment (que._queue[i] = op(que._queue[i]);) and then come up with the idea that op should be something like the post-increment operator.

Both together would boil down to a = a++ which has no effect.

You could go one of two ways:

think of "op" as a function, getting an element and returning an altered one, i.e. L op(const L&l) { return l+1; }. Then use the code above and call

change_if(q, [](auto && l) { return std::isdigit(l); }, [](auto && l) { return l + 1});

think of "op" as a function, changing the element it got, i.e. void op(L&l) { l++;}. Then use if(pred(...)) op(que._queue[i]) and call

change_if(q, [](auto && l) { return std::isdigit(l); }, [](auto && l) { l++; });

As a side note: you cannot simply take the address of std::isdigit as it is overloaded so I wrapped the call in a lambda here.

Another side note: I don't know your queue implementation but < size-1 in the for loop's condition looks a bit like you're missing the last element.


问:
http get from assets not work in published app Angular 9
i worked with Angular +9 and i've a problem when read json file from assets folder.

i am using the http module and the call works fine when the application is run locally, but when i run ng-build and publish the application on a server, the call to the json file doesn't work indicating the following message:

ERROR Http failure response for assets/resources/fakeData.json: 0 Unknown Error

My code:

What could be the problem? Why can't I access the assets folder directly?

答:
I don't know which web server you are using, but it looks like your web server does not support hosting of JSON-files.

Apache: use the AddType directive - https://cets.seas.upenn.edu/answers/addtype.html

IIS: Add a MIME-type - https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap


问:
Flask+MySQL. App reloads the same page instead of routing and it fails to add values to mysql db
I know there is much of code below, but i had to show the html/css/js and flask+mysql codes for better understanding. Ask if anything is not clear.

The problem is that, after i give the credentials in the register page and i submit, i expect for it to add the values to database and to route to the login page, but what it does actually, is that it reloads the same page, and the link look like this,

i.e.:

"http://127.0.0.1:5000/register/patient?name_surname=jack+stathem&email=jsm%40outlook.com&ssn=123456789&age=40"

i am having some semantic error and i cant figure out how to fix.

Thank you

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
    // document.getElementById("nextBtn").value = "submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }
  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code> /* Style the form */
#regForm {
  background-color: #ffffff;
  margin: 100px auto;
  padding: 40px;
  width: 70%;
  min-width: 300px;
}

/* Style the input fields */
input {
  padding: 10px;
  width: 100%;
  font-size: 17px;
  font-family: Raleway;
  border: 1px solid #aaaaaa;
}

/* Mark input boxes that gets an error on validation: */
input.invalid {
  background-color: #ffdddd;
}

/* Hide all steps by default: */
.tab {
  display: none;
}

/* Make circles that indicate the steps of the form: */
.step {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbbbbb;
  border: none;
  border-radius: 50%;
  display: inline-block;
  opacity: 0.5;
}

/* Mark the active step: */
.step.active {
  opacity: 1;
}

/* Mark the steps that are finished and valid: */
.step.finish {
  background-color: #4CAF50;
} </code>```

{% extends 'main.html' %}

{% block head %}
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style/docnpatientreg.css') }}">
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap-tagsinput.css') }}">
{% endblock %}

{% block body %}
    <form id="regForm">

Register:

Name:

<input name="name_surname" type="text" placeholder="First name...">

<input name='email' type="email" placeholder="E-mail...">

<input name='ssn' type="text" placeholder="SSN">

<input name='age' type="text" placeholder="Age">

                <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
                <button type="submit" id="nextBtn" onclick="nextPrev(1)">Next</button>

    </form>

{% endblock %}```
</div>
</div>
</p>

<p>Flask+MySQL</p>

<p><strong>Note</strong>: It is not the whole code, if needed i will post it</p>

```@medAI.route('/')
def main_base():

  cursor.execute("select * from Patients")
  result = cursor.fetchall()
  print(result)

  return render_template('main.html')

@medAI.route('/register/<where>', methods=['GET','POST'])
def register(where):

  if where == "patient":
      if request.method == "GET":
          print("get phase")
          return render_template("patientreg.html")

      else:
          print("post phase")
          name_surname=request.form['name_surname']
          emailadd=request.form['email']
          # weight=request.form['weight']
          # height=request.form['']
          ssn=request.form['ssn']
          age=request.form['age']
          # gender=request.form['gender']
          # symptoms=request.form['symptoms']

      cursor.execute('select * from Patients')
      patients = cursor.fetchall()
      print(patients)

      check = True

      for patient in patients:
          print(patient[0])

      if check == True:
          cursor.execute("insert into patients(name_surname,emailadd, ssn)"
                         "values(%s);",(name_surname,emailadd, ssn, age,))
          database.commit()
          print('done')
      else:
          print('failed')
          return redirect('/register/patient')

      return redirect('/login/')

  elif where == "doctor":
      pass
  return "Invalid Registration Attempt"
```

答:
"action" and "method" are missing in the form.

```<code><form id="regForm" action="/register/patient" method="POST">
</code>```

Body:
I know there is much of code below, but i had to show the html/css/js and flask+mysql codes for better understanding. Ask if anything is not clear.

The problem is that, after i give the credentials in the register page and i submit, i expect for it to add the values to database and to route to the login page, but what it does actually, is that it reloads the same page, and the link look like this,

i.e.:

"http://127.0.0.1:5000/register/patient?name_surname=jack+stathem&email=jsm%40outlook.com&ssn=123456789&age=40"

i am having some semantic error and i cant figure out how to fix.

Thank you

var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
  // ... and fix the Previous/Next buttons:
  if (n == 0) {
    document.getElementById("prevBtn").style.display = "none";
  } else {
    document.getElementById("prevBtn").style.display = "inline";
  }
  if (n == (x.length - 1)) {
    document.getElementById("nextBtn").innerHTML = "Submit";
    // document.getElementById("nextBtn").value = "submit";
  } else {
    document.getElementById("nextBtn").innerHTML = "Next";
  }
  // ... and run a function that displays the correct step indicator:
  fixStepIndicator(n)
}

function nextPrev(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab");
  // Exit the function if any field in the current tab is invalid:
  if (n == 1 && !validateForm()) return false;
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);
}

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

 /* Style the form */
#regForm {
  background-color: #ffffff;
  margin: 100px auto;
  padding: 40px;
  width: 70%;
  min-width: 300px;
}

/* Style the input fields */
input {
  padding: 10px;
  width: 100%;
  font-size: 17px;
  font-family: Raleway;
  border: 1px solid #aaaaaa;
}

/* Mark input boxes that gets an error on validation: */
input.invalid {
  background-color: #ffdddd;
}

/* Hide all steps by default: */
.tab {
  display: none;
}

/* Make circles that indicate the steps of the form: */
.step {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbbbbb;
  border: none;
  border-radius: 50%;
  display: inline-block;
  opacity: 0.5;
}

/* Mark the active step: */
.step.active {
  opacity: 1;
}

/* Mark the steps that are finished and valid: */
.step.finish {
  background-color: #4CAF50;
}

{% extends 'main.html' %}

{% block head %}
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style/docnpatientreg.css') }}">
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap-tagsinput.css') }}">
{% endblock %}

{% block body %}
    <form id="regForm">

Register:

Name:

<input name="name_surname" type="text" placeholder="First name...">

<input name='email' type="email" placeholder="E-mail...">

<input name='ssn' type="text" placeholder="SSN">

<input name='age' type="text" placeholder="Age">

                <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
                <button type="submit" id="nextBtn" onclick="nextPrev(1)">Next</button>

    </form>

{% endblock %}

Flask+MySQL

Note: It is not the whole code, if needed i will post it

@medAI.route('/')
def main_base():

  cursor.execute("select * from Patients")
  result = cursor.fetchall()
  print(result)

  return render_template('main.html')

@medAI.route('/register/<where>', methods=['GET','POST'])
def register(where):

  if where == "patient":
      if request.method == "GET":
          print("get phase")
          return render_template("patientreg.html")

      else:
          print("post phase")
          name_surname=request.form['name_surname']
          emailadd=request.form['email']
          # weight=request.form['weight']
          # height=request.form['']
          ssn=request.form['ssn']
          age=request.form['age']
          # gender=request.form['gender']
          # symptoms=request.form['symptoms']

      cursor.execute('select * from Patients')
      patients = cursor.fetchall()
      print(patients)

      check = True

      for patient in patients:
          print(patient[0])

      if check == True:
          cursor.execute("insert into patients(name_surname,emailadd, ssn)"
                         "values(%s);",(name_surname,emailadd, ssn, age,))
          database.commit()
          print('done')
      else:
          print('failed')
          return redirect('/register/patient')

      return redirect('/login/')

  elif where == "doctor":
      pass
  return "Invalid Registration Attempt"

Body:
"action" and "method" are missing in the form.

<form id="regForm" action="/register/patient" method="POST">


问:
MongoDB Compass: How to select Distinct Values of a Field
I have a MongoDB database where each entry has a 'comment' field. I'm using MongoDB Compass to connect to it, and trying to find all unique values of the 'comment' field. I tried the following code in the 'Aggregations' Tab of Compass (see image below), but I didn't get any result:

```<code>{$group: {
  _id: null,
  unique_comments: {
    $addToSet: comment
  }
}
</code>```

An example of the data, in JSON format, is:

```<code>{"name":"Hannah Maxwell","date":"2020-01-07T20:16:13.931629-08:00","comment":"Maybe I like camping","location":{"latitude":43.81710433959961,"longitude":-79.42430114746094,"country":"CA","region":"ON"},"likes":1,"responses":24}
{"name":"Jordan Rodriguez","date":"2019-04-28T20:16:13.931629-07:00","comment":"I hate skiing","location":{"latitude":43.41518783569336,"longitude":-80.51475524902344,"country":"CA","region":"ON"},"likes":5,"responses":1}
{"name":"Bodhi Mckenzie","date":"2019-07-09T20:16:13.931629-07:00","comment":"I think I might like skiing","location":{"latitude":43.65549087524414,"longitude":-79.38555908203125,"country":"CA","region":"ON"},"likes":65,"responses":5}
</code>```

答:
In MongoDB Compass you need to pick the Aggregation Pipeline stage from the menu, try:

The preview data should get displayed on the right-hand side

Body:
I have a MongoDB database where each entry has a 'comment' field. I'm using MongoDB Compass to connect to it, and trying to find all unique values of the 'comment' field. I tried the following code in the 'Aggregations' Tab of Compass (see image below), but I didn't get any result:

{$group: {
  _id: null,
  unique_comments: {
    $addToSet: comment
  }
}

An example of the data, in JSON format, is:

{"name":"Hannah Maxwell","date":"2020-01-07T20:16:13.931629-08:00","comment":"Maybe I like camping","location":{"latitude":43.81710433959961,"longitude":-79.42430114746094,"country":"CA","region":"ON"},"likes":1,"responses":24}
{"name":"Jordan Rodriguez","date":"2019-04-28T20:16:13.931629-07:00","comment":"I hate skiing","location":{"latitude":43.41518783569336,"longitude":-80.51475524902344,"country":"CA","region":"ON"},"likes":5,"responses":1}
{"name":"Bodhi Mckenzie","date":"2019-07-09T20:16:13.931629-07:00","comment":"I think I might like skiing","location":{"latitude":43.65549087524414,"longitude":-79.38555908203125,"country":"CA","region":"ON"},"likes":65,"responses":5}


问:
How to make user control header load only one time?
I'm implementing a user control in an asp.net website.  The user control will be used as a header in all pages.  How can load the user control content depends on the user (logged in, logged out, user name).

How can i load my user control only one time?  For example, when the user is logged in like quora.  To have an idea of what i mean, log into quora, you will notice: every time,i open a page of a question,the quora header is not reloaded.only the main content changes.

How that is achieved?

答:
I did not signup with quora, but the public pages still have a consistent header, but the header is downloaded each time a request is made. I think the simplicity makes it hard to tell that the entire screen is being redrawn.

You could use ajax to make a request and only redraw a portion of the page if that is what you desire. Or, you could go old school and use frames (please don't).


问:
Altair heatmap independent color map calculation per row
I am trying to plot a heatmap using altair. The idea is that the color mapping is applied independently to each of the rows and not across all the observations. Unfortunately, this is what I get so far.

As you can see on the graph, you can only see changes in one row, because this is the one with more cases. However, the idea is to apply the mapping for each row and not all together.

This is the code that I have so far:

data = pd.read_csv(
    "https://raw.githubusercontent.com/jlcoto/covid-peru-data/master"
    "/data/limpia/data_limpia_datos_siscovid_2020_05_26.csv",
    parse_dates=["fecha_resultado"],
    dtype={"ubigeo": "string"},
)

evol_departamento = (
    data.groupby(
        ["departamento", pd.Grouper(key="fecha_resultado", freq="D")]
    )[["uuid"]]
    .count()
    .rename(columns={"uuid": "num_casos"})
    .reset_index()
)

alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos:Q"),
).resolve_scale(color="independent",)
```

I saw this reply about using resolve_scale, however it does not seem to do the trick.

答:
The resolve functionality only applies across multi-panel charts (facet, concat, repeat, layer, etc.) To adjust the color scale within the encoding for a single chart, the best approach is to use altair transforms to compute a normalized version of your data.

Here is an example for your dataset:

```<code>alt.Chart(evol_departamento).transform_joinaggregate(
    max_casos='max(num_casos)',
    groupby=['departamento']
).transform_calculate(
    num_casos_norm='datum.num_casos / datum.max_casos'
).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos_norm:Q"),
)
</code>```

Body:
I am trying to plot a heatmap using altair. The idea is that the color mapping is applied independently to each of the rows and not across all the observations. Unfortunately, this is what I get so far.

As you can see on the graph, you can only see changes in one row, because this is the one with more cases. However, the idea is to apply the mapping for each row and not all together.

This is the code that I have so far:

data = pd.read_csv(
    "https://raw.githubusercontent.com/jlcoto/covid-peru-data/master"
    "/data/limpia/data_limpia_datos_siscovid_2020_05_26.csv",
    parse_dates=["fecha_resultado"],
    dtype={"ubigeo": "string"},
)

evol_departamento = (
    data.groupby(
        ["departamento", pd.Grouper(key="fecha_resultado", freq="D")]
    )[["uuid"]]
    .count()
    .rename(columns={"uuid": "num_casos"})
    .reset_index()
)

alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos:Q"),
).resolve_scale(color="independent",)

I saw this reply about using resolve_scale, however it does not seem to do the trick.

Body:
The resolve functionality only applies across multi-panel charts (facet, concat, repeat, layer, etc.) To adjust the color scale within the encoding for a single chart, the best approach is to use altair transforms to compute a normalized version of your data.

Here is an example for your dataset:

alt.Chart(evol_departamento).transform_joinaggregate(
    max_casos='max(num_casos)',
    groupby=['departamento']
).transform_calculate(
    num_casos_norm='datum.num_casos / datum.max_casos'
).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos_norm:Q"),
)


问:
Can't run React Native App due to react navigation errors
I started making my first react native app but I keep running into issues with react-navigation. In my app.js file, I included

```<code>import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
</code>```

but I ran into this error: Error Message

Before I used these import statements here:

```<code>import { NavigationContainer } from 'react-navigation-stack';
import { createStackNavigator } from 'react-navigation-stack';
</code>```

But ran into this error: Error Message

Which one should I use and how do I fix each error?

This is my App.js file:

```<code>import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import profile from './components/Profile';
import messages from './components/Messages';
import home from './components/Home';
import signInScreen from './components/signInScreen';
import signUpScreen from './components/signUpScreen';

const Stack = createStackNavigator();

export default function App()
{
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName= "Sign In" screenOptions={{headerShown: false}}>
        <Stack.Screen name="Sign In" component={signInScreen}/>
        <Stack.Screen name="Sign Up" component={signUpScreen}/>
        <Stack.Screen name="Home" component={home}/>
        <Stack.Screen name="Messages" component={messages}/>
        <Stack.Screen name="Profile" component={profile}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

答:
I was able to fix my issue by playing around with the react-navigation dependencies. I got some warnings saying that some of my dependencies were too new so I uninstalled and installed them again but I decided to try and install react-navigation again for the 3rd time from the react-navigation docs:Install command for Expo managed Project

After that, my project started working.

Body:
I started making my first react native app but I keep running into issues with react-navigation. In my app.js file, I included

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

but I ran into this error: Error Message

Before I used these import statements here:

import { NavigationContainer } from 'react-navigation-stack';
import { createStackNavigator } from 'react-navigation-stack';

But ran into this error: Error Message

Which one should I use and how do I fix each error?

This is my App.js file:

import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import profile from './components/Profile';
import messages from './components/Messages';
import home from './components/Home';
import signInScreen from './components/signInScreen';
import signUpScreen from './components/signUpScreen';

const Stack = createStackNavigator();

export default function App()
{
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName= "Sign In" screenOptions={{headerShown: false}}>
        <Stack.Screen name="Sign In" component={signInScreen}/>
        <Stack.Screen name="Sign Up" component={signUpScreen}/>
        <Stack.Screen name="Home" component={home}/>
        <Stack.Screen name="Messages" component={messages}/>
        <Stack.Screen name="Profile" component={profile}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}


问:
Remove duplicated rows on gridview
Hi There I have the following grid view developed with vb.net and html

This is the code to fill the gridview

```<code> Private Sub BindGrid()
    Dim modelo As String = txtModelo.Text
    Dim linha As String = txtLinha.Text
    Dim data As String = txtData.Text
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("SELECT * FROM tempo where timermodelo = @timermodelo and timerlinha = @timerlinha and timerdata = @timerdata")
            Using sda As New MySqlDataAdapter()
                cmd.Parameters.AddWithValue("@timermodelo", modelo)
                cmd.Parameters.AddWithValue("@timerlinha", linha)
                cmd.Parameters.AddWithValue("@timerdata", data)
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
</code>```

My question is, is it possible to remove the duplicated rows on the column Operador, Posto, Linha and Modelo?
And also how can I form the date to show 'dd-mm-yyyy'?
Actually, I want to merge these values, if they are the same, show just one time
Sorry if it is difficult to understand, if more information is needed let me know
Thanks in advance

答:
Remove duplicates : Why don't you use SqlStatement that return rows without duplication, depending on your Database type 'you did not mention', if this is achievable in your SqlStatement then this problem is solved.

Format Date in GridView1 cell : Use GridView1_CellFormatting event [ Where your Date ColumnIndex = 4] as follows

```<code>Private Sub GridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
If Not IsNothing(e.Value) Then
            If e.ColumnIndex().ToString = 4 And IsDate(e.Value) Then
               e.Value = Format(e.Value, "dd-mm-yyyy")
            End If
         End If
End Sub
</code>```

I want to merge these values, if they are the same

What values are we talking about here ?

Title: Remove duplicated rows on gridview

Body:
Hi There I have the following grid view developed with vb.net and html

This is the code to fill the gridview

 Private Sub BindGrid()
    Dim modelo As String = txtModelo.Text
    Dim linha As String = txtLinha.Text
    Dim data As String = txtData.Text
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("SELECT * FROM tempo where timermodelo = @timermodelo and timerlinha = @timerlinha and timerdata = @timerdata")
            Using sda As New MySqlDataAdapter()
                cmd.Parameters.AddWithValue("@timermodelo", modelo)
                cmd.Parameters.AddWithValue("@timerlinha", linha)
                cmd.Parameters.AddWithValue("@timerdata", data)
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub

My question is, is it possible to remove the duplicated rows on the column Operador, Posto, Linha and Modelo?
And also how can I form the date to show 'dd-mm-yyyy'?
Actually, I want to merge these values, if they are the same, show just one time
Sorry if it is difficult to understand, if more information is needed let me know
Thanks in advance

Body:
Remove duplicates : Why don't you use SqlStatement that return rows without duplication, depending on your Database type 'you did not mention', if this is achievable in your SqlStatement then this problem is solved.

Format Date in GridView1 cell : Use GridView1_CellFormatting event [ Where your Date ColumnIndex = 4] as follows

Private Sub GridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
If Not IsNothing(e.Value) Then
            If e.ColumnIndex().ToString = 4 And IsDate(e.Value) Then
               e.Value = Format(e.Value, "dd-mm-yyyy")
            End If
         End If
End Sub

I want to merge these values, if they are the same

What values are we talking about here ?


问:
Drawing border of constant width around image in OpenGL on Android and iOS
I am trying to draw a border around an image that is rendered using OpenGL on an Android and iOS app. The way I do it now is that I specify the 3 vertices around each corner of the image as shown in the diagram and fill them up by drawing triangles.

The way I compute these vertices is by adding/subtracting an absolute value called BORDER_WIDTH that is set to a float. For example, the  3 vertices around the left corner of the rendered image (marked as 0,1,2 in the image linked above) are computed as follows.

```<code>[bottom_left_viewport_vertex[0] - BORDER_WIDTH, bottom_left_viewport_vertex[1], 0.0f,
bottom_left_viewport_vertex[0] - BORDER_WIDTH, bottom_left_viewport_vertex[1] - BORDER_WIDTH, 0.0f,
bottom_left_viewport_vertex[0], bottom_left_viewport_vertex[1] - BORDER_WIDTH, 0.0f]
</code>```

This method causes 2 problems:

The border is way thicker on iOS devices compared to Android devices probably because of the Retina display.

The width of the border on the top and the bottom of the image is different from that on the sides of the image.

What is the right way to solve such a problem?
Thank you.

答:
The border is way thicker on iOS devices compared to Android devices probably because of the Retina display.

Determine the DPI using DisplayMetrics, and adjust your BORDER_WIDTH value as appropriate.

The width of the border on the top and the bottom of the image is different from that on the sides of the image.

Viewport coordinates are between zero and one, regardless of aspect ratio. If you're not correcting for aspect ratio, then everything is going to get scaled by that.

Alternatively, you are doing calculations assuming pixels are square. They usually aren't.

Body:
I am trying to draw a border around an image that is rendered using OpenGL on an Android and iOS app. The way I do it now is that I specify the 3 vertices around each corner of the image as shown in the diagram and fill them up by drawing triangles.

The way I compute these vertices is by adding/subtracting an absolute value called BORDER_WIDTH that is set to a float. For example, the  3 vertices around the left corner of the rendered image (marked as 0,1,2 in the image linked above) are computed as follows.

[bottom_left_viewport_vertex[0] - BORDER_WIDTH, bottom_left_viewport_vertex[1], 0.0f,
bottom_left_viewport_vertex[0] - BORDER_WIDTH, bottom_left_viewport_vertex[1] - BORDER_WIDTH, 0.0f,
bottom_left_viewport_vertex[0], bottom_left_viewport_vertex[1] - BORDER_WIDTH, 0.0f]

This method causes 2 problems:

The border is way thicker on iOS devices compared to Android devices probably because of the Retina display.

The width of the border on the top and the bottom of the image is different from that on the sides of the image.

What is the right way to solve such a problem?
Thank you.


问:
How to configre Create React Apps default Service Worker to cache assets that are not in react src Context (public Folder)?
today I tried the ServiceWorker of Create React App and everything is cached except the Favicon of my Page which is defined in public/img/favicon.ico, so when the Page is Offline the Favicon disapears and Connection Error is displayed in Console, so does anyone has experience how to configure webpage Plugin of the Service worker to cache this too?</p>

答:
I have a CRA project here.  I don't precache my favicon, I let a default handler runtime cache it, but I do precache a fallback image and you should be able to do the same to precache your favicon.

CRA creates a default sw which I don't think I touched.  To get more control I use workbox in a sw-addendum file that I append to the default sw in the build.  In the addendum you can precache what you need and set up routes, etc.

see package.json for postdeploy script

```<code>"postdeploy": "cp src/face.69232788.jpg docs/face.69232788.jpg && cat src/swAddendum.js >> docs/service-worker.js",
</code>```

sw-addendum here

workbox.precaching.precache([
  './face.69232788.jpg',
]);
```

Body:
I have a CRA project here.  I don't precache my favicon, I let a default handler runtime cache it, but I do precache a fallback image and you should be able to do the same to precache your favicon.

CRA creates a default sw which I don't think I touched.  To get more control I use workbox in a sw-addendum file that I append to the default sw in the build.  In the addendum you can precache what you need and set up routes, etc.

see package.json for postdeploy script

"postdeploy": "cp src/face.69232788.jpg docs/face.69232788.jpg && cat src/swAddendum.js >> docs/service-worker.js",

sw-addendum here

workbox.precaching.precache([
  './face.69232788.jpg',
]);


问:
How would I go about scraping data from a website and updating a file with the new info each day while saving older data?
I was initially planning on using a CSV file, however it would require me to manually log into VScode each day and run my script to add the data to a csv file, and it would replace the old data that I had previously input.</p>

答:
If your scraped dataset is small, scrape the data to a nested list of dictionaries with the structure [{<column1>: <data>, <column2>: <data>, ...}, ...] for each row you want to save, then use this function to append that dictionary to a csv file by doing append_csv_dict(<path_to_your_csv>, <your_dictionary>):

import csv

def append_csv_dict(path, data):
    '''
    Append a csv with a dictionary keys as column headers
    Args:
        path (str): Path to the csv file
        data (dict or list): Dictionary or list(dict) with keys as
                             column  headers and values as column data
    '''
    with open(path, 'a') as file:
        # set the field names to the keys of the dictionary or keys of the first item
        fieldnames = list(data.keys()) if isinstance(data, dict) else data[0].keys()
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        # write the header if the file is new
        if file.tell() == 0:
            writer.writeheader()
        if isinstance(data, dict):
            fieldnames = list(data.keys())
            # write the row
            writer.writerow(data)
        elif isinstance(data, list):
            # write the rows if it is a list
            writer.writerows(data)

# some example data, you can do one dictionary at a time if you only do one row per day
scraped_data = [
    {
        'first_name': 'John',
        'last_name': 'Do',
        'age': 31
    },
    {
        'first_name': 'Jane',
        'last_name': 'Do',
        'age': 33
    },
    {
        'first_name': 'Foo',
        'last_name': 'Bar',
        'age': 58
    }
]

append_csv_dict('./scrape.csv', scraped_data)
```

<p>Output (scrape.csv):</p>

```first_name,last_name,age
John,Do,31
Jane,Do,33
Foo,Bar,58
```

Body:
If your scraped dataset is small, scrape the data to a nested list of dictionaries with the structure [{<column1>: <data>, <column2>: <data>, ...}, ...] for each row you want to save, then use this function to append that dictionary to a csv file by doing append_csv_dict(<path_to_your_csv>, <your_dictionary>):

import csv

def append_csv_dict(path, data):
    '''
    Append a csv with a dictionary keys as column headers
    Args:
        path (str): Path to the csv file
        data (dict or list): Dictionary or list(dict) with keys as
                             column  headers and values as column data
    '''
    with open(path, 'a') as file:
        # set the field names to the keys of the dictionary or keys of the first item
        fieldnames = list(data.keys()) if isinstance(data, dict) else data[0].keys()
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        # write the header if the file is new
        if file.tell() == 0:
            writer.writeheader()
        if isinstance(data, dict):
            fieldnames = list(data.keys())
            # write the row
            writer.writerow(data)
        elif isinstance(data, list):
            # write the rows if it is a list
            writer.writerows(data)

# some example data, you can do one dictionary at a time if you only do one row per day
scraped_data = [
    {
        'first_name': 'John',
        'last_name': 'Do',
        'age': 31
    },
    {
        'first_name': 'Jane',
        'last_name': 'Do',
        'age': 33
    },
    {
        'first_name': 'Foo',
        'last_name': 'Bar',
        'age': 58
    }
]

append_csv_dict('./scrape.csv', scraped_data)

Output (scrape.csv):

first_name,last_name,age
John,Do,31
Jane,Do,33
Foo,Bar,58


问:
Getting a ValueError in tensorflow saying that my shapes are incompatible
Error:

```<code>return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
    C:\Users\selvaa\miniconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\backend.py:4619 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Users\selvaa\miniconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1128 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 1) and (None, 151) are incompatible
</code>```

My model:

```<code>x = np.array(x)
y = np.array(y)

x = x/255.0

model = Sequential()
model.add(Conv2D(3, (3,3), input_shape=(128,128,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(302, activation='relu'))
model.add(Dense(151, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x, y, batch_size=32, epochs=5, verbose=1, validation_split=0.1)
</code>```

I'm trying to train a model to identify different pokemon, I have two pictures of each 151 pokemon for my datasets (correctly labeled and all). Not sure what I'm doing wrong.

Here is what happens when I print x.shape and y.shape:

```<code>(301, 128, 128, 3) (301,)
</code>```

答:
Use the loss tf.keras.losses.SparseCategoricalCrossEntropy, as shown in the code example below.

The loss function tf.keras.losses.SparseCategoricalCrossEntropy accepts reference labels in the shape (n_samples,) and predicted labels in the shape (n_samples, n_classes), which would work for your data. You cannot use categorical_crossentropy because that expects your labels to be one-hot encoded (see bottom of answer).

```<code>x = np.array(x)
y = np.array(y)

x = x / 255.0

model = Sequential()
model.add(Conv2D(3, (3,3), input_shape=(128,128,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(302, activation='relu'))
model.add(Dense(151, activation='softmax'))

model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    optimizer='adam',
    metrics=['accuracy'])

model.fit(x, y, batch_size=32, epochs=5, verbose=1, validation_split=0.1)
</code>```

Another solution is to one-hot encode your labels prior to training, for example using the function tf.one_hot. If you use this approach, then you can use categorical_crossentropy.

Body:
Error:

return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
    C:\Users\selvaa\miniconda3\envs\tensorflow\lib\site-packages\tensorflow\python\keras\backend.py:4619 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Users\selvaa\miniconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1128 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 1) and (None, 151) are incompatible

My model:

x = np.array(x)
y = np.array(y)

x = x/255.0

model = Sequential()
model.add(Conv2D(3, (3,3), input_shape=(128,128,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(302, activation='relu'))
model.add(Dense(151, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x, y, batch_size=32, epochs=5, verbose=1, validation_split=0.1)

I'm trying to train a model to identify different pokemon, I have two pictures of each 151 pokemon for my datasets (correctly labeled and all). Not sure what I'm doing wrong.

Here is what happens when I print x.shape and y.shape:

(301, 128, 128, 3) (301,)

Body:
Use the loss tf.keras.losses.SparseCategoricalCrossEntropy, as shown in the code example below.

The loss function tf.keras.losses.SparseCategoricalCrossEntropy accepts reference labels in the shape (n_samples,) and predicted labels in the shape (n_samples, n_classes), which would work for your data. You cannot use categorical_crossentropy because that expects your labels to be one-hot encoded (see bottom of answer).

x = np.array(x)
y = np.array(y)

x = x / 255.0

model = Sequential()
model.add(Conv2D(3, (3,3), input_shape=(128,128,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(302, activation='relu'))
model.add(Dense(151, activation='softmax'))

model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    optimizer='adam',
    metrics=['accuracy'])

model.fit(x, y, batch_size=32, epochs=5, verbose=1, validation_split=0.1)

Another solution is to one-hot encode your labels prior to training, for example using the function tf.one_hot. If you use this approach, then you can use categorical_crossentropy.