问:
Checking whether the ports on a given host is open or not
I am trying to find whether the ports are open or closed in a given host. I am bewildered whether this is a correct approach to do it. Here I only check ports from 0 to 1024. Could someone say whether it is correct since most of my ports are closed and some are only open and also is there any way to print the port name like if port number is 80 the port name is HTTP.</p>

```<code>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netdb.h>
#include<error.h>
#include<errno.h>

char *convert_int_to_string(int num)
{
    int tmp;
    int i = 0;
    int j = 0;
    static char a[5] = {'0'};

    while (num > 0) {
        tmp = num % 10;
        a[i++] = tmp + '0';
        num = num / 10;
    }
    a[i] = '\0';
    for (j = 0; j < i / 2; j++) {
        tmp = a[j];
        a[j] = a[i - j - 1];
        a[i - j - 1] = tmp;
    }
    return a;
}

int main(int argc, char **argv)
{
    int status;
    char *node;
    char *port_no;
    int sock_fd;
    int i = 0;
    struct  addrinfo hints, *serviceinfo;

    if (argc != 2)
        error(1, errno, "Too many or few arguments\n");
    node = argv[1];
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    for (i = 0; i < 1024; i++) {
        port_no = convert_int_to_string(i);
        status = getaddrinfo(node, port_no, &hints, &serviceinfo);
        if (status != 0) {
            error(1, errno, "error in getaddrinfo() function call\n");
        }
        sock_fd = socket(serviceinfo->ai_family, serviceinfo->ai_socktype, serviceinfo->ai_protocol);
        if (sock_fd == -1)
            error(1, errno, "error in socket() function call\n");
        status = connect(sock_fd, serviceinfo->ai_addr, serviceinfo->ai_addrlen);
        if (status != -1)
            printf("Port : %s is open\n", port_no);
        else
            printf("Port : %s is closed\n", port_no);
    }
}

</code>```

答:
If you're only trying to check TCP ports and not UDP, I would recommend simply trying to connect() to the server and wait a certain amount of time before you assume that port is closed.

You'll have to use poll() or select() in order to timeout the connect() call.
(C: socket connection timeout)

Here's a working example:
(works only with IPs, not domain name so you'd have to ping the server in order to find out its IP address or implement the dns query yourself)

```<code>#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>

#define MAX_PORT 1024
#define TIMEOUT 5000

int main(int argc, char *argv[])
{
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = inet_addr(argv[1])
    };
    struct pollfd fds[1];

    for (uint16_t port = 0; port < MAX_PORT; port++) {
        int8_t sock = socket(PF_INET, SOCK_STREAM, 0);
        fcntl(sock, F_SETFL, O_NONBLOCK);
        fds[0].fd = sock;
        fds[0].events = POLLOUT;
        addr.sin_port = htons(port);

        if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
            if (errno == EINPROGRESS) {
                if (poll(fds, 1, TIMEOUT) > 0)
                    printf("Port %d opened.\n", port);
                else
                    printf("Port %d closed.\n", port);
            }
            else
                printf("Port %d closed.\n", port);
        }
        else
            printf("Port %d opened.\n", port);
        close(sock);
    }
}
</code>```

Body:
I am trying to find whether the ports are open or closed in a given host. I am bewildered whether this is a correct approach to do it. Here I only check ports from 0 to 1024. Could someone say whether it is correct since most of my ports are closed and some are only open and also is there any way to print the port name like if port number is 80 the port name is HTTP.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netdb.h>
#include<error.h>
#include<errno.h>

char *convert_int_to_string(int num)
{
    int tmp;
    int i = 0;
    int j = 0;
    static char a[5] = {'0'};

    while (num > 0) {
        tmp = num % 10;
        a[i++] = tmp + '0';
        num = num / 10;
    }
    a[i] = '\0';
    for (j = 0; j < i / 2; j++) {
        tmp = a[j];
        a[j] = a[i - j - 1];
        a[i - j - 1] = tmp;
    }
    return a;
}

int main(int argc, char **argv)
{
    int status;
    char *node;
    char *port_no;
    int sock_fd;
    int i = 0;
    struct  addrinfo hints, *serviceinfo;

    if (argc != 2)
        error(1, errno, "Too many or few arguments\n");
    node = argv[1];
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    for (i = 0; i < 1024; i++) {
        port_no = convert_int_to_string(i);
        status = getaddrinfo(node, port_no, &hints, &serviceinfo);
        if (status != 0) {
            error(1, errno, "error in getaddrinfo() function call\n");
        }
        sock_fd = socket(serviceinfo->ai_family, serviceinfo->ai_socktype, serviceinfo->ai_protocol);
        if (sock_fd == -1)
            error(1, errno, "error in socket() function call\n");
        status = connect(sock_fd, serviceinfo->ai_addr, serviceinfo->ai_addrlen);
        if (status != -1)
            printf("Port : %s is open\n", port_no);
        else
            printf("Port : %s is closed\n", port_no);
    }
}

Body:
If you're only trying to check TCP ports and not UDP, I would recommend simply trying to connect() to the server and wait a certain amount of time before you assume that port is closed.

You'll have to use poll() or select() in order to timeout the connect() call.
(C: socket connection timeout)

Here's a working example:
(works only with IPs, not domain name so you'd have to ping the server in order to find out its IP address or implement the dns query yourself)

#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>

#define MAX_PORT 1024
#define TIMEOUT 5000

int main(int argc, char *argv[])
{
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = inet_addr(argv[1])
    };
    struct pollfd fds[1];

    for (uint16_t port = 0; port < MAX_PORT; port++) {
        int8_t sock = socket(PF_INET, SOCK_STREAM, 0);
        fcntl(sock, F_SETFL, O_NONBLOCK);
        fds[0].fd = sock;
        fds[0].events = POLLOUT;
        addr.sin_port = htons(port);

        if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
            if (errno == EINPROGRESS) {
                if (poll(fds, 1, TIMEOUT) > 0)
                    printf("Port %d opened.\n", port);
                else
                    printf("Port %d closed.\n", port);
            }
            else
                printf("Port %d closed.\n", port);
        }
        else
            printf("Port %d opened.\n", port);
        close(sock);
    }
}


来源: stackexchange

问:
Trading View has a Divergence Indicator that I'd like information how how to use the Alerts effectively
I am not a coder.

I'd like to use the basic, locked, TView indicator Alerts to notifications when a Bull / Bear flag appears from the "Divergence Indicator". It doesn't have a script author to ask. Can this Alert be done with the script and coding that already exists? How?

If not, How much would it be to code something like this?

答:
You can configure alerts using the indicator without any changes to it, provided you are happy with the possibilities it provides as is. Here, we have configured an alert on its Regular Bullish plot which shows a non-zero value when a bullish divergence occurs.

Use the Data Window and inspect bars, as we are doing here, to see which plots activate when your conditions occur.

ContentLicense: CC BY-SA 4.0


问:
mysql_connect(): No connection could be made because the target machine actively refused it
I have this problem when I am trying to run my PHP MySQL script. When I try to run my .php file this is what I get.

```<code>mysql_connect(): No connection could be made because the target machine actively refused it
</code>```

This is code for dbconnect.php:

```<code><?php
mysql_connect("localhost","root");
mysql_select_db("users");
?>
</code>```

I tried to use this format before but I don't know what seems to be the problem with this code.

Thank you in advance.

答: Changing "mysql://username:password@/databasename" to "mysql://username:password@localhost/databasename" fixed the issue for me. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have this problem when I am trying to run my PHP MySQL script. When I try to run my .php file this is what I get.

mysql_connect(): No connection could be made because the target machine actively refused it

This is code for dbconnect.php:

<?php
mysql_connect("localhost","root");
mysql_select_db("users");
?>

I tried to use this format before but I don't know what seems to be the problem with this code.

Thank you in advance.


问:
Fluid and fixed web page
Is there any way to create a page, using only valid html and css code, that would allow the page to be fluid (shrink and grow via browser window size), but also not allow any of the data (abbreviated/overflow/etc) to be lost on the page? See the attached image to see what I'm talking about. Thanks in advance.

css table example

答:
You can use Bootstrap, it is pretty simple to learn
https://getbootstrap.com/docs/4.0/layout/grid/</p>

Title: Fluid and fixed web page


问:
How to add a 'X' to the end of every line in C?
I'm trying to append a capital 'X' character at the end of every line of a simple text file (while switching all chars to upper case at the same time) and writing the changes to a new file.

So initially, the file faust.txt contains:

```<code>Besonders aber laßt genug geschehn!
Man kommt zu schaun, man will am liebsten sehn.
Wird vieles vor den Augen abgesponnen,
</code>```

After the call, the file FAUST.txt should contain:

```<code>BESONDERS ABER LAßT GENUG GESCHEHN!X
MAN KOMMT ZU SCHAUN, MAN WILL AM LIEBSTEN SEHN.X
WIRD VIELES VOR DEN AUGEN ABGESPONNEN,X
</code>```

The copying and conversion to upper case seems to work but the appending is unclear to me:

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read_bytes > 0) {

        char c = src[0];
        char *C = &c;
        src[0] = toupper(*C);

        if (src[0] == '\n') {
            char *end = &src[0];
            strcat(end, "X");
            src[0] = *end;
        }

        write(FAUST_fh, &src, BUF_SIZE);
        read_bytes = read(faust_fh, src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}
</code>```

Note: I should accomplish this with system calls (if possible).

答:
You're causing undefined behavior when you call strcat(end, "X"); because end points to src, and src doesn't have a null terminator and doesn't have enough bytes allocated to concatenate anything.

If you're reading the file one byte at a time, you don't need an array. Just read into a char variable. When the character is a newline, write an X to the output file before writing the character.

Another problem: when you call open() to create the output file, you have to pass a third argument containing the desired file permissions.

```<code>#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src;

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY, 0644);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read(faust_fh, &src, BUF_SIZE) > 0) {
        src = toupper(src);
        if (src == '\n') {
            write(FAUST_fh, "X", 1);
        }
        write(FAUST_fh, &src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}
</code>```

Body:
I'm trying to append a capital 'X' character at the end of every line of a simple text file (while switching all chars to upper case at the same time) and writing the changes to a new file.

So initially, the file faust.txt contains:

Besonders aber laßt genug geschehn!
Man kommt zu schaun, man will am liebsten sehn.
Wird vieles vor den Augen abgesponnen,

After the call, the file FAUST.txt should contain:

BESONDERS ABER LAßT GENUG GESCHEHN!X
MAN KOMMT ZU SCHAUN, MAN WILL AM LIEBSTEN SEHN.X
WIRD VIELES VOR DEN AUGEN ABGESPONNEN,X

The copying and conversion to upper case seems to work but the appending is unclear to me:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read_bytes > 0) {

        char c = src[0];
        char *C = &c;
        src[0] = toupper(*C);

        if (src[0] == '\n') {
            char *end = &src[0];
            strcat(end, "X");
            src[0] = *end;
        }

        write(FAUST_fh, &src, BUF_SIZE);
        read_bytes = read(faust_fh, src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}

Note: I should accomplish this with system calls (if possible).

Body:
You're causing undefined behavior when you call strcat(end, "X"); because end points to src, and src doesn't have a null terminator and doesn't have enough bytes allocated to concatenate anything.

If you're reading the file one byte at a time, you don't need an array. Just read into a char variable. When the character is a newline, write an X to the output file before writing the character.

Another problem: when you call open() to create the output file, you have to pass a third argument containing the desired file permissions.

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src;

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY, 0644);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read(faust_fh, &src, BUF_SIZE) > 0) {
        src = toupper(src);
        if (src == '\n') {
            write(FAUST_fh, "X", 1);
        }
        write(FAUST_fh, &src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}


问:
localhost redirects to a different page
I am experiencing a problem with my Spring Boot project. When I run the application and go to http://localhost:8086/ it redirects to http://localhost:8086/login which is not the page I want.

This is the content of my application.properties file

```<code>#Database
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#Html
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html

#Server
server.port=8086
</code>```

I have also added this class which is supposed to open the index.html file found in the /public/ folder as specified in the properties above

```<code>public class WebAppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
    }

}
</code>```

Is there something that I am doing wrong or should I log in first in the page that it redirects to?

答: Hopefully Here you can find your answer, basically it's in the configuration</p>

Title: localhost redirects to a different page

Body:
I am experiencing a problem with my Spring Boot project. When I run the application and go to http://localhost:8086/ it redirects to http://localhost:8086/login which is not the page I want.

This is the content of my application.properties file

#Database
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#Html
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html

#Server
server.port=8086

I have also added this class which is supposed to open the index.html file found in the /public/ folder as specified in the properties above

public class WebAppConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
    }

}

Is there something that I am doing wrong or should I log in first in the page that it redirects to?


问:
Is it possible to get the DOM Attr for an attribute using JAXB?
We're using JAXB to unmarshall a fragment of XML which looks a bit like this:

```<code><someRandomElement xmlns:foo="http://example.com/foo" xpath="//foo:bar" />
</code>```

Our object model is:

```<code>@XmlRootElement(name="someRandomElement")
class SomeRandomClass {

    @XmlAttribute(name="xpath")
    private XPathFragment _expression;
}

class XPathFragment {
    String _expr;

    // we need this to look up namespace prefixes used in _expr
    Node _parentNode;
}
</code>```

So my question is, how can I unmarshall the XPathFragment from the XML using JAXB?

I have tried using a custom XmlAdapter for XPathFragment, but this doesn't seem to have an opportunity to access the DOM Nodes corresponding to the someRandomElement and its attributes.

答:
For JAXB RI:

Write a custom XmlAdapter for your XPathFragment. You can access the current namespace context during unmarshalling via UnmarshallingContext.getInstance(). See how QName handling is implemented (check implementations of com.sun.xml.bind.v2.model.runtime.RuntimeBuiltinLeafInfo). Parsing of QName also needs namespace resolution, just like you XPathFragment case.

Body:
We're using JAXB to unmarshall a fragment of XML which looks a bit like this:

<someRandomElement xmlns:foo="http://example.com/foo" xpath="//foo:bar" />

Our object model is:

@XmlRootElement(name="someRandomElement")
class SomeRandomClass {

    @XmlAttribute(name="xpath")
    private XPathFragment _expression;
}

class XPathFragment {
    String _expr;

    // we need this to look up namespace prefixes used in _expr
    Node _parentNode;
}

So my question is, how can I unmarshall the XPathFragment from the XML using JAXB?

I have tried using a custom XmlAdapter for XPathFragment, but this doesn't seem to have an opportunity to access the DOM Nodes corresponding to the someRandomElement and its attributes.


问:
Avoid mutating a prop directly since the value will be overwritten
I have very common problem with upgrading to Vue 2.0

I am getting warning:

Avoid mutating a prop directly since the value will be overwritten
  whenever the parent component re-renders. Instead, use a data or
  computed property based on the prop's value. Prop being mutated:
  "username"  (found in the component )

I read the documentation many times but I still can't understand how to fix it.

username and password are declared in the main Vue app.

Here is my code:

```<code>var GuestMenu = Vue.extend({
   props : ['username', 'password'],
      template: `
        <div id="auth">
            <form class="form-inline pull-right">
                <div class="form-group">
                    <label class="sr-only" for="UserName">User name</label>
                  <input type="username" v-model="username" class="form-control" id="UserName" placeholder="username">
                </div>
                <div class="form-group">
                  <label class="sr-only" for="Password">Password</label>
                  <input type="password" v-model="password" class="form-control" id="Password" placeholder="Password">
                </div>
            </form>
        </div>`,
    });
</code>```

```<code>App = new Vue ({
   el: '#app',
  data:
    {
      topMenuView: "guestmenu",
      contentView: "guestcontent",
      username: "",
      password: "",

    }
})
</code>```

I tried v-bind but it does not seem to work, and I can't understand why. It should bind the value to parent (the main Vue app)

答:
```<code>var GuestMenu = Vue.extend({
   props : {
    uNpW:{type:Object}
   }
      template: `
        <div id="auth">
            <form class="form-inline pull-right">
                <div class="form-group">
                    <label class="sr-only" for="UserName">User name</label>
                  <input type="username" v-model="uNpW.username" class="form-control" id="UserName" placeholder="username">
                </div>
                <div class="form-group">
                  <label class="sr-only" for="Password">Password</label>
                  <input type="password" v-model="uNpW.password" class="form-control" id="Password" placeholder="Password">
                </div>
            </form>
        </div>`,
    });
</code>```

```<code>App = new Vue ({
   el: '#app',
  data:
    {
      topMenuView: "guestmenu",
      contentView: "guestcontent",
      unAndPw:{username: "",password: ""}

    }
})
</code>```

```<code>in main html
<guest-menu :uNpW=unAndPw> </guest-menu>
</code>```

you dont need emit or any other thing

Body:
I have very common problem with upgrading to Vue 2.0

I am getting warning:

Avoid mutating a prop directly since the value will be overwritten
  whenever the parent component re-renders. Instead, use a data or
  computed property based on the prop's value. Prop being mutated:
  "username"  (found in the component )

I read the documentation many times but I still can't understand how to fix it.

username and password are declared in the main Vue app.

Here is my code:

var GuestMenu = Vue.extend({
   props : ['username', 'password'],
      template: `

            <form class="form-inline pull-right">

                    User name
                  <input type="username" v-model="username" class="form-control" id="UserName" placeholder="username">

                  Password
                  <input type="password" v-model="password" class="form-control" id="Password" placeholder="Password">

            </form>

`,
    });

App = new Vue ({
   el: '#app',
  data:
    {
      topMenuView: "guestmenu",
      contentView: "guestcontent",
      username: "",
      password: "",

    }
})

I tried v-bind but it does not seem to work, and I can't understand why. It should bind the value to parent (the main Vue app)

Body:
var GuestMenu = Vue.extend({
   props : {
    uNpW:{type:Object}
   }
      template: `
        <div id="auth">
            <form class="form-inline pull-right">
                <div class="form-group">
                    <label class="sr-only" for="UserName">User name</label>
                  <input type="username" v-model="uNpW.username" class="form-control" id="UserName" placeholder="username">
                </div>
                <div class="form-group">
                  <label class="sr-only" for="Password">Password</label>
                  <input type="password" v-model="uNpW.password" class="form-control" id="Password" placeholder="Password">
                </div>
            </form>
        </div>`,
    });

App = new Vue ({
   el: '#app',
  data:
    {
      topMenuView: "guestmenu",
      contentView: "guestcontent",
      unAndPw:{username: "",password: ""}

    }
})

in main html
<guest-menu :uNpW=unAndPw> </guest-menu>

you dont need emit or any other thing


问:
Windows Equivalent for package.json script commands
I am using parcel and want to clean the .cache folder and also to run React frontend on 3000 while also running backend on 1234. these are my start scripts.

```<code>"scripts": {
    "test": "jest --watchAll",
    "start": "npm run build-client && node index.js",
    "dev": "npm run dev-client & nodemon index.js",
    "dev-peer": "cross-env GENERATE_PEER_PORT='true' nodemon index.js",
    "build-client": "npm run clean && parcel build client/src/index.html --out-dir client/dist",
    "dev-client": "npm run clean && parcel client/src/index.html --out-dir client/dist",
    "clean": "rmdir /s/q .cache client/dist"
  },
</code>```

I have already put the windows commands on the 'clean' script with rmdir /s/q but get

Invalid switch - "dist".
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ajax27-blockchain@1.0.0 clean: `rmdir /s/q .cache client/dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ajax27-blockchain@1.0.0 clean script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shaun\AppData\Roaming\npm-cache\_logs\2019-07-09T11_49_08_194Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ajax27-blockchain@1.0.0 dev-client: `npm run clean && parcel client/src/index.html --out-dir client/dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ajax27-blockchain@1.0.0 dev-client script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shaun\AppData\Roaming\npm-cache\_logs\2019-07-09T11_49_08_223Z-debug.log
```

答: You can alternatively use rimraf npm module and it works well with windows as well.</p>

Body:
I am using parcel and want to clean the .cache folder and also to run React frontend on 3000 while also running backend on 1234. these are my start scripts.

"scripts": {
    "test": "jest --watchAll",
    "start": "npm run build-client && node index.js",
    "dev": "npm run dev-client & nodemon index.js",
    "dev-peer": "cross-env GENERATE_PEER_PORT='true' nodemon index.js",
    "build-client": "npm run clean && parcel build client/src/index.html --out-dir client/dist",
    "dev-client": "npm run clean && parcel client/src/index.html --out-dir client/dist",
    "clean": "rmdir /s/q .cache client/dist"
  },

I have already put the windows commands on the 'clean' script with rmdir /s/q but get

Invalid switch - "dist".
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ajax27-blockchain@1.0.0 clean: `rmdir /s/q .cache client/dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ajax27-blockchain@1.0.0 clean script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shaun\AppData\Roaming\npm-cache\_logs\2019-07-09T11_49_08_194Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! ajax27-blockchain@1.0.0 dev-client: `npm run clean && parcel client/src/index.html --out-dir client/dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ajax27-blockchain@1.0.0 dev-client script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\shaun\AppData\Roaming\npm-cache\_logs\2019-07-09T11_49_08_223Z-debug.log


问:
Update XML file with C#
I have a xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns="http://test.org/SDK/Configuration.xsd">
    <ApplicationName>
        <ApplicationUri>123</ApplicationUri>
        <ApplicationUri>456</ApplicationUri>
    </ApplicationName>
</ApplicationConfiguration>
</code>```

What I want is set the value of ApplicationUri from 456 to 789 in C# code.

I wrote this code:

```<code>string docaddress = "testfile.xml";

XDocument doc = XDocument.Load(docaddress);
doc.Element("ApplicationConfiguration")
            .Elements("ApplicationName").FirstOrDefault()
            .SetElementValue("ApplicationUri", "789");
doc.Save(docaddress);
</code>```

The problems are:

There is no error while running. I think the element ApplicationConfiguration is not correct. But when I delete the line xmlns=... from the xml file, it runs normally

The value 789 is replaced with 123, but not 456 as I want (same element name)

Can you tell me how to fix those problems?

答:
Hello and welcome to Stack Overflow!

The xmlns attribute on the ApplicationConfiguration element makes that the root.
So you get the root first. Then you replace the values of each descendant, selecting locally by name with the element name you want. something like this:

```<code> string docaddress = "C:\\temp\\testfile.xml";
        XDocument doc = XDocument.Load(docaddress);
        var root = doc.Root;
        var descendants = root.Descendants();
        var these = root.Descendants().Where(p => p.Name.LocalName == "ApplicationUri");
        foreach (var elem in these)
        {
            elem.Value = "789";

        }
        doc.Save(docaddress);
</code>```

Title: Update XML file with C#

Body:
I have a xml file:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration xmlns="http://test.org/SDK/Configuration.xsd">
    <ApplicationName>
        <ApplicationUri>123</ApplicationUri>
        <ApplicationUri>456</ApplicationUri>
    </ApplicationName>
</ApplicationConfiguration>

What I want is set the value of ApplicationUri from 456 to 789 in C# code.

I wrote this code:

string docaddress = "testfile.xml";

XDocument doc = XDocument.Load(docaddress);
doc.Element("ApplicationConfiguration")
            .Elements("ApplicationName").FirstOrDefault()
            .SetElementValue("ApplicationUri", "789");
doc.Save(docaddress);

The problems are:

There is no error while running. I think the element ApplicationConfiguration is not correct. But when I delete the line xmlns=... from the xml file, it runs normally

The value 789 is replaced with 123, but not 456 as I want (same element name)

Can you tell me how to fix those problems?

Body:
Hello and welcome to Stack Overflow!

The xmlns attribute on the ApplicationConfiguration element makes that the root.
So you get the root first. Then you replace the values of each descendant, selecting locally by name with the element name you want. something like this:

 string docaddress = "C:\\temp\\testfile.xml";
        XDocument doc = XDocument.Load(docaddress);
        var root = doc.Root;
        var descendants = root.Descendants();
        var these = root.Descendants().Where(p => p.Name.LocalName == "ApplicationUri");
        foreach (var elem in these)
        {
            elem.Value = "789";

        }
        doc.Save(docaddress);


问:
is it possible to explain why this returns 21
Hello this isn't an assignment or anything but can you explain why this returns 2 1.</p>
```<code>#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}
</code>```

答:
fun() is a non tail recursion call and base condition is n<2 then
fun will call twice fun(0) &fun(1). As recursion activation record maintain on stack then while reaching at base condition it will print

2 1
Cout "2"
Cout "1"

I will recommend please go through recursion concept thoroughly.

Body:
Hello this isn't an assignment or anything but can you explain why this returns 2 1.

#include <string>
using namespace std;
void fun(int);
int main()
{
    int a = 0;
    fun(a);
    return 0;
}

void fun(int n)
{
    if (n < 2)
    {
        fun(++n);
        cout << n<<" ";
    }
}


问:
How to select and apply styling to custom tags
I'm trying to change a background color of a single table header, the problem is that there is no unique id. There is a unique/costum tag but I can't find a way to select it.

The element looks like this

```

<p>If i select</p>

<pre class="lang-css prettyprint-override"><code>.ag-header-cell.ag-header-cell-sortable {
  background-color: #56CC2B;
}
</code>```

It prints all columns headers. I'd like to select the col-id="name" is that even possible? Here is the page example.

答:
You can do it using attribute selector.

```<code>[col-id="name"]
</code>```

[col-id="name"] {
     background-color: #56CC2B;
     height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div
  class="ag-grid-header-cell ag-header-cell-sortable"
  role="presentation"
  unselectable="on"
  col-id="name"
  style="width:180px;left:500px;"
></code>```

Here i add hide so that the effect can visible.

Body:
I'm trying to change a background color of a single table header, the problem is that there is no unique id. There is a unique/costum tag but I can't find a way to select it.

The element looks like this

If i select

.ag-header-cell.ag-header-cell-sortable {
  background-color: #56CC2B;
}

It prints all columns headers. I'd like to select the col-id="name" is that even possible? Here is the page example.

Body:
You can do it using attribute selector.

[col-id="name"]

[col-id="name"] {
     background-color: #56CC2B;
     height: 500px;
}

<div
  class="ag-grid-header-cell ag-header-cell-sortable"
  role="presentation"
  unselectable="on"
  col-id="name"
  style="width:180px;left:500px;"
>

Here i add hide so that the effect can visible.


问:
android studio recyclerview firebase not showing data
l am try to build Android book store project using Firebase Database and recyclerview to display my data . But the problem is when i run my app i have empty activity without any error .

RecyclerViewActivity java:

```<code>package sky.ex.ai.booksstore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class RecyclerViewActivity extends AppCompatActivity {

    RecyclerView rviwe;
    ArrayList<BookDetails> plist;
    ItemAdapter itemAdapter;
    FirebaseDatabase fb;
    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        rviwe = findViewById(R.id.recycler_view);
        plist = new ArrayList<BookDetails>();
        fb = FirebaseDatabase.getInstance();
        ref = fb.getReference("Library");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){

                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));

                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
        LinearLayoutManager im = new LinearLayoutManager((this));
        rviwe.setLayoutManager(im);
        itemAdapter = new ItemAdapter(plist);
        rviwe.setAdapter(itemAdapter);

    }
}
</code>```

activity_recycler_view xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerViewActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Item layout xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="138dp"
        android:layout_height="59dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/book" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="10dp">

        <TextView
            android:id="@+id/book_name_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book name" />

        <TextView
            android:id="@+id/book_author_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book Author" />

        <TextView
            android:id="@+id/book_price_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book price" />
    </LinearLayout>
</LinearLayout>
</code>```

Book Details Class

```<code>package sky.ex.ai.booksstore;

    public class BookDetails {

       String bkAuthor;
       String bkname;

        public BookDetails() {
        }

       public BookDetails(String bkname, String bkAuthor){
           this.bkAuthor = bkAuthor;
           this.bkname = bkname;
       }

        public String getBkAuthor() {
            return bkAuthor;
        }

        public void setBkAuthor(String bkAuthor) {
            this.bkAuthor = bkAuthor;
        }

        public String getBkname() {
            return bkname;
        }

        public void setBkname(String bkname) {
            this.bkname = bkname;
        }
    }
</code>```

Item Adapter java

```<code>package sky.ex.ai.booksstore
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    public ArrayList<BookDetails> itemlist;

    public ItemAdapter(ArrayList<BookDetails> itemlist) {
        this.itemlist = itemlist;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater
                .from(viewGroup.getContext()).inflate(R.layout.item_layot,viewGroup, false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
        holder.txt_pname.setText("Book Name :" +itemlist.get(i).bkname);
        holder.txt_pid.setText("Book Author :" +itemlist.get(i).bkAuthor);
    }

    @Override
    public int getItemCount() {
        if (itemlist==null)
            return 0;
        else  return itemlist.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public ImageButton imgb1;
        public TextView txt_pid,txt_pname,txt_pric;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_pid = itemView.findViewById(R.id.book_name_list);
            txt_pname = itemView.findViewById(R.id.book_author_list);
        }
    }

}
</code>```

Database structure

any idea please ?

答:
Since you are calling an asynchronous method. The adapter is being set with empty plist. You need to set items inside the callback method onDataChange, then call notifyDatasetChanged on the adapter to notify it availability of new data. Might need to fix some compiler complaints but this should get you close.</p>

```<code>ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){
                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));
                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
                LinearLayoutManager im = new LinearLayoutManager((RecyclerViewActivity.this));
                rviwe.setLayoutManager(im);
                itemAdapter = new ItemAdapter(plist);
                rviwe.setAdapter(itemAdapter);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
</code>```

Body:
l am try to build Android book store project using Firebase Database and recyclerview to display my data . But the problem is when i run my app i have empty activity without any error .

RecyclerViewActivity java:

package sky.ex.ai.booksstore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class RecyclerViewActivity extends AppCompatActivity {

    RecyclerView rviwe;
    ArrayList<BookDetails> plist;
    ItemAdapter itemAdapter;
    FirebaseDatabase fb;
    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        rviwe = findViewById(R.id.recycler_view);
        plist = new ArrayList<BookDetails>();
        fb = FirebaseDatabase.getInstance();
        ref = fb.getReference("Library");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){

                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));

                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
        LinearLayoutManager im = new LinearLayoutManager((this));
        rviwe.setLayoutManager(im);
        itemAdapter = new ItemAdapter(plist);
        rviwe.setAdapter(itemAdapter);

    }
}

activity_recycler_view xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerViewActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Item layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="138dp"
        android:layout_height="59dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/book" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="10dp">

        <TextView
            android:id="@+id/book_name_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book name" />

        <TextView
            android:id="@+id/book_author_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book Author" />

        <TextView
            android:id="@+id/book_price_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book price" />
    </LinearLayout>
</LinearLayout>

Book Details Class

package sky.ex.ai.booksstore;

    public class BookDetails {

       String bkAuthor;
       String bkname;

        public BookDetails() {
        }

       public BookDetails(String bkname, String bkAuthor){
           this.bkAuthor = bkAuthor;
           this.bkname = bkname;
       }

        public String getBkAuthor() {
            return bkAuthor;
        }

        public void setBkAuthor(String bkAuthor) {
            this.bkAuthor = bkAuthor;
        }

        public String getBkname() {
            return bkname;
        }

        public void setBkname(String bkname) {
            this.bkname = bkname;
        }
    }

Item Adapter java

package sky.ex.ai.booksstore
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    public ArrayList<BookDetails> itemlist;

    public ItemAdapter(ArrayList<BookDetails> itemlist) {
        this.itemlist = itemlist;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater
                .from(viewGroup.getContext()).inflate(R.layout.item_layot,viewGroup, false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
        holder.txt_pname.setText("Book Name :" +itemlist.get(i).bkname);
        holder.txt_pid.setText("Book Author :" +itemlist.get(i).bkAuthor);
    }

    @Override
    public int getItemCount() {
        if (itemlist==null)
            return 0;
        else  return itemlist.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public ImageButton imgb1;
        public TextView txt_pid,txt_pname,txt_pric;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_pid = itemView.findViewById(R.id.book_name_list);
            txt_pname = itemView.findViewById(R.id.book_author_list);
        }
    }

}

Database structure

any idea please ?

Body:
Since you are calling an asynchronous method. The adapter is being set with empty plist. You need to set items inside the callback method onDataChange, then call notifyDatasetChanged on the adapter to notify it availability of new data. Might need to fix some compiler complaints but this should get you close.

ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){
                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));
                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
                LinearLayoutManager im = new LinearLayoutManager((RecyclerViewActivity.this));
                rviwe.setLayoutManager(im);
                itemAdapter = new ItemAdapter(plist);
                rviwe.setAdapter(itemAdapter);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });


问:
Protected Route and React Context
I have a context (AuthContext) which lets me know whether the user is authenticated or not. I had also created a protected route which lets me log onto DashBoard if the user is authenticated otherwise redirects to login. I am however having a problem connecting those two so that it happens together.

ProtectedRoute.js

```<code>import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from './AuthContext';

const ProtectedRoute = ({ component: Component, ...rest }) => {
  return (
    <AuthContext.Consumer>
      {(context) => {
        const { isAuthenticated } = this.context;

        return (
          <Route
            {...rest}
            render={(props) => {
              const { isAuthenticated } = this.context; //getting an error here
              if (isAuthenticated) {
                return <Component {...props} />;
              } else {
                return (
                  <Redirect
                    to={{
                      pathname: '/',
                      state: {
                        from: props.location,
                      },
                    }}
                  />
                );
              }
            }}
          />
        );
      }}
    </AuthContext.Consumer>
  );
};

export default ProtectedRoute;
</code>```

AuthContext.js

```<code>import React, { Component, createContext } from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
  state = {
    isAuthenticated: false,
  };
  toggleAuth = () => {
    this.setState({ isAuthenticated: !this.state.isAuthenticated });
  };

  render() {
    return (
      <AuthContext.Provider
        value={{ ...this.state, toggleAuth: this.toggleAuth }}>
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}

export default AuthContextProvider;
</code>```

Edited code (getting an error saying render is not a function)

```<code>import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthContext } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => {

    return (
        <AuthContext.Consumer>
            {({context}) => (
                <Route
                    {...rest}
                    render={(props) => {
                    const {isAuthenticated} = context;
                        if(isAuthenticated) {
                            return <Component {...props} />;
                        } else {
                            return (
                                <Redirect
                                to={{
                                    pathname: "/",
                                    state: {
                                        from: props.location
                                    }
                                }}
                                />
                            );
                         }
                    }}
                />
            )};
        </AuthContext.Consumer>
    )
}

export default ProtectedRoute
</code>```

答:
The argument provided to the context consumer function is the value prop in the corresponding provider.

  return (
    <AuthContext.Consumer>
      {(context) => (
        <Route
          {...rest}
          render={(props) => {
            const { isAuthenticated } = context; // no `this`
            // ...
          }}
        />
      )}
    </AuthContext.Consumer>
  );
```

I noticed that in your original code there are some syntax errors:

You need to enclose the body of the consumer function in braces if you're using return.

Since the consumer function is a child of the consumer element, you need to provide a closing tag.

Title: Protected Route and React Context

Body:
I have a context (AuthContext) which lets me know whether the user is authenticated or not. I had also created a protected route which lets me log onto DashBoard if the user is authenticated otherwise redirects to login. I am however having a problem connecting those two so that it happens together.

ProtectedRoute.js

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { AuthContext } from './AuthContext';

const ProtectedRoute = ({ component: Component, ...rest }) => {
  return (
    <AuthContext.Consumer>
      {(context) => {
        const { isAuthenticated } = this.context;

        return (
          <Route
            {...rest}
            render={(props) => {
              const { isAuthenticated } = this.context; //getting an error here
              if (isAuthenticated) {
                return <Component {...props} />;
              } else {
                return (
                  <Redirect
                    to={{
                      pathname: '/',
                      state: {
                        from: props.location,
                      },
                    }}
                  />
                );
              }
            }}
          />
        );
      }}
    </AuthContext.Consumer>
  );
};

export default ProtectedRoute;

AuthContext.js

import React, { Component, createContext } from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
  state = {
    isAuthenticated: false,
  };
  toggleAuth = () => {
    this.setState({ isAuthenticated: !this.state.isAuthenticated });
  };

  render() {
    return (
      <AuthContext.Provider
        value={{ ...this.state, toggleAuth: this.toggleAuth }}>
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}

export default AuthContextProvider;

Edited code (getting an error saying render is not a function)

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthContext } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => {

    return (
        <AuthContext.Consumer>
            {({context}) => (
                <Route
                    {...rest}
                    render={(props) => {
                    const {isAuthenticated} = context;
                        if(isAuthenticated) {
                            return <Component {...props} />;
                        } else {
                            return (
                                <Redirect
                                to={{
                                    pathname: "/",
                                    state: {
                                        from: props.location
                                    }
                                }}
                                />
                            );
                         }
                    }}
                />
            )};
        </AuthContext.Consumer>
    )
}

export default ProtectedRoute

Body:
The argument provided to the context consumer function is the value prop in the corresponding provider.

  return (
    <AuthContext.Consumer>
      {(context) => (
        <Route
          {...rest}
          render={(props) => {
            const { isAuthenticated } = context; // no `this`
            // ...
          }}
        />
      )}
    </AuthContext.Consumer>
  );

I noticed that in your original code there are some syntax errors:

You need to enclose the body of the consumer function in braces if you're using return.

Since the consumer function is a child of the consumer element, you need to provide a closing tag.


问:
Create if not exist PostgresSql
i have managed to write a line that says locate certain user by email and assign a role. Just wondering if there is a way to say create if not exist and specify a couple if users</p>

```<code>Create if not exist ->

<sql>
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘test@gmai.com’
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘tes1t@gmai.com’
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘test2@gmai.com’
</sql>
</code>```

答:
You could use the insert ... on conflict syntax. For this to work, you need a unique or primary key constraint on column email. If it does not yet exist, you can create it as follows:

```<code>alter table users add constraint users_unique_email unique(email);
</code>```

Then you can do:

```<code>insert into users (email, role)
values(
    ('test@gmai.com',  'ROLE_ADMIN'),
    ('test1@gmai.com', 'ROLE_ADMIN'),
    ('test2@gmai.com', 'ROLE_ADMIN')
)
on conflict(email) do update set role = excluded.role
</code>```

Title: Create if not exist PostgresSql

Body:
i have managed to write a line that says locate certain user by email and assign a role. Just wondering if there is a way to say create if not exist and specify a couple if users

Create if not exist ->

<sql>
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘test@gmai.com’
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘tes1t@gmai.com’
 UPDATE USERS SET ROLE = ‘ROLE_ADMIN’ WHERE EMAIL = ‘test2@gmai.com’
</sql>

Body:
You could use the insert ... on conflict syntax. For this to work, you need a unique or primary key constraint on column email. If it does not yet exist, you can create it as follows:

alter table users add constraint users_unique_email unique(email);

Then you can do:

insert into users (email, role)
values(
    ('test@gmai.com',  'ROLE_ADMIN'),
    ('test1@gmai.com', 'ROLE_ADMIN'),
    ('test2@gmai.com', 'ROLE_ADMIN')
)
on conflict(email) do update set role = excluded.role


问:
AWS Cognito Hosted UI -- How to use the returned JWT token?
I am using Amazon Cognito and its hosted UI to help create a web application.  I am able to use to log in using the hosted UI and the redirect link successfully points me to where I want it to go.  I also recieve a correctly formatted JWT token on redirect.

I've also successfully parsed that JWT token into a JS object and am able to verify its validity.  With the correct username, expiration time, issue time, etc., etc.

The problem I'm having now is that I simply don't know where to go from here.  Is the fact that I have that JWT enough to continue on and assume that the user is valid?  If I want to be able to persist the user across different webpages on the site, is it safe to store the JWT -- or, at least, parts of it -- in session storage and act as if that is valid user?

If not, then what am I supposed to do next with the JWT?  I have looked through many of the various articles on using the JWT with Cognito and they all seem to be about decoding the JWT, but not about what I'm supposed to do with the JWT once I have it decoded.
 For context, all I am really trying to get from the JWT is the correct user name, I am planning on storing a lot of other important user details elsewhere.

I'm sorry if there is something very obvious I'm missing about where to go next, but I'm very new to all this AWS stuff and a lot the of documentation is confusing, and not beginner friendly.  Thank you for your time, any help at all is greatly appreciated.

EDIT: I wanted to include that I am writing the log in / verification / redirect code on vanilla, client-side javascript.  I am using the standard aws SDK, the aws-cognito SDK, and the amazon-cognito-identity SDK.  My imports look like this:

```<code>   <script src="https://sdk.amazonaws.com/js/aws-sdk-2.686.0.min.js"</script>
   <script src="../../aws-cognito/dist/amazon-cognito-auth.min.js" type="text/javascript"></script>
   <script src="../../amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js"></script>
</code>```

答:
my advise for you would be to look into the AWS Client Side SDK which handle the storing, refreshing and other nice functionality for you.

https://docs.amplify.aws/start/q/integration/js - Main Client side SDK.

https://github.com/amazon-archives/amazon-cognito-auth-js - older SDK used for Cognito Oauth endpoints/ Hosted UI.

Both SDK's will store the result from your HostedUI authentication is local storage in the browser. There you can check if the tokens are valid and even access them if you require to send them to an authorized resource server.

This of course can all be implemented without the use of those SDK's but they help and can give you poinnters. Additionally, the AWS SDK and Cognito identity SDK do not have any functionality that will help you integrate with the HostedUI and Oauth endpoints. That can be done using the SDK's provided above.


问:
error : C2664 'void RecursiveDelete(LPWSTR,LPWSTR)': cannot convert argument 2 from 'const wchar_t [12]' to 'LPWSTR'
Any Idea how to fix? Would be really useful. I tried changing conformance mode to off and it worked but the other parts of the program failed. Any other fixes?

Line that has problem :

```<code>RecursiveDelete(path, L"desktop.ini");
</code>```

Edit :

The program is to change windows registry files and is connected with my c++ loader. When the project is standalone not connected to the loader it works perfectly fine.

答:
The RecursiveDelete() function takes 2 LPWSTR parameters.  LPWSTR is an alias for wchar_t*, ie a pointer to non-const wchar_t data.  However, a string literal is const data, in this case L"desktop.ini" is a const wchar_t[12] (including the null terminator), which decays into a const wchar_t* pointer.  You can't use a pointer-to-const where a pointer-to-non-const is expected, that is what the error message is complaining about.

IF the function DOES NOT alter the contents of its second parameter, then that parameter should be implemented as a pointer-to-const, eg:

```<code>void RecursiveDelete(LPWSTR, LPCWSTR);
</code>```

(aka void RecursiveDelete(wchar_t*, const wchar_t*);).

If changing the declaration of the function is not an option (ie, it is from an existing API, etc), you could instead cast away the string literal's constness using const_cast (be VERY CAREFUL doing this!), eg:

```<code>RecursiveDelete(path, const_cast<LPWSTR>(L"desktop.ini"));
</code>```

However, making a non-const duplicate of the string literal's data would be much safer, eg:

```<code>wchar_t copy[] = L"desktop.ini";
RecursiveDelete(path, copy);
</code>```

Body:
Any Idea how to fix? Would be really useful. I tried changing conformance mode to off and it worked but the other parts of the program failed. Any other fixes?

Line that has problem :

RecursiveDelete(path, L"desktop.ini");

Edit :

The program is to change windows registry files and is connected with my c++ loader. When the project is standalone not connected to the loader it works perfectly fine.

Body:
The RecursiveDelete() function takes 2 LPWSTR parameters.  LPWSTR is an alias for wchar_t*, ie a pointer to non-const wchar_t data.  However, a string literal is const data, in this case L"desktop.ini" is a const wchar_t[12] (including the null terminator), which decays into a const wchar_t* pointer.  You can't use a pointer-to-const where a pointer-to-non-const is expected, that is what the error message is complaining about.

IF the function DOES NOT alter the contents of its second parameter, then that parameter should be implemented as a pointer-to-const, eg:

void RecursiveDelete(LPWSTR, LPCWSTR);

(aka void RecursiveDelete(wchar_t*, const wchar_t*);).

If changing the declaration of the function is not an option (ie, it is from an existing API, etc), you could instead cast away the string literal's constness using const_cast (be VERY CAREFUL doing this!), eg:

RecursiveDelete(path, const_cast<LPWSTR>(L"desktop.ini"));

However, making a non-const duplicate of the string literal's data would be much safer, eg:

wchar_t copy[] = L"desktop.ini";
RecursiveDelete(path, copy);


问:
Why does modifier order matter in SwiftUI?
When applying modifiers to a view in SwiftUI, it appears that the order matters.

For example, this code:

HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}
```

<p>..will produce this:</p>

<p><img src="https://i.stack.imgur.com/LjDj3.png" alt="watchOS preview displaying a simple view"></p>

<p>Change the order of the modifiers and things change. This code effectively 'breaks' the modifiers, as padding and corner radius are no longer applied:</p>

<pre class="lang-swift prettyprint-override"><code>HStack {
  Text("Hello world")
    .background(Color(UIColor.darkGray))
    .padding()
    .cornerRadius(20.0)
}
</code>```

Why is this? I'm sure there's a logical explanation but I couldn't find any documentation or rationale for it.

答:
New Dev's answer is correct. Here is also another good explanation what happens behind the scenes. It's just another point of view of the same concept:

Whenever we apply a modifier to a SwiftUI view, we actually create a
  new view with that change applied – we don’t just modify the existing
  view in place. If you think about it, this behavior makes sense – our
  views only hold the exact properties we give them, so if we set the
  background color or font size there is no place to store that data.

Body:
When applying modifiers to a view in SwiftUI, it appears that the order matters.

For example, this code:

HStack {
  Text("Hello world")
    .padding()
    .background(Color(UIColor.darkGray))
    .cornerRadius(20.0)
}

..will produce this:

Change the order of the modifiers and things change. This code effectively 'breaks' the modifiers, as padding and corner radius are no longer applied:

HStack {
  Text("Hello world")
    .background(Color(UIColor.darkGray))
    .padding()
    .cornerRadius(20.0)
}

Why is this? I'm sure there's a logical explanation but I couldn't find any documentation or rationale for it.


问:
Show image in JTextPane
I know we can set html as JTextPane content type and then use img tag to display image but here I have image data in bytes and img do not accept bytes it just wants url. So how can I show that image in JTextPane? Any other solution for this situation?

I have tried storing image temporary at Temp directory and then give it's url in img but didn't get any success.

答:
The only way is to use JEditorPane instead of JTextPane. There you would have to set HTMLEditorKit. After that, following html should work (only with absolute paths).

```<code><html><img src="file:\\c:\images\example.gif" width=200 height=200></img>
</code>```

More information is at http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html

Title: Show image in JTextPane

Body:
The only way is to use JEditorPane instead of JTextPane. There you would have to set HTMLEditorKit. After that, following html should work (only with absolute paths).

<html><img src="file:\\c:\images\example.gif" width=200 height=200></img>

More information is at http://download.oracle.com/javase/tutorial/uiswing/components/editorpane.html


问:
Local npm registry, can't create team or org (verdaccio)
There is a server in which we configured a fresh installation of verdaccio to manage a local cache of NPM packages. We need to give some specific users access to publish packages and also manage package access for other users. For publishing purpose we create a team, put our package publisher users in that team and finally give admin permissions to the team.

The problem is for creating a team, there should exist an org, and there is no documentation for creating an organization via command-line.

Tried below steps

```<code>npm team create publishers
</code>```

npm ERR! code EINVALIDTYPE
npm ERR! typeerror Error: Argument #1: Expected string but got null
npm ERR! typeerror at /root/.nvm/versions/node/v14.3.0/lib/node_modules/npm/node_modules/libnpmteam/index.js:20:5
npm ERR! typeerror at /root/.nvm/versions/node/v14.3.0/lib/node_modules/npm/node_modules/libnpmteam/index.js:104:5
...
npm ERR! typeerror This is an error with npm itself. Please report this error at:
npm ERR! typeerror <https://npm.community>

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-06-01T04_49_13_414Z-debug.log
```
</blockquote>

```npm team create admin:publishers
```

<blockquote>
  <pre class="lang-none prettyprint-override"><code>npm ERR! code E404
npm ERR! 404 Not Found - PUT http://localhost:4873/-/org/admin/team

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-06-01T04_49_04_772Z-debug.log
</code>```

Links already read: npm team - npm org - verdaccio

答:
Verdaccio does not support npm team and any organization feature created by npmjs. You can find https://github.com/verdaccio/verdaccio#compatibility here the list of commands you can use.

If you want to support those commands by your own, you might create a plugin middleware for it.

Body:
There is a server in which we configured a fresh installation of verdaccio to manage a local cache of NPM packages. We need to give some specific users access to publish packages and also manage package access for other users. For publishing purpose we create a team, put our package publisher users in that team and finally give admin permissions to the team.

The problem is for creating a team, there should exist an org, and there is no documentation for creating an organization via command-line.

Tried below steps

npm team create publishers

npm ERR! code EINVALIDTYPE
npm ERR! typeerror Error: Argument #1: Expected string but got null
npm ERR! typeerror at /root/.nvm/versions/node/v14.3.0/lib/node_modules/npm/node_modules/libnpmteam/index.js:20:5
npm ERR! typeerror at /root/.nvm/versions/node/v14.3.0/lib/node_modules/npm/node_modules/libnpmteam/index.js:104:5
...
npm ERR! typeerror This is an error with npm itself. Please report this error at:
npm ERR! typeerror <https://npm.community>

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-06-01T04_49_13_414Z-debug.log

npm team create admin:publishers

npm ERR! code E404
npm ERR! 404 Not Found - PUT http://localhost:4873/-/org/admin/team

npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-06-01T04_49_04_772Z-debug.log

Links already read: npm team - npm org - verdaccio


答:
Since BUF_SIZE is 1, you are reading the input character by character.

This is fine, but this also mean that src is just a one-char array, not a nul-terminated string (an array of characters terminated by '\0' character).

And this mean all string manipulation functions, such as strcat cannot be used. All of them lead to undefined behavior when it comes to deal with araays that are not null-terminated..

In order to accomplish your task, just perform an extra write whenever you find an end of line:

```<code>if (src[0] == '\n') {
    char ecs = 'X';
    write(FAUST_fh, &ecs, 1);
    // it's always recommended to check the return value of write()
}
</code>```

All the other characters will be appended as usual. The X char write is just an insertion on the fly.

Title: How to add a 'X' to the end of every line in C?

Body:
I'm trying to append a capital 'X' character at the end of every line of a simple text file (while switching all chars to upper case at the same time) and writing the changes to a new file.

So initially, the file faust.txt contains:

Besonders aber laßt genug geschehn!
Man kommt zu schaun, man will am liebsten sehn.
Wird vieles vor den Augen abgesponnen,

After the call, the file FAUST.txt should contain:

BESONDERS ABER LAßT GENUG GESCHEHN!X
MAN KOMMT ZU SCHAUN, MAN WILL AM LIEBSTEN SEHN.X
WIRD VIELES VOR DEN AUGEN ABGESPONNEN,X

The copying and conversion to upper case seems to work but the appending is unclear to me:

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>

int main() {

    // 1)  Open faust source file
    int BUF_SIZE = 1;
    int faust_fh = open("faust.txt", O_RDONLY);
    char src[BUF_SIZE];

    // Destination file.
    int FAUST_fh = open("FAUST.txt", O_CREAT | O_WRONLY);

    int read_bytes = read(faust_fh, &src, BUF_SIZE);
    while (read_bytes > 0) {

        char c = src[0];
        char *C = &c;
        src[0] = toupper(*C);

        if (src[0] == '\n') {
            char *end = &src[0];
            strcat(end, "X");
            src[0] = *end;
        }

        write(FAUST_fh, &src, BUF_SIZE);
        read_bytes = read(faust_fh, src, BUF_SIZE);
    }

    close(FAUST_fh);
    close(faust_fh);
    return 0;
}

Note: I should accomplish this with system calls (if possible).

Body:
Since BUF_SIZE is 1, you are reading the input character by character.

This is fine, but this also mean that src is just a one-char array, not a nul-terminated string (an array of characters terminated by '\0' character).

And this mean all string manipulation functions, such as strcat cannot be used. All of them lead to undefined behavior when it comes to deal with araays that are not null-terminated..

In order to accomplish your task, just perform an extra write whenever you find an end of line:

if (src[0] == '\n') {
    char ecs = 'X';
    write(FAUST_fh, &ecs, 1);
    // it's always recommended to check the return value of write()
}

All the other characters will be appended as usual. The X char write is just an insertion on the fly.


问:
KeyError when trying to access a value in Tweepy response
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

```<code># Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)
</code>```

I've copied an extract of "image" at the bottom of the post

Then when I call:

```<code>image['id']
</code>```

I get: 892420643555336193, which is great :-)

But when I call:

```<code>image['media']
</code>```

I get the following error

```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'
</code>```

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

```<code># The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},
</code>```

答:
The media is inside another dictionary, image['entities'].

It might be easier to read contents of the dictionary image by looking at its keys:

image.keys()
```

<p>or the whole dictionary:</p>

<pre class="lang-py prettyprint-override"><code>import pprint
pprint.PrettyPrinter(depth=4).pprint(image)
</code>```

which outputs

```<code>{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
              'media': [{'display_url': '.....',
                         'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
                         'id': 892420639486877696,
                         'id_str': '892420639486877696',
                         'indices': [...],
                         'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'sizes': {...},
                         'type': 'photo',
                         'url': 'https......'}],
              'symbols': [],
              'urls': [],
              'user_mentions': []},
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the "
              'hole of a donut. 13/10',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'truncated': False}
</code>```

Body:
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

# Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)

I've copied an extract of "image" at the bottom of the post

Then when I call:

image['id']

I get: 892420643555336193, which is great :-)

But when I call:

image['media']

I get the following error

KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

# The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},

Body:
The media is inside another dictionary, image['entities'].

It might be easier to read contents of the dictionary image by looking at its keys:

image.keys()

or the whole dictionary:

import pprint
pprint.PrettyPrinter(depth=4).pprint(image)

which outputs

{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
              'media': [{'display_url': '.....',
                         'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
                         'id': 892420639486877696,
                         'id_str': '892420639486877696',
                         'indices': [...],
                         'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'sizes': {...},
                         'type': 'photo',
                         'url': 'https......'}],
              'symbols': [],
              'urls': [],
              'user_mentions': []},
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the "
              'hole of a donut. 13/10',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'truncated': False}


问:
This document requires 'TrustedScriptURL' assignment
After adding require-trusted-types-for 'script'; in my Content-Security-Policy header, which introduced from
Chrome 83 Beta to help lock down DOM XSS injection sinks,

when I open my website, it becomes a blank page. I got many these three kinds of errors in my console. (Chrome version 83.0.4103.61)

This document requires 'TrustedScript' assignment.

This document requires 'TrustedScriptURL' assignment.

TypeError: Failed to set the 'src' property on 'HTMLScriptElement': This document requires 'TrustedScriptURL' assignment.

I have read the article Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types. However, the article only says how to handle TrustedHTML, but not TrustedScript or TrustedScriptURL.

Any guide will be helpful. Thanks!

答:
Check this. MIght help you out.

https://zeronights.ru/wp-content/themes/zeronights-2019/public/materials/3_ZN2019_Jakub_Vrana_Krzysztof_Kotowicz_Trusted_Types_and_the_end_of_DOM_XSS.pdf

References for a potential fix:

https://github.com/w3c/webappsec-trusted-types

https://w3c.github.io/webappsec-trusted-types/dist/spec/#trused-script-url

Background on Trusted Types and Chrome browser implementation:

https://github.com/w3c/webappsec-trusted-types/blob/master/explainer.md

https://www.chromestatus.com/feature/5650088592408576

https://gadgets.kotowicz.net/poc/Trusted_Types_TPAC_2018.pdf

Short-term fix option:

Add a report-only CSP header. [not great and you have to knowledge various risks if you are running a sensitive prod app]

Long term fix option:

You could investigate to bring to your base the external third party stuff and avoid the overall pain.

I am not an expert, just trying to learn from this too and I'd say the fix is pretty much from case to case, and not a silver bullet type.

All the best!


问:
Typescript. What to do if module doesn't have @types?
I'm developing react application using typescript.

Here is my App.tsx. As you can see react has @types but other modules don't

Is there any way to stub these modules or use them as any or another

答:
All the modules you're referring have @types. But let's assume that the module you're using doesn't, e.g. the library kea(keajs) doesn't have @type defined to this date.

The simplest way to solve this is to create a declaration file declarations.d.ts and declare the problematic module like this:

```<code>declare module "kea"
</code>```

Then in your tsconfig.json you need to be sure that in include property you have something like:

```<code>...
"include": [
  "src", "declarations.d.ts"
]
...
</code>```

Or just put declarations.d.ts inside your src folder so you don't need to touch this file.

Be wary that you won’t have any types for the module (the module will be just a big any); but you won’t have any errors.

Body:
All the modules you're referring have @types. But let's assume that the module you're using doesn't, e.g. the library kea(keajs) doesn't have @type defined to this date.

The simplest way to solve this is to create a declaration file declarations.d.ts and declare the problematic module like this:

declare module "kea"

Then in your tsconfig.json you need to be sure that in include property you have something like:

...
"include": [
  "src", "declarations.d.ts"
]
...

Or just put declarations.d.ts inside your src folder so you don't need to touch this file.

Be wary that you won’t have any types for the module (the module will be just a big any); but you won’t have any errors.


问:
How to create a seperate dataframe of rows that contain NaN with pandas
Is it possible to create a new dataFrame using pandas that contains any row that has NaN in any column from an existing datafram to be reviewed by a person?

I'm able to get rows that contain NaN in a specific column with:
    df_nan = df[pd.isna(df["sales_person"])]

but is there a way to do this without having to list out each column name?

Body:
Since you didn't include your data, I created some as an example:

import pandas as pd
import numpy as np

X = np.random.RandomState(1).rand(10, 5)
X[X < 0.1] = np.nan

df = pd.DataFrame.from_records(X)
print(df)
#           0         1         2         3         4
# 0  0.417022  0.720324       NaN  0.302333  0.146756
# 1       NaN  0.186260  0.345561  0.396767  0.538817
# 2  0.419195  0.685220  0.204452  0.878117       NaN
# 3  0.670468  0.417305  0.558690  0.140387  0.198101
# 4  0.800745  0.968262  0.313424  0.692323  0.876389
# 5  0.894607       NaN       NaN  0.169830  0.878143
# 6       NaN  0.421108  0.957890  0.533165  0.691877
# 7  0.315516  0.686501  0.834626       NaN  0.750144
# 8  0.988861  0.748166  0.280444  0.789279  0.103226
# 9  0.447894  0.908596  0.293614  0.287775  0.130029

With that data, it's pretty straight forward to find any NaNs on a row:

nan_mask = pd.isnull(df).any(axis=1)
df[nan_mask]
#           0         1         2         3         4
# 0  0.417022  0.720324       NaN  0.302333  0.146756
# 1       NaN  0.186260  0.345561  0.396767  0.538817
# 2  0.419195  0.685220  0.204452  0.878117       NaN
# 5  0.894607       NaN       NaN  0.169830  0.878143
# 6       NaN  0.421108  0.957890  0.533165  0.691877
# 7  0.315516  0.686501  0.834626       NaN  0.750144

Now, only rows with any NaNs in them appear.


问:
Simple constraint layout child with max width in RecyclerView
I am trying to create a TextView such that it wraps its content until it reaches its max width. Following code kind of achieves that perfectly until it is used in RecyclerView. It seems like TextView doesn't measure its width again after I change its text in onBindViewHolder().

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_max="wrap"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.72" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

However notice how it works fine if I invoke requestLayout() on TextView in onBindViewHolder() below:

Update: Following code in onBindViewHolder() works too.

```<code>ConstraintSet().apply {
    clone(holder.parent)
    applyTo(holder.parent)
}
</code>```

parent being ConstraintLayout.

Does anyone understand whats going on here? Is this a bug in ConstraintLayout? Invoking requestLayout() in onBindViewHolder() is a bad practice and I don't want to do that.

答: I know its month late, but I recently encountered this problem, and couldn't find an answer either. The changing ConstraintSet() posed by the author works, but always has the question in mind if this is efficient. Another solution is to change app:layout_constraintWidth_max="wrap" to app:layout_constraintWidth_default="wrap" That worked for me, the recyclerView updates the constraint correctly when recycling the view holders

Body:
I am trying to create a TextView such that it wraps its content until it reaches its max width. Following code kind of achieves that perfectly until it is used in RecyclerView. It seems like TextView doesn't measure its width again after I change its text in onBindViewHolder().

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_max="wrap"
        app:layout_constraintWidth_default="percent"
        app:layout_constraintWidth_percent="0.72" />

</androidx.constraintlayout.widget.ConstraintLayout>

However notice how it works fine if I invoke requestLayout() on TextView in onBindViewHolder() below:

Update: Following code in onBindViewHolder() works too.

ConstraintSet().apply {
    clone(holder.parent)
    applyTo(holder.parent)
}

parent being ConstraintLayout.

Does anyone understand whats going on here? Is this a bug in ConstraintLayout? Invoking requestLayout() in onBindViewHolder() is a bad practice and I don't want to do that.


问:
Spring security: get Authenticated user in method
I am trying to get back the current authenticated user in a service class with:

```<code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
</code>```

but it returns me a String username instead of a user object.

What should I do to have the user object?

答:
An example of how to get the authenticated user in Controller using @AuthenticationPrincipal :

```<code>import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping
    public void getUser(@AuthenticationPrincipal User activeUser) {
        System.out.println("user name is "+activeUser.getUsername());
    }
}
</code>```

Body:
I am trying to get back the current authenticated user in a service class with:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

but it returns me a String username instead of a user object.

What should I do to have the user object?

Body:
An example of how to get the authenticated user in Controller using @AuthenticationPrincipal :

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping
    public void getUser(@AuthenticationPrincipal User activeUser) {
        System.out.println("user name is "+activeUser.getUsername());
    }
}


问:
mapView not zooming on second try using didUpdateUserLocation
i am loading a mapviewcontroller when the view map button is pressed from my mainviewcontroller:

```<code>- (IBAction)mapButton:(id)sender {
    MapKitDisplayViewController *mapKitDisplayView = [[MapKitDisplayViewController alloc] init];
    [self presentModalViewController:mapKitDisplayView animated:YES];
    [mapKitDisplayView release]; mapKitDisplayView = nil;
}
</code>```

On startup of this map view this method is called, which correctly zooms to the users location:

```<code>- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    myMapView.showsUserLocation = YES;
    NSLog(@"didUpdateUserLocation = '%@'", userLocation);

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([userLocation coordinate], 20000, 20000);
    [myMapView setRegion:region animated:YES];
}
</code>```

I have a done button on this screen that dismisses this view:

```<code>- (IBAction)mapDoneButton:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}
</code>```

At this stage the user is taken back to the main view controller, however when i press the view map button again, the didUpdateUserLocation method is never called! Hence, the map view is zoomed out to the default one and wont zoom in as before.

How can i get it to be called again?

thanks

答: MKMapView object doesn't trigger an update on user location on its own. You need to activate the search by setting showsUserLocation = YES. This will then fetch the user's location and then the delegate method mapView:didUpdateUserLocation: is called. So set this value to YES on viewWillAppear: and once you've the user location you can set it to NO to stop tracking the user. If you don't do that, it periodically updates the user location and calls the delegate method. Without doing this, user location should be unreliable.

Body:
i am loading a mapviewcontroller when the view map button is pressed from my mainviewcontroller:

- (IBAction)mapButton:(id)sender {
    MapKitDisplayViewController *mapKitDisplayView = [[MapKitDisplayViewController alloc] init];
    [self presentModalViewController:mapKitDisplayView animated:YES];
    [mapKitDisplayView release]; mapKitDisplayView = nil;
}

On startup of this map view this method is called, which correctly zooms to the users location:

- (void)mapView:(MKMapView *)myMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    myMapView.showsUserLocation = YES;
    NSLog(@"didUpdateUserLocation = '%@'", userLocation);

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([userLocation coordinate], 20000, 20000);
    [myMapView setRegion:region animated:YES];
}

I have a done button on this screen that dismisses this view:

- (IBAction)mapDoneButton:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

At this stage the user is taken back to the main view controller, however when i press the view map button again, the didUpdateUserLocation method is never called! Hence, the map view is zoomed out to the default one and wont zoom in as before.

How can i get it to be called again?

thanks


问:
Why Golang packages have to be v0 or v1 and not v2020
I read everywhere that packages have to have a tag of v0 or v1.  Why can't a tag be v2020 or something other than v0 or v1.  I have tried this personal and is get the following error with I use v2020.</p>

```<code>Scotts-Mac-mini:seeding syacko$ go mod tidy
go: errors parsing go.mod:
/Users/syacko/workspace/sotesoft/src/utils/seeding/go.mod:10: require gitlab.com/soteapps/packages: version "v2020.2.0" invalid: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2020
Scotts-Mac-mini:seeding syacko$
</code>```

答:
It's a convention, a convenience for everyone. Go modules chose to use the widely accepted Semantic Versioning v2.

Go Modules Wiki:

What happens if I create a go.mod but do not apply semver tags to my repository?

semver is a foundation of the modules system. In order to provide the best experience for consumers, module authors are encouraged to apply semver VCS tags (e.g., v0.1.0 or v1.2.3-rc.1), but semver VCS tags are not strictly required:

Modules are required to follow the semver specification in order for the go command to behave as documented. This includes following the semver specification regarding how and when breaking changes are allowed.

Modules that do not have semver VCS tags are recorded by consumers using a semver version in the form of a pseudo-version. Typically this will be a v0 major version, unless the module author constructed a v2+ module following the "Major Subdirectory" approach.

Therefore, modules that do not apply semver VCS tags and have not created a "Major Subdirectory" are effectively declaring themselves to be in the semver v0 major version series, and a module-based consumer will treat them as having a semver v0 major version.

An interesting and relevant blog post from Dave Cheney that predates Go modules: Gophers, please tag your releases

What do we want? Version management for Go packages! When do we want it? Yesterday!

[...] We want our Go build tool of choice to fetch the latest stable version when you start using the package in your project.[...]

But as it stands, today, in 2016, there is no way for a human, or a tool, to look at an arbitrary git (or mercurial, or bzr, etc) repository of Go code and ask questions like:

What versions of this project have been released?

What is the latest stable release of this software?

If I have version 1.2.3, is there a bugfix or security update that I should apply?

The reason for this is Go projects (repositories of Go packages) do not have versions, at least not in the way that our friends in other languages use that word. Go projects do not have versions because there is no formalised release process.

[...] I recommend that Go projects adopt SemVer 2.0.0. It’s a sound standard, it is well understood by many, not just Go programmers, and semantic versioning will let people write tools to build a dependency management ecosystem on top of a minimal release process.

Body:
I read everywhere that packages have to have a tag of v0 or v1.  Why can't a tag be v2020 or something other than v0 or v1.  I have tried this personal and is get the following error with I use v2020.

Scotts-Mac-mini:seeding syacko$ go mod tidy
go: errors parsing go.mod:
/Users/syacko/workspace/sotesoft/src/utils/seeding/go.mod:10: require gitlab.com/soteapps/packages: version "v2020.2.0" invalid: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2020
Scotts-Mac-mini:seeding syacko$