问:
Undefined references to symbols in standard libraries with musl-cross-make
I am using a musl-targeting cross compiler for arm, built with musl-cross-make (gcc 9.2.0, musl 1.2.0). When I compile a simple hello world c program with printf, I get undefined references for symbols that are in the standard library:

```<code>cross-musl/bin/arm-linux-musleabihf-gcc -c hello.c -o hello.o
cross-musl/bin/arm-linux-musleabihf-ld  hello.o -o hello.elf
cross-musl/bin/arm-linux-musleabihf-ld: warning: cannot find entry symbol _start; defaulting to 0000000000010074
cross-musl/bin/arm-linux-musleabihf-ld: hello.o: in function `main':
hello.c:(.text+0x18): undefined reference to `puts'
</code>```

When I add libc.a and crt1.o to the linker command, I get no error:

```<code>cross-musl/bin/arm-linux-musleabihf-gcc -c hello.c -o hello.o
cross-musl/bin/arm-linux-musleabihf-ld -Lcross-musl/arm-linux-musleabihf/lib -lc cross-musl/arm-linux-musleabihf/lib/crt1.o hello.o -o hello.elf
</code>```

I thought that it's not necessary to specify standard libraries and startup files when -nostartfiles, -nostdlib or -nodefaultlibs is not used, or am I wrong ?

答:
This is how the GNU tools work gcc has the most smarts when it is used to call not just the compiler but to call the linker it knows where everything is relative to it, binutils and the C library, this is why you see what you see when you build a GNU based toolchain. It is trivial to examine the call from gcc to the linker and see that it specifies everything.  ld has no clue where it is nor any way to figure out where anything is it has to be told everything. This is how ld was designed.  A simple example of a Linux program and a cross compiler.

```<code>#include <stdlib.h>
int main ( void )
{
    exit(1);
}

arm-linux-gnueabi-gcc so.c -o so.o
</code>```

and this is what is passed to ld (the actual binary is named ld when called from arm-whatever-gcc) to make linking work.

```<code>[1][-plugin]
[2][/usr/lib/gcc-cross/arm-linux-gnueabi/5/liblto_plugin.so]
[3][-plugin-opt=/usr/lib/gcc-cross/arm-linux-gnueabi/5/lto-wrapper]
[4][-plugin-opt=-fresolution=/tmp/ccaUZvi4.res]
[5][-plugin-opt=-pass-through=-lgcc]
[6][-plugin-opt=-pass-through=-lgcc_s]
[7][-plugin-opt=-pass-through=-lc]
[8][-plugin-opt=-pass-through=-lgcc]
[9][-plugin-opt=-pass-through=-lgcc_s]
[10][--sysroot=/]
[11][--build-id]
[12][--eh-frame-hdr]
[13][-dynamic-linker]
[14][/lib/ld-linux.so.3]
[15][-X]
[16][--hash-style=gnu]
[17][--as-needed]
[18][-m]
[19][armelf_linux_eabi]
[20][-z]
[21][relro]
[22][-o]
[23][so.o]
[24][crt1.o]
[25][crti.o]
[26][/usr/lib/gcc-cross/arm-linux-gnueabi/5/crtbegin.o]
[27][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5]
[28][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5/../../../../arm-linux-gnueabi/lib/../lib]
[29][-L/lib/../lib]
[30][-L/usr/lib/../lib]
[31][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5/../../../../arm-linux-gnueabi/lib]
[32][/tmp/ccmlFvlr.o]
[33][-lgcc]
[34][--as-needed]
[35][-lgcc_s]
[36][--no-as-needed]
[37][-lc]
[38][-lgcc]
[39][--as-needed]
[40][-lgcc_s]
[41][--no-as-needed]
[42][/usr/lib/gcc-cross/arm-linux-gnueabi/5/crtend.o]
[43][crtn.o]
</code>```

If you want to link yourself this has always been the case that you have to point at everything.  An exception being the default linker script, which since you want to replace your C library you absolutely have to replace that too.

This or you build into gcc the knowledge/mechanism to have it pass the new library information to the linker rather than the GNU C library information/paths...

Another example, x86 native:

```<code>gcc -O2 so.c -o so
[1][-plugin]
[2][/usr/lib/gcc/x86_64-linux-gnu/5/liblto_plugin.so]
[3][-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper]
[4][-plugin-opt=-fresolution=/tmp/ccmhqpU9.res]
[5][-plugin-opt=-pass-through=-lgcc]
[6][-plugin-opt=-pass-through=-lgcc_s]
[7][-plugin-opt=-pass-through=-lc]
[8][-plugin-opt=-pass-through=-lgcc]
[9][-plugin-opt=-pass-through=-lgcc_s]
[10][--sysroot=/]
[11][--build-id]
[12][--eh-frame-hdr]
[13][-m]
[14][elf_x86_64]
[15][--hash-style=gnu]
[16][--as-needed]
[17][-dynamic-linker]
[18][/lib64/ld-linux-x86-64.so.2]
[19][-z]
[20][relro]
[21][-o]
[22][so]
[23][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o]
[24][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o]
[25][/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o]
[26][-L/usr/lib/gcc/x86_64-linux-gnu/5]
[27][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu]
[28][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib]
[29][-L/lib/x86_64-linux-gnu]
[30][-L/lib/../lib]
[31][-L/usr/lib/x86_64-linux-gnu]
[32][-L/usr/lib/../lib]
[33][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../..]
[34][/tmp/ccg1E03e.o]
[35][-lgcc]
[36][--as-needed]
[37][-lgcc_s]
[38][--no-as-needed]
[39][-lc]
[40][-lgcc]
[41][--as-needed]
[42][-lgcc_s]
[43][--no-as-needed]
[44][/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o]
[45][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o]
</code>```

Same deal, ld has no knowledge of where anything is, the C library, its bootstrap, gcc lib, etc...this was all boiled into gcc, probably by design. (gcc of course being a wrapper that calls multiple programs in order to compile a parser and some other then the actual compiler, then the assembler then the linker and perhaps others as well, as just assembles, ld just links).

A lot of folks get familiar with baremetal and thus not use a C library or other stuff, so the linker script is somewhat trivial (certainly not as trivial as ld file.o -o file.elf, unless you have a hand made environment for that target).  When you want to add libraries either you teach gcc about it or you pass everything to the linker that it needs.

-lgcc simply means for example go look for libgcc in the -L specified path, without a -L specified path, no joy as ld doesn't know about things outside binutils and probably looks locally.

binutils is a set of utils.  gcc is a higher level than that and relies on binutils (or a replacement).  gcc can't live without binutils, bintuils certainly lives without gcc, this and the Unix way, clearly gcc passes everything outside binutils to binutils in order for it to be a binary utility for gcc.

Body:
I am using a musl-targeting cross compiler for arm, built with musl-cross-make (gcc 9.2.0, musl 1.2.0). When I compile a simple hello world c program with printf, I get undefined references for symbols that are in the standard library:

cross-musl/bin/arm-linux-musleabihf-gcc -c hello.c -o hello.o
cross-musl/bin/arm-linux-musleabihf-ld  hello.o -o hello.elf
cross-musl/bin/arm-linux-musleabihf-ld: warning: cannot find entry symbol _start; defaulting to 0000000000010074
cross-musl/bin/arm-linux-musleabihf-ld: hello.o: in function `main':
hello.c:(.text+0x18): undefined reference to `puts'

When I add libc.a and crt1.o to the linker command, I get no error:

cross-musl/bin/arm-linux-musleabihf-gcc -c hello.c -o hello.o
cross-musl/bin/arm-linux-musleabihf-ld -Lcross-musl/arm-linux-musleabihf/lib -lc cross-musl/arm-linux-musleabihf/lib/crt1.o hello.o -o hello.elf

I thought that it's not necessary to specify standard libraries and startup files when -nostartfiles, -nostdlib or -nodefaultlibs is not used, or am I wrong ?

Body:
This is how the GNU tools work gcc has the most smarts when it is used to call not just the compiler but to call the linker it knows where everything is relative to it, binutils and the C library, this is why you see what you see when you build a GNU based toolchain. It is trivial to examine the call from gcc to the linker and see that it specifies everything.  ld has no clue where it is nor any way to figure out where anything is it has to be told everything. This is how ld was designed.  A simple example of a Linux program and a cross compiler.

#include <stdlib.h>
int main ( void )
{
    exit(1);
}

arm-linux-gnueabi-gcc so.c -o so.o

and this is what is passed to ld (the actual binary is named ld when called from arm-whatever-gcc) to make linking work.

[1][-plugin]
[2][/usr/lib/gcc-cross/arm-linux-gnueabi/5/liblto_plugin.so]
[3][-plugin-opt=/usr/lib/gcc-cross/arm-linux-gnueabi/5/lto-wrapper]
[4][-plugin-opt=-fresolution=/tmp/ccaUZvi4.res]
[5][-plugin-opt=-pass-through=-lgcc]
[6][-plugin-opt=-pass-through=-lgcc_s]
[7][-plugin-opt=-pass-through=-lc]
[8][-plugin-opt=-pass-through=-lgcc]
[9][-plugin-opt=-pass-through=-lgcc_s]
[10][--sysroot=/]
[11][--build-id]
[12][--eh-frame-hdr]
[13][-dynamic-linker]
[14][/lib/ld-linux.so.3]
[15][-X]
[16][--hash-style=gnu]
[17][--as-needed]
[18][-m]
[19][armelf_linux_eabi]
[20][-z]
[21][relro]
[22][-o]
[23][so.o]
[24][crt1.o]
[25][crti.o]
[26][/usr/lib/gcc-cross/arm-linux-gnueabi/5/crtbegin.o]
[27][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5]
[28][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5/../../../../arm-linux-gnueabi/lib/../lib]
[29][-L/lib/../lib]
[30][-L/usr/lib/../lib]
[31][-L/usr/lib/gcc-cross/arm-linux-gnueabi/5/../../../../arm-linux-gnueabi/lib]
[32][/tmp/ccmlFvlr.o]
[33][-lgcc]
[34][--as-needed]
[35][-lgcc_s]
[36][--no-as-needed]
[37][-lc]
[38][-lgcc]
[39][--as-needed]
[40][-lgcc_s]
[41][--no-as-needed]
[42][/usr/lib/gcc-cross/arm-linux-gnueabi/5/crtend.o]
[43][crtn.o]

If you want to link yourself this has always been the case that you have to point at everything.  An exception being the default linker script, which since you want to replace your C library you absolutely have to replace that too.

This or you build into gcc the knowledge/mechanism to have it pass the new library information to the linker rather than the GNU C library information/paths...

Another example, x86 native:

gcc -O2 so.c -o so
[1][-plugin]
[2][/usr/lib/gcc/x86_64-linux-gnu/5/liblto_plugin.so]
[3][-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper]
[4][-plugin-opt=-fresolution=/tmp/ccmhqpU9.res]
[5][-plugin-opt=-pass-through=-lgcc]
[6][-plugin-opt=-pass-through=-lgcc_s]
[7][-plugin-opt=-pass-through=-lc]
[8][-plugin-opt=-pass-through=-lgcc]
[9][-plugin-opt=-pass-through=-lgcc_s]
[10][--sysroot=/]
[11][--build-id]
[12][--eh-frame-hdr]
[13][-m]
[14][elf_x86_64]
[15][--hash-style=gnu]
[16][--as-needed]
[17][-dynamic-linker]
[18][/lib64/ld-linux-x86-64.so.2]
[19][-z]
[20][relro]
[21][-o]
[22][so]
[23][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o]
[24][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o]
[25][/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o]
[26][-L/usr/lib/gcc/x86_64-linux-gnu/5]
[27][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu]
[28][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib]
[29][-L/lib/x86_64-linux-gnu]
[30][-L/lib/../lib]
[31][-L/usr/lib/x86_64-linux-gnu]
[32][-L/usr/lib/../lib]
[33][-L/usr/lib/gcc/x86_64-linux-gnu/5/../../..]
[34][/tmp/ccg1E03e.o]
[35][-lgcc]
[36][--as-needed]
[37][-lgcc_s]
[38][--no-as-needed]
[39][-lc]
[40][-lgcc]
[41][--as-needed]
[42][-lgcc_s]
[43][--no-as-needed]
[44][/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o]
[45][/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o]

Same deal, ld has no knowledge of where anything is, the C library, its bootstrap, gcc lib, etc...this was all boiled into gcc, probably by design. (gcc of course being a wrapper that calls multiple programs in order to compile a parser and some other then the actual compiler, then the assembler then the linker and perhaps others as well, as just assembles, ld just links).

A lot of folks get familiar with baremetal and thus not use a C library or other stuff, so the linker script is somewhat trivial (certainly not as trivial as ld file.o -o file.elf, unless you have a hand made environment for that target).  When you want to add libraries either you teach gcc about it or you pass everything to the linker that it needs.

-lgcc simply means for example go look for libgcc in the -L specified path, without a -L specified path, no joy as ld doesn't know about things outside binutils and probably looks locally.

binutils is a set of utils.  gcc is a higher level than that and relies on binutils (or a replacement).  gcc can't live without binutils, bintuils certainly lives without gcc, this and the Unix way, clearly gcc passes everything outside binutils to binutils in order for it to be a binary utility for gcc.


来源: stackexchange

问:
Ajax file upload not working in chrome browser
I am using AjaxUpload for file upload but with the recent update in Chrome, it seems to be no longer working in chrome and many other browsers. So I started to figure it out. I have to spend around 2 to 3 hours trying various possible ways but it was not working.

The Issue was, When we select image or file then it was calling the OnComplete Event without calling server-side action due to which it was returning a null empty value. And after completed with OnComplete event then server-side action got called with no return back to OnComplete Event.

When “iframeSrc” is set to “javascript:false” on https pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue

Later I fix this in the code and it seems to be working for me now.

```<code>var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
</code>```

I hope it will work for you as well. :)

Reference: https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

If is there anything I am missing the do correct me.

答:
This will fix the issue.

Old Code:

```<code>var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
</code>```

New Code with chagnes:

```<code>var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using AjaxUpload for file upload but with the recent update in Chrome, it seems to be no longer working in chrome and many other browsers. So I started to figure it out. I have to spend around 2 to 3 hours trying various possible ways but it was not working.

The Issue was, When we select image or file then it was calling the OnComplete Event without calling server-side action due to which it was returning a null empty value. And after completed with OnComplete event then server-side action got called with no return back to OnComplete Event.

When “iframeSrc” is set to “javascript:false” on https pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue

Later I fix this in the code and it seems to be working for me now.

var iframe = toElement('');

I hope it will work for you as well. :)

Reference: https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

If is there anything I am missing the do correct me.

Body:
This will fix the issue.

Old Code:

var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');

New Code with chagnes:

var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');


问:
How to load a word doc in Rich Textbox WPF
I am trying to load a word document into Rich Textbox control so that user can edit the contents and eventually save it. Following is the code I use:

```<code>string fileName = @"..\..\Files\test.doc";

            TextRange range;

            FileStream fStream;

            if (File.Exists(fileName))
            {

                range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);

                fStream = new FileStream(fileName, FileMode.OpenOrCreate);

                range.Load(fStream, DataFormats.Rtf);

                fStream.Close();

            }
</code>```

When I run it I get the following error:

```<code>Unrecognized structure in data format 'Rich Text Format'.Parameter name: stream
</code>```

I have made sure that that document contains no images.

答:
A word document isn't a rich text document.

The doc would need to be first saved as an RTF file before you can do this.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to load a word document into Rich Textbox control so that user can edit the contents and eventually save it. Following is the code I use:

string fileName = @"..\..\Files\test.doc";

            TextRange range;

            FileStream fStream;

            if (File.Exists(fileName))
            {

                range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);

                fStream = new FileStream(fileName, FileMode.OpenOrCreate);

                range.Load(fStream, DataFormats.Rtf);

                fStream.Close();

            }

When I run it I get the following error:

Unrecognized structure in data format 'Rich Text Format'.Parameter name: stream

I have made sure that that document contains no images.


问:
Reactor Flux flatMap operator throughput/concurrency control and achieve backpressure
I am using Flux to build my reactive pipeline. In the pipeline, I need to call 3 different external system REST APIs, which are very strict with their Rate of access.
I will be throttled exponentially if i breach the rate-per-sec threshold. Each system will have their own thresholds.

I am using Spring WebClient to make the REST API calls; among 3 APIs, 2 of them are GET and 1 is POST.

In my reactor pipeline, the WebClient are wrapped within the flatMap to perform the API calls, like the below code:

```<code>WebClient getApiCall1 = WebClient.builder().build().get("api-system-1").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall2 = WebClient.builder().build().get("api-system-2").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall3 = WebClient.builder().build().get("api-system-3").retrieve().bodyToMono(String.class) //actual return DTO is different from string

    Flux.generator(generator) // Generator pushes the elements from source 1 at a time

    // make call to 1st API Service
    .flatMap(data -> getApiCall1)
    .map(api1Response -> api1ResponseModified)

    // make call to 2nd API Service
    .flatMap(api1ResponseModified -> getApiCall2)
    .map(api2Response -> api2ResponseModified)

// make call to 3rd API Service
.flatMap(api2ResponseModified -> getApiCall3)
.map(api3Response -> api3ResponseModified)

// rest of the pipeline operators

//end
.subscriber();
</code>```

The problem is, if I dont set the concurrency value to the flatMap, then I the pipeline execution breaching the threshold within few seconds of service startup.
If I set the value of concurrency to 1, 2, 5, 10, then the throughput is becoming very low.

The Question is, Without setting any value to the concurrency How could I achieve the Backpressure which should honour the rate limits of the external system?

答:
Resilience4j has support for rate limiting with Reactor.
See:

https://resilience4j.readme.io/docs/ratelimiter

https://resilience4j.readme.io/docs/examples-1#section-decorate-mono-or-flux-with-a-ratelimiter

Body:
I am using Flux to build my reactive pipeline. In the pipeline, I need to call 3 different external system REST APIs, which are very strict with their Rate of access.
I will be throttled exponentially if i breach the rate-per-sec threshold. Each system will have their own thresholds.

I am using Spring WebClient to make the REST API calls; among 3 APIs, 2 of them are GET and 1 is POST.

In my reactor pipeline, the WebClient are wrapped within the flatMap to perform the API calls, like the below code:

WebClient getApiCall1 = WebClient.builder().build().get("api-system-1").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall2 = WebClient.builder().build().get("api-system-2").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall3 = WebClient.builder().build().get("api-system-3").retrieve().bodyToMono(String.class) //actual return DTO is different from string

    Flux.generator(generator) // Generator pushes the elements from source 1 at a time

    // make call to 1st API Service
    .flatMap(data -> getApiCall1)
    .map(api1Response -> api1ResponseModified)

    // make call to 2nd API Service
    .flatMap(api1ResponseModified -> getApiCall2)
    .map(api2Response -> api2ResponseModified)

// make call to 3rd API Service
.flatMap(api2ResponseModified -> getApiCall3)
.map(api3Response -> api3ResponseModified)

// rest of the pipeline operators

//end
.subscriber();

The problem is, if I dont set the concurrency value to the flatMap, then I the pipeline execution breaching the threshold within few seconds of service startup.
If I set the value of concurrency to 1, 2, 5, 10, then the throughput is becoming very low.

The Question is, Without setting any value to the concurrency How could I achieve the Backpressure which should honour the rate limits of the external system?


问:
New form of for loop in C language?
Not long ago, I stumbled across a very interesting innovation in a for loop (or maybe it is nothing new but I've been living in a cave?). Please take a look and explain to me why the initialize gap is empty? Of course, that's the part of the program which works. I would grateful for any revelation:)

```<code>void rzad_zn(char ch, int i, int j)
{
    int pom;
    pom = i;
    for(; i<=j; i++)
    {
        printf("%d ", i);
    }
    printf("\n");
    for(; pom<=j; pom++)
    {
        printf("%c ", ch);
    }
    printf("\n");
}
</code>```

答:
The for loop has three components, all of which are optional, as in this is a valid loop as well:

```<code>for (;;) { }
</code>```

Though it is an infinite loop unless something calls break.

Any combination of arguments may be used, even compound ones like:

```<code>for (int i = 0, j = 0; i < j; ++i) { ... }
</code>```

Where you can declare multiple variables, or use the comma operator in the other parts to join together several operations if necessary.

Title: New form of for loop in C language?

Body:
Not long ago, I stumbled across a very interesting innovation in a for loop (or maybe it is nothing new but I've been living in a cave?). Please take a look and explain to me why the initialize gap is empty? Of course, that's the part of the program which works. I would grateful for any revelation:)

void rzad_zn(char ch, int i, int j)
{
    int pom;
    pom = i;
    for(; i<=j; i++)
    {
        printf("%d ", i);
    }
    printf("\n");
    for(; pom<=j; pom++)
    {
        printf("%c ", ch);
    }
    printf("\n");
}

Body:
The for loop has three components, all of which are optional, as in this is a valid loop as well:

for (;;) { }

Though it is an infinite loop unless something calls break.

Any combination of arguments may be used, even compound ones like:

for (int i = 0, j = 0; i < j; ++i) { ... }

Where you can declare multiple variables, or use the comma operator in the other parts to join together several operations if necessary.


问:
How to get the list of path to directories which do not other directories?
example:

```<code>v2/doc/a/text1.txt
v2/doc/a/text2.txt
v2/doc/a/text3.txt
v2/doc/b/text1.txt
v2/doc/b/text1.txt
v2/doc/b/some_dir
v2/docs/a/text1.txt
v2/docs/a/text2.txt
</code>```

This output should be:

```<code>v2/doc/a (because a does not contain any other dir)
v2/doc/b/some_dir (because some_dir also does not contain any other dir)
v2/docs/a
</code>```

I know in python this could be done by something as simple as this:

```<code>for root, dirs, files in os.walk(".", topdown=False):
    if not dirs
</code>```

I was trying to use walk function. func Walk(root string, walkFn WalkFunc) error

```<code>err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
        if info.IsDir()  {
            // here I want to check if the current dir has any other dir or not(how do I check for this using Walk or some other function??)
            // if directory is present; do nothing
            // else store the path to a string array
        }

        return nil
    })
</code>```

After hmm help, I wrote this.

```<code>var paths []string
    err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            files, err := ioutil.ReadDir(path)
            if err != nil{
                log.Fatal(err)
            }
            for _, file := range files{
                if file.IsDir(){
                    return nil
                }
            }
            fmt.Printf("%s added to PATHS\n", path)
            paths = append(paths, path)
        }
        return nil
    })
    if err != nil {
        //fmt.Printf()
        return
    }
    fmt.Println(paths)
</code>```

Is there a better way or is this fine?

答:
this is a solution to find most deep directories of a given path.</p>

```<code>package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

func main() {

    // 1. Collect all directories
    var dirs []string
    filepath.Walk("..", func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            dirs = append(dirs, path)
        }
        return nil
    })

    // 2. Keep only those that do not match a (longer) subdirectory path
    var okDirs []string
    for _, maybe := range dirs {
        ok := true
        for _, d := range dirs {
            if len(d) > len(maybe) && strings.HasPrefix(d, maybe) {
                ok = false
                break
            }
        }
        if ok {
            okDirs = append(okDirs, maybe)
            fmt.Println(maybe)
        }
    }
    _ = okDirs
}
</code>```

Body:
example:

v2/doc/a/text1.txt
v2/doc/a/text2.txt
v2/doc/a/text3.txt
v2/doc/b/text1.txt
v2/doc/b/text1.txt
v2/doc/b/some_dir
v2/docs/a/text1.txt
v2/docs/a/text2.txt

This output should be:

v2/doc/a (because a does not contain any other dir)
v2/doc/b/some_dir (because some_dir also does not contain any other dir)
v2/docs/a

I know in python this could be done by something as simple as this:

for root, dirs, files in os.walk(".", topdown=False):
    if not dirs

I was trying to use walk function. func Walk(root string, walkFn WalkFunc) error

err = filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
        if info.IsDir()  {
            // here I want to check if the current dir has any other dir or not(how do I check for this using Walk or some other function??)
            // if directory is present; do nothing
            // else store the path to a string array
        }

        return nil
    })

After hmm help, I wrote this.

var paths []string
    err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            files, err := ioutil.ReadDir(path)
            if err != nil{
                log.Fatal(err)
            }
            for _, file := range files{
                if file.IsDir(){
                    return nil
                }
            }
            fmt.Printf("%s added to PATHS\n", path)
            paths = append(paths, path)
        }
        return nil
    })
    if err != nil {
        //fmt.Printf()
        return
    }
    fmt.Println(paths)

Is there a better way or is this fine?

Body:
this is a solution to find most deep directories of a given path.

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

func main() {

    // 1. Collect all directories
    var dirs []string
    filepath.Walk("..", func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            dirs = append(dirs, path)
        }
        return nil
    })

    // 2. Keep only those that do not match a (longer) subdirectory path
    var okDirs []string
    for _, maybe := range dirs {
        ok := true
        for _, d := range dirs {
            if len(d) > len(maybe) && strings.HasPrefix(d, maybe) {
                ok = false
                break
            }
        }
        if ok {
            okDirs = append(okDirs, maybe)
            fmt.Println(maybe)
        }
    }
    _ = okDirs
}


问:
How to change axios content from "text/html" to application/json type in Nestjs
I discovered that axios is returning a string instead of a valid json.

```<code>headers:Object {date: "Tue, 02 Jun 2020 08:44:06 GMT", server: "Apache", connection: "close", …}
connection:"close"
content-type:"text/html; charset=UTF-8"
date:"Tue, 02 Jun 2020 08:44:06 GMT"
server:"Apache"
transfer-encoding:"chunked"

</code>```

how do I change the content-type to application/json in NestJs application?
I tried this but didnt not work

```<code> const meterInfo = await this.httpService.get(url, { headers: { "Content-Type": "application/json" } }).toPromise();
</code>```

Here is the invalid json returned.

```<code>"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"
</code>```

答:
Instead of sending a Content-Type header, you should send an Accept header with the same MIME type. This tells the server what you are expecting to receive, and if Content Negotiation is set up properly, it will allow you to get a JSON back instead of that weird string.

this.httpService.get(
  url,
  {
    headers: {
      'Accept': 'application/json',
    },
  },
).toPromise();
```

If that doesn't work, you'll need to provide your own serializer to take the string from that wonky format to JSON, or get in touch with the server admins and see if they can provide you better documentation about how to consume their API.

Body:
I discovered that axios is returning a string instead of a valid json.

headers:Object {date: "Tue, 02 Jun 2020 08:44:06 GMT", server: "Apache", connection: "close", …}
connection:"close"
content-type:"text/html; charset=UTF-8"
date:"Tue, 02 Jun 2020 08:44:06 GMT"
server:"Apache"
transfer-encoding:"chunked"

how do I change the content-type to application/json in NestJs application?
I tried this but didnt not work

 const meterInfo = await this.httpService.get(url, { headers: { "Content-Type": "application/json" } }).toPromise();

Here is the invalid json returned.

"{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Utility","minimumAmount":"13897"},"response_hash":"c43c9d74480f340f55156f6r5c56487v8w"}"

Body:
Instead of sending a Content-Type header, you should send an Accept header with the same MIME type. This tells the server what you are expecting to receive, and if Content Negotiation is set up properly, it will allow you to get a JSON back instead of that weird string.

this.httpService.get(
  url,
  {
    headers: {
      'Accept': 'application/json',
    },
  },
).toPromise();

If that doesn't work, you'll need to provide your own serializer to take the string from that wonky format to JSON, or get in touch with the server admins and see if they can provide you better documentation about how to consume their API.


问:
Automatically compile a .au3 script via my C# code
I'm trying to compile an .Au3 script code automatically, then then run it.
I update the script (au3 file) automatically, but for it to work when I update the script, it must be compiled first (to use the new script).
There is no issue running the .exe file, my issue is I can't find code to compile it before I run it.
This is how I run my executable:

```<code> Process.Start(@"C:\Users\XX\Documents\visual studio 2017\Projects\TESTING TEXT\TESTING TEXT\bin\Debug\XX.exe");
</code>```

But before I run my executable, I need to compile the script.  Any help?

答:
Take a look at this documentation: https://www.autoitscript.com/autoit3/docs/intro/compiler.htm

You should be able to call the command line utility, Aut2exe.exe, to compile from another application.

The syntax here would be

```<code>Aut2exe.exe /in c:\path\to\your\script.au3 /out c:\path\to\save\app.exe /icon c:\path\to\icon.ico /x64
</code>```

So to execute this from C#, it would be something like

```<code>Process.Start('c:\path\to\Aut2exe.exe', '/in c:\path\to\your\script.au3 /out c:\path\to\save\app.exe /icon c:\path\to\icon.ico /x64')
</code>```

Body:
I'm trying to compile an .Au3 script code automatically, then then run it.
I update the script (au3 file) automatically, but for it to work when I update the script, it must be compiled first (to use the new script).
There is no issue running the .exe file, my issue is I can't find code to compile it before I run it.
This is how I run my executable:

 Process.Start(@"C:\Users\XX\Documents\visual studio 2017\Projects\TESTING TEXT\TESTING TEXT\bin\Debug\XX.exe");

But before I run my executable, I need to compile the script.  Any help?

Body:
Take a look at this documentation: https://www.autoitscript.com/autoit3/docs/intro/compiler.htm

You should be able to call the command line utility, Aut2exe.exe, to compile from another application.

The syntax here would be

Aut2exe.exe /in c:\path\to\your\script.au3 /out c:\path\to\save\app.exe /icon c:\path\to\icon.ico /x64

So to execute this from C#, it would be something like

Process.Start('c:\path\to\Aut2exe.exe', '/in c:\path\to\your\script.au3 /out c:\path\to\save\app.exe /icon c:\path\to\icon.ico /x64')


问:
Which reducer gets used when using dispatch in mapDispatchToProps?
I am learning about Redux and I have two reducers, a contactReducer to show contacts on the page and a testReducer to just mess around with. In one of my component files I have this function:

```<code>const mapDispatchToProps = (dispatch) => ({
  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});
</code>```

These are my two reducer files:
contactReducer:

```<code>import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contacts: [
    {
      id: 1,
      name: "John Doe",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "Karen Williams",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "Henry Johnson",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CONTACTS:
      return {
        ...state,
      };
    default:
      console.log("testing action in contactReducer");
      return state;
  }
}

</code>```

and testReducer:

```<code>import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contactsTest: [
    {
      id: 1,
      name: "ffffffffffff",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "ggggggggggggg",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "aaaaaaaaaaaaaa",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case "TEST_ACTION":
      return {
        ...state,
      };
    default:
      console.log("testing action");
      return state;
  }
}

</code>```

So, what I noticed from the console.log statements in the reducer files was that for every contact, both the contactReducer and testReducer's function was called with this line:

```<code>  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});
</code>```

What if I have multiple reducers but I only want to call one of their functions for dispatch, what would I do?

答: combineReducers, Is a helper function in redux that helps you divide your reducers. take a look at this link: LINK

Body:
I am learning about Redux and I have two reducers, a contactReducer to show contacts on the page and a testReducer to just mess around with. In one of my component files I have this function:

const mapDispatchToProps = (dispatch) => ({
  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});

These are my two reducer files:
contactReducer:

import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contacts: [
    {
      id: 1,
      name: "John Doe",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "Karen Williams",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "Henry Johnson",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CONTACTS:
      return {
        ...state,
      };
    default:
      console.log("testing action in contactReducer");
      return state;
  }
}

and testReducer:

import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contactsTest: [
    {
      id: 1,
      name: "ffffffffffff",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "ggggggggggggg",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "aaaaaaaaaaaaaa",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case "TEST_ACTION":
      return {
        ...state,
      };
    default:
      console.log("testing action");
      return state;
  }
}

So, what I noticed from the console.log statements in the reducer files was that for every contact, both the contactReducer and testReducer's function was called with this line:

  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});

What if I have multiple reducers but I only want to call one of their functions for dispatch, what would I do?


问:
LaTeX: Strange "La, Lb" showing in nested enumerate
I'm writing a big LaTeX document. In it I have a nested enumerate environment:

```<code>\begin{enumerate}
     \item Bla bla
     \item More Bla Bla
     \item Now we nest:
        \begin{enumerate}
        \item Nested Bla Bla
        \item ...And more
        \end{enumerate}
     \item Back from enumeration
\end{enumerate}
</code>```

The problem: In the output the enumeration of the nested part is with "La", "Lb" etc.

As I said, it's a complex document and I'm sure the error is somewhere in the definitions/document class. So I don't expect a solution; rather, I hope that someone can pinpoint me as where to search, and what exactly to search (for example, what commands modify the numbering in enumerate environment in the first place?)

答:
Your example above reproduces fine on my machine. Here's the output (as expected)

Now if you wanted to change the list numbering to look like (La), (Lb) etc, you'd add something like this to your preamble:

```<code>\renewcommand{\theenumii}{(L\alph{enumii})}
\renewcommand{\labelenumii}{\theenumii}
</code>```

which will produce and output like

So you should look in your preamble/definitions to see if you've made any modifications like this.

Body:
I'm writing a big LaTeX document. In it I have a nested enumerate environment:

\begin{enumerate}
     \item Bla bla
     \item More Bla Bla
     \item Now we nest:
        \begin{enumerate}
        \item Nested Bla Bla
        \item ...And more
        \end{enumerate}
     \item Back from enumeration
\end{enumerate}

The problem: In the output the enumeration of the nested part is with "La", "Lb" etc.

As I said, it's a complex document and I'm sure the error is somewhere in the definitions/document class. So I don't expect a solution; rather, I hope that someone can pinpoint me as where to search, and what exactly to search (for example, what commands modify the numbering in enumerate environment in the first place?)

Body:
Your example above reproduces fine on my machine. Here's the output (as expected)

Now if you wanted to change the list numbering to look like (La), (Lb) etc, you'd add something like this to your preamble:

\renewcommand{\theenumii}{(L\alph{enumii})}
\renewcommand{\labelenumii}{\theenumii}

which will produce and output like

So you should look in your preamble/definitions to see if you've made any modifications like this.


问:
search in each of the s3 bucket and see if the given folder exists
I'm trying to get the files from specific folders in s3 Buckets:

I have 4 buckets in s3 with the following names:

```<code>1 - 'PDF'
2 - 'TXT'
3 - 'PNG'
4 - 'JPG'
</code>```

The folder structure for all s3 buckets looks like this:

```<code>1- PDF/analysis/pdf-to-img/processed/files
2- TXT/report/processed/files
3- PNG/analysis/reports/png-to-txt/processed/files
4- JPG/jpg-to-txt/empty
</code>```

I have to check if this folder prefix processed/files is present in the bucket, and if it is present, I'll read the files present in those directories, else I'll ignore them.

Code:

```<code>buckets = ['PDF','TXT','PNG','JPG']

client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'processed/files', Delimiter='/')
    print(result)
</code>```

I can enter into each directory if the folder structure is same, but how can I handle this when the folder structure varies for each bucket?

答:
This is maybe a lengthy process.

```<code> buckets = ['PDF','TXT','PNG','JPG']
    s3_client = getclient('s3')
    for i in buckets:
        result = s3_client.list_objects(Bucket= i, Prefix='', Delimiter ='')
        contents = result.get('Contents')
        for content in contents:
            if 'processed/files/' in content.get('Key'):
                print("Do the process")
</code>```

You can get the list of directories from the s3 bucket. If it contains the required folder do the required process.

Body:
I'm trying to get the files from specific folders in s3 Buckets:

I have 4 buckets in s3 with the following names:

1 - 'PDF'
2 - 'TXT'
3 - 'PNG'
4 - 'JPG'

The folder structure for all s3 buckets looks like this:

1- PDF/analysis/pdf-to-img/processed/files
2- TXT/report/processed/files
3- PNG/analysis/reports/png-to-txt/processed/files
4- JPG/jpg-to-txt/empty

I have to check if this folder prefix processed/files is present in the bucket, and if it is present, I'll read the files present in those directories, else I'll ignore them.

Code:

buckets = ['PDF','TXT','PNG','JPG']

client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'processed/files', Delimiter='/')
    print(result)

I can enter into each directory if the folder structure is same, but how can I handle this when the folder structure varies for each bucket?

Body:
This is maybe a lengthy process.

 buckets = ['PDF','TXT','PNG','JPG']
    s3_client = getclient('s3')
    for i in buckets:
        result = s3_client.list_objects(Bucket= i, Prefix='', Delimiter ='')
        contents = result.get('Contents')
        for content in contents:
            if 'processed/files/' in content.get('Key'):
                print("Do the process")

You can get the list of directories from the s3 bucket. If it contains the required folder do the required process.


问:
Get base URL from Axios - react native
Is is possible to get the base URL from the axios and store it to a variable?

```<code>const instance = axios.create({
  baseURL: "http://192.168.0.103/api",
});
</code>```

What i want to do is..

```<code>const photo= "HTTP://192.168.0.103/" + image-Path;
</code>```

this is working , but i don't want to use the address here (since i already declared it in axios file, i don't want to repeat it several pages), instead i want to get it from axios and use it here.

Is it even possible?

答:
This will work</p>

```<code>    const axios = require('axios');

    const api = axios.create({
    baseURL: "http://www.google.com.pk"
    });

    console.log(api.defaults.baseURL)
</code>```

Title: Get base URL from Axios - react native

Body:
Is is possible to get the base URL from the axios and store it to a variable?

const instance = axios.create({
  baseURL: "http://192.168.0.103/api",
});

What i want to do is..

const photo= "HTTP://192.168.0.103/" + image-Path;

this is working , but i don't want to use the address here (since i already declared it in axios file, i don't want to repeat it several pages), instead i want to get it from axios and use it here.

Is it even possible?

Body:
This will work

    const axios = require('axios');

    const api = axios.create({
    baseURL: "http://www.google.com.pk"
    });

    console.log(api.defaults.baseURL)


问:
PostgreSQL - Declaring a variable that can store multiple values
I need a way to declare a variable that can store multiple values. My first attempt was to declare a variable using the TABLE type:

```<code>DECLARE __id TABLE(results_id integer);
</code>```

However this didnt go as planned, giving me type-declaration errors. My next attempt was to make an integer[] type

```<code>DECLARE __id integer[];
</code>```

but it ended up giving me an error of that values needs to be inserted using curly braces whenever i attempted to insert them with a select function.

```<code>SELECT p.id FROM files.main p
WHERE p.reference = __reference
AND p.platform = __platform_id
INTO __id;
</code>```

I wonder if there is any way to solve this problem?

答:
i need an array to use them afterwards, where every result will be run in a function and the results will be inserted into a table object of same type – Crated

While you can do this with arrays and variables, it's simpler and faster to do it in a single query using an insert into select.

```<code>INSERT INTO some_other_table (some_column)
SELECT your_function(p.id)
FROM files.main p
WHERE p.reference = __reference
  AND p.platform = __platform_id
</code>```

This will run each matching p.id through your_function and insert the results as some_column in some_other_table.

Body:
I need a way to declare a variable that can store multiple values. My first attempt was to declare a variable using the TABLE type:

DECLARE __id TABLE(results_id integer);

However this didnt go as planned, giving me type-declaration errors. My next attempt was to make an integer[] type

DECLARE __id integer[];

but it ended up giving me an error of that values needs to be inserted using curly braces whenever i attempted to insert them with a select function.

SELECT p.id FROM files.main p
WHERE p.reference = __reference
AND p.platform = __platform_id
INTO __id;

I wonder if there is any way to solve this problem?

Body:
i need an array to use them afterwards, where every result will be run in a function and the results will be inserted into a table object of same type – Crated

While you can do this with arrays and variables, it's simpler and faster to do it in a single query using an insert into select.

INSERT INTO some_other_table (some_column)
SELECT your_function(p.id)
FROM files.main p
WHERE p.reference = __reference
  AND p.platform = __platform_id

This will run each matching p.id through your_function and insert the results as some_column in some_other_table.


问:
Redux form, clear and rest for one specific field, react JS
how would I specify in clear button, that i only need to reset the dropdown field and not everything else

```<code>import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'

let SelectingFormValuesForm = (props) => {
  const {
    favoriteColorValue, fullName, handleSubmit, hasEmailValue, pristine, reset, submitting
  } = props
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>First Name</label>
        <div>
          <Field name="firstName" component="input" type="text" placeholder="First Name"/>
        </div>
      </div>
      <div>
        <label>Last Name</label>
        <div>
          <Field name="lastName" component="input" type="text" placeholder="Last Name"/>
        </div>
      </div>
      <div>
        <label htmlFor="hasEmail">Has Email?</label>
        <div>
          <Field name="hasEmail" id="hasEmail" component="input" type="checkbox"/>
        </div>
      </div>
      {hasEmailValue && <div>
        <label>Email</label>
        <div>
          <Field name="email" component="input" type="email" placeholder="Email"/>
        </div>
      </div>}
      <div>
        <label>Favorite Color</label>
        <div>
          <Field name="favoriteColor" component="select">
            <option></option>
            <option value="#ff0000">Red</option>
            <option value="#00ff00">Green</option>
            <option value="#0000ff">Blue</option>
          </Field>
        </div>
      </div>
      {favoriteColorValue && <div style={{
        height: 80,
        width: 200,
        margin: '10px auto',
        backgroundColor: favoriteColorValue
      }}/>}
      <div>
        <button type="submit" disabled={pristine || submitting}>Submit {fullName}</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values
        </button>
      </div>
    </form>
  )
}
</code>```

https://redux-form.com/6.0.2/examples/selectingformvalues/

答:
If you use refux-form version 6.0.2 You can update it to the latest and use clearFields (doc)

clearFields(form:String, keepTouched: boolean, persistentSubmitErrors: boolean, ...fields:String)

Cleans fields values for all the fields passed in. Will reset to initialValue for each field if has any.

If the keepTouched parameter is true, the values of currently touched fields will be retained.

If the persistentSubmitErrors parameter is true, the values of currently submit errors fields will be retained

```<code>dispatch(clearFields('FORM_NAME', false, false, 'favoriteColor'));
</code>```

Body:
how would I specify in clear button, that i only need to reset the dropdown field and not everything else

import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'

let SelectingFormValuesForm = (props) => {
  const {
    favoriteColorValue, fullName, handleSubmit, hasEmailValue, pristine, reset, submitting
  } = props
  return (
    <form onSubmit={handleSubmit}>

        First Name

          <Field name="firstName" component="input" type="text" placeholder="First Name"/>

        Last Name

          <Field name="lastName" component="input" type="text" placeholder="Last Name"/>

        Has Email?

          <Field name="hasEmail" id="hasEmail" component="input" type="checkbox"/>

      {hasEmailValue &&

        Email

          <Field name="email" component="input" type="email" placeholder="Email"/>

}

        Favorite Color

          <Field name="favoriteColor" component="select">
            <option></option>
            <option value="#ff0000">Red</option>
            <option value="#00ff00">Green</option>
            <option value="#0000ff">Blue</option>
          </Field>

      {favoriteColorValue &&
}

        <button type="submit" disabled={pristine || submitting}>Submit {fullName}</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values
        </button>

    </form>
  )
}

https://redux-form.com/6.0.2/examples/selectingformvalues/

Body:
If you use refux-form version 6.0.2 You can update it to the latest and use clearFields (doc)

clearFields(form:String, keepTouched: boolean, persistentSubmitErrors: boolean, ...fields:String)

Cleans fields values for all the fields passed in. Will reset to initialValue for each field if has any.

If the keepTouched parameter is true, the values of currently touched fields will be retained.

If the persistentSubmitErrors parameter is true, the values of currently submit errors fields will be retained

dispatch(clearFields('FORM_NAME', false, false, 'favoriteColor'));


问:
Using a prvalue to create a shared_pointer
I have a class functionCombiner which constructor looks like this

```<code>FunctionCombiner::FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>> Inner_) : Inner(std::move(Inner_)), valuationFunction("", 0) //<- Needs to initalize itself even though it gets all data from inner functions.
{
}
</code>```

In my main class I'm calling it like this:

```<code>vector<std::shared_ptr<valuationFunction>> combinedStillFrontFunctions{ stillFrontStock, stillFrontEuropeanCall };
std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>(combinedStillFrontFunctions);
</code>```

What I would like to be able to do is reduce that to one line by constructing it in place like so

```<code>std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>({ stillFrontStock, stillFrontEuropeanCall });
</code>```

Which the compiler doesn't like. Is there a way to make this work? This works obviously:

```<code>FunctionCombiner StillFrontFunctions({ stillFrontStock, stillFrontEuropeanCall });
</code>```

But I need it to be a shared pointer.

答:
(Shorting some names to make the example readable w/o horizontal scrollbars.  You should consider doing the same...)

Passing {x,y} to make_shared() is attempting to forward a brace-enclosed initializer list, not to initialize the value in the shared pointer, but the temporary object its constructor takes.  It's not something that can be forwarded since it's not a full expression on its own.  So make a temporary vector with those values:

```<code>... = make_shared<FunComb>(vector<shared_ptr<valFun>>{FS, FEC});
</code>```

Another approach may be to change FunComb's constructor to be a (or add a new) variadic constructor, removing the need to pass in a vector just to hold the inputs.

Body:
I have a class functionCombiner which constructor looks like this

FunctionCombiner::FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>> Inner_) : Inner(std::move(Inner_)), valuationFunction("", 0) //<- Needs to initalize itself even though it gets all data from inner functions.
{
}

In my main class I'm calling it like this:

vector<std::shared_ptr<valuationFunction>> combinedStillFrontFunctions{ stillFrontStock, stillFrontEuropeanCall };
std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>(combinedStillFrontFunctions);

What I would like to be able to do is reduce that to one line by constructing it in place like so

std::shared_ptr<valuationFunction> StillFrontFunctions = std::make_shared<FunctionCombiner>({ stillFrontStock, stillFrontEuropeanCall });

Which the compiler doesn't like. Is there a way to make this work? This works obviously:

FunctionCombiner StillFrontFunctions({ stillFrontStock, stillFrontEuropeanCall });

But I need it to be a shared pointer.

Body:
(Shorting some names to make the example readable w/o horizontal scrollbars.  You should consider doing the same...)

Passing {x,y} to make_shared() is attempting to forward a brace-enclosed initializer list, not to initialize the value in the shared pointer, but the temporary object its constructor takes.  It's not something that can be forwarded since it's not a full expression on its own.  So make a temporary vector with those values:

... = make_shared<FunComb>(vector<shared_ptr<valFun>>{FS, FEC});

Another approach may be to change FunComb's constructor to be a (or add a new) variadic constructor, removing the need to pass in a vector just to hold the inputs.


问:
Pure SQL checklist format
I'm not sure if this is possible in SQL

I have the following tables

Below shows the list of all the food

Below shows who bought the items

Basically the user wants to display it as below

I want to use pure SQL because there is a function on my web api service to convert sqldatareader => datatable => CSV. So I don't have to manipulate the data on the api level.

答:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.food)
            FROM food c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'select *
                from buyer
            pivot
            (
                 COUNT(food)
                for food in (' + @cols + ')
            ) p '

execute(@query)

Title: Pure SQL checklist format


问:
Rows not copied to destination table from source table using oracle sqlplus copy command
I am using this copy command.

```<code>COPY FROM username/[pwd]@identifier INSERT SCHEMA_NAME.TABLE_NAME
USING SELECT * FROM SCHEMA_NAME.TABLE_NAME;
</code>```

Note : Both the source and target tables are in different databases. The source table has around 19 million records. Both tables have 198 columns.

and I am getting the below message when the copy command is executed (I am not seeing any error message but no rows are copied).

```<code>Array fetch/bind size is 5000. (arraysize is 5000)

Will commit after every 100 array binds. (copycommit is 100)

Maximum long size is 80. (long is 80)

   0 rows selected from username/[pwd]@identifier.

   0 rows inserted into SCHEMA_NAME.TABLE_NAME.

   0 rows committed into SCHEMA_NAME.TABLE_NAME at DEFAULT HOST connection.
</code>```

Please help me on this or any possible guidance to tackle above issue is deeply appreciated.

答:
I tried it on my local 11g XE database; it works OK.

```<code>SQL> create table test as select * From dept where 1 = 2;

Table created.

SQL> copy from scott/tiger@xe insert test using select * from dept;

Array fetch/bind size is 15. (arraysize is 15)
Will commit when done. (copycommit is 0)
Maximum long size is 80. (long is 80)
   4 rows selected from scott@xe.
   4 rows inserted into TEST.
   4 rows committed into TEST at DEFAULT HOST connection.

SQL> select * From test;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

SQL>
</code>```

Your query selected nothing and inserted nothing, which looks as if query doesn't do what you thought it would. Did you make sure that it is correctly written and that it fetches some rows?

As of disadvantages: Oracle 19c documentation says that

The COPY command will be deprecated in future releases of SQL*Plus. After Oracle 9i, no new datatypes are supported by COPY.

so you'd probably rather use other options to move data around. That would be e.g.

INSERT INTO

MERGE

data pump export & import

Body:
I am using this copy command.

COPY FROM username/[pwd]@identifier INSERT SCHEMA_NAME.TABLE_NAME
USING SELECT * FROM SCHEMA_NAME.TABLE_NAME;

Note : Both the source and target tables are in different databases. The source table has around 19 million records. Both tables have 198 columns.

and I am getting the below message when the copy command is executed (I am not seeing any error message but no rows are copied).

Array fetch/bind size is 5000. (arraysize is 5000)

Will commit after every 100 array binds. (copycommit is 100)

Maximum long size is 80. (long is 80)

   0 rows selected from username/[pwd]@identifier.

   0 rows inserted into SCHEMA_NAME.TABLE_NAME.

   0 rows committed into SCHEMA_NAME.TABLE_NAME at DEFAULT HOST connection.

Please help me on this or any possible guidance to tackle above issue is deeply appreciated.

Body:
I tried it on my local 11g XE database; it works OK.

SQL> create table test as select * From dept where 1 = 2;

Table created.

SQL> copy from scott/tiger@xe insert test using select * from dept;

Array fetch/bind size is 15. (arraysize is 15)
Will commit when done. (copycommit is 0)
Maximum long size is 80. (long is 80)
   4 rows selected from scott@xe.
   4 rows inserted into TEST.
   4 rows committed into TEST at DEFAULT HOST connection.

SQL> select * From test;

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

SQL>

Your query selected nothing and inserted nothing, which looks as if query doesn't do what you thought it would. Did you make sure that it is correctly written and that it fetches some rows?

As of disadvantages: Oracle 19c documentation says that

The COPY command will be deprecated in future releases of SQL*Plus. After Oracle 9i, no new datatypes are supported by COPY.

so you'd probably rather use other options to move data around. That would be e.g.

INSERT INTO

MERGE

data pump export & import


问:
What does re.compile(r'[[]]') match?
With Python's re module, why do the following act differently:</p>

```<code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code>```

答: and r'[][]' forms a character class {'[',']'}, and match either '[' or ']'.</p>

OwnerDisplayName: gray

ContentLicense: CC BY-SA 2.5

Title: What does re.compile(r'[[]]') match?

Body:
With Python's re module, why do the following act differently:

>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]

LastEditorDisplayName: dbr


问:
GridView doesn't refresh LINQ to XML data?
If have a Xml-file with 3 entries

Country Name="Denmark" InternetTLD="dk"

Country Name="Holland" InternetTLD="nl"

Country Name="Greate britain" InternetTLD="uk"

In my web-page if have a textbox, gridview and xmlDataSource.
When I don't specify anything in the textbox then all three countries are are loaded using a LINQ query into the xmlDataSource and then displayed in the gridview.
But when I specify for example 'Denmark' in the textbox then I keep on seeing all 3 records whereas the count property of the LINQ query says 1 and the Data-property of the xmlDataSource shows only 1 country as well (Denmark) as it should be.

Problem is that the gridView doesn't seem to refresh the new data???

Here's my code:

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        QueryXml();
    }  // Page_Load()

    private void QueryXml()
    {
        XElement _countries = XElement.Load(Server.MapPath(COUNTRIES_XML));
        IEnumerable<XElement> query = null;

        // extract all countries
        if (txtCountry.Text == "" || txtCountry.Text == "*")
        {
            query = from c in _countries.Elements()
                    select c;
        }
        else
        {
            // Extract all elements where Name has been specified
            query = from c in _countries.Elements()
                    where c.Attribute("Name").Value.ToString().StartsWith(txtCountry.Text, StringComparison.CurrentCultureIgnoreCase)
                    select c;
        }

        // Set xml filtered string data source
        xmlDsCountries.Data =
            "<Countries>" +
            string.Join("", query.Select(country => country.ToString())) +
            "</Countries>";
        // set the data source of the gridview
        gdvwCountries.DataSource = xmlDsCountries;
        // Show the data
        gdvwCountries.DataBind();

        lblMsg.Text = query.Count().ToString();
    }  // QueryXml()
</code>```

Why isn't the gridView refreshing?

thank you

Chris

答:
Try turning off caching on the XmlDataSource</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    xmlDsCountries.EnableCaching = false;
    //...........the rest.............
}
</code>```

Body:
If have a Xml-file with 3 entries

Country Name="Denmark" InternetTLD="dk"

Country Name="Holland" InternetTLD="nl"

Country Name="Greate britain" InternetTLD="uk"

In my web-page if have a textbox, gridview and xmlDataSource.
When I don't specify anything in the textbox then all three countries are are loaded using a LINQ query into the xmlDataSource and then displayed in the gridview.
But when I specify for example 'Denmark' in the textbox then I keep on seeing all 3 records whereas the count property of the LINQ query says 1 and the Data-property of the xmlDataSource shows only 1 country as well (Denmark) as it should be.

Problem is that the gridView doesn't seem to refresh the new data???

Here's my code:

    protected void Page_Load(object sender, EventArgs e)
    {
        QueryXml();
    }  // Page_Load()

    private void QueryXml()
    {
        XElement _countries = XElement.Load(Server.MapPath(COUNTRIES_XML));
        IEnumerable<XElement> query = null;

        // extract all countries
        if (txtCountry.Text == "" || txtCountry.Text == "*")
        {
            query = from c in _countries.Elements()
                    select c;
        }
        else
        {
            // Extract all elements where Name has been specified
            query = from c in _countries.Elements()
                    where c.Attribute("Name").Value.ToString().StartsWith(txtCountry.Text, StringComparison.CurrentCultureIgnoreCase)
                    select c;
        }

        // Set xml filtered string data source
        xmlDsCountries.Data =
            "<Countries>" +
            string.Join("", query.Select(country => country.ToString())) +
            "</Countries>";
        // set the data source of the gridview
        gdvwCountries.DataSource = xmlDsCountries;
        // Show the data
        gdvwCountries.DataBind();

        lblMsg.Text = query.Count().ToString();
    }  // QueryXml()

Why isn't the gridView refreshing?

thank you

Chris

Body:
Try turning off caching on the XmlDataSource

protected void Page_Load(object sender, EventArgs e)
{
    xmlDsCountries.EnableCaching = false;
    //...........the rest.............
}


问:
Which way of creating and updating a document is better in mongoose.js?
Which is a better way of saving a document so that it may not cause any error while using other methods of mongoose such as findOneAndUpdate()? </p>

```<code>const doc = new Doc();
// Some lines of the code
doc.save(...)
.then(...)
.catch(...);

           OR,

const doc = {};
//Some lines of code
Doc(doc).save()
.then(...)
.catch(...)
</code>```

答: Use doc.save() when creating a new document. And use findOneAndUpdate() when you are updating an existing document. They both don't cause any interference with each other.</p>

Body:
Which is a better way of saving a document so that it may not cause any error while using other methods of mongoose such as findOneAndUpdate()?

const doc = new Doc();
// Some lines of the code
doc.save(...)
.then(...)
.catch(...);

           OR,

const doc = {};
//Some lines of code
Doc(doc).save()
.then(...)
.catch(...)


问:
Flutter plugin not installed error; When running 'flutter doctor'
I am configuring the Flutter SDK on my Linux Ubuntu 16.04 (Xenial Xerus) system. Why am I getting the following error when I run the flutter doctor?

I have specified both PATHS for flutter and dart in the .bashrc file, but I get this error when I run flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.5.1, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 28.0.2)
[✓] Android Studio (version 3.1)
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] IntelliJ IDEA Community Edition (version 2018.2)
[!] VS Code (version 1.25.1)
[!] Connected devices
    ! No devices available

! Doctor found issues in 2 categories.
```

答:
I’ve just had this problem after an update and I solved it entering menu File → Settings → Plugins. Then at the top of the window there are two options: Marketplace and Installed. Then I clicked on Installed and on the Flutter plugin there’s was a message saying that the current version of Flutter does not support the new version of Android Studio, so there was a green button written “Restart”. Then I clicked and when it opened again, the problem disappeared.

It may not be the same for you, but many people will search for it here and it may help someone.


问:
Change/Update the CompletionKey

ULONG_PTR CKey = 2;  CreateIoCompletionPort(...Ckey...);

Is it possible to change/update the CompletionKey somehow after I called the function?
Also, an operation happening on both serversock and clientsock (E.g. AcceptEx in a mode that both accepts and receives) returns completion only for the server, can I change that to the Client or even better to both?

答:
Is it possible to change/update the CompletionKey somehow after I
  called the function?

this is possible begin from Windows 8.1

you need use NtSetInformationFile with FileReplaceCompletionInformation

Change or remove the I/O completion port for the specified file handle. The caller supplies a pointer to a
  FILE_COMPLETION_INFORMATION structure that specifies a port
  handle and a completion key. If the port handle is non-NULL, this
  handle specifies a new I/O completion port to associate with the file
  handle. To remove the I/O completion port associated with the file
  handle, set the port handle in the structure to NULL. To get a port
  handle, a user-mode caller can call the CreateIoCompletionPort
  function.

note that for initial set I/O completion port for the specified file handle we use FileCompletionInformation

however even if this is possible i think in most case will be wrong and not need do this

Title: Change/Update the CompletionKey


问:
Self-Signed CA not trusted in iOS 13 anymore
I created a Self-Signed CA and trust this certificate in Settings and it's working well in iOS 12. But after I upgrade the iOS version to 13, even the certificate trusted in Setting but still can't get it to working. So how do I fix this?</p>

答: I Happen to try something and it actually worked, Send the self signed .cer to the iphone with another configured email. The cert will be added to the iphone cert store. And Go to general setting then find Profil. Within the option you will see the name of the cert you just added and the option to configure it. Just do that in first place. Once done. Add the Exchange email account just like any other, it will prompt with certificate error but you will the option to continue and the account will be added correctly. I tried on Iphone 11 in the Mail App with Latest IOS. </p>


问:
REST PUT is that ok without key in the uri? instead put the key inside the body?
I am designing a REst API. our backend resource object has a combination as key, like account_number+product_type.

is that ok for PUT to update an account, use this
PUT: /accounts

```<code>{

account_number:1222;

product_type:sn,

;;;;

}
</code>```

I know standard way to use PUT with reference key in the uri, just wondering if without key will occur any issues?

答:
is that ok for PUT to update an account, use this PUT: /accounts

The potential problem is that the request doesn't mean what you think it does.

One of the constraints in the REST architectural style is uniform interface constraint; broadly, that means that everybody understands requests the same way.

PUT, in HTTP, is defined to mean: replace the state of the target resource with the representation enclosed in the message body of the http request.  See RFC 7231

A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.

In other words, when you create a request like

```<code>PUT  /accounts

{ "account_number":1222, ...
</code>```

You are saying that you want this block of JSON to be the thing returned when somebody sends a GET /accounts request.

What you probably want, from the your question, is to leave /accounts unchanged, and to actually be making changes to the /accounts/1222 resource.  But that's not what this request says.

The danger is not that your server will do the wrong thing - you control your server, and the server has a great deal of freedom about what it does in response to a request.

The real danger is that other general purpose components will do the wrong thing, because they will believe that the message means what it says it means, and not some other thing that only your server understands.

If the resulting confusion results in loss of property, everybody is going to (correctly) blame your server for its incorrect interpretation of the message semantics.

What kind of confusion are we talking about?  The specification of 204 No Content offers a hint: the client (and any other general purpose components) are permitted to assume that the meta data included in the 204 response apply to the target resource, which is to say the resource identified by the target-uri; in this example, the meta data will be applied to /accounts instead of the /accounts/1222.

Certainly, such a design is faulty; the fault may or may not lead to a failure.

In a project I maintained, I would immediately reject a pull-request when I discovered this fault.  It's right up there with needless breaking backwards compatibility.

Body:
I am designing a REst API. our backend resource object has a combination as key, like account_number+product_type.

is that ok for PUT to update an account, use this
PUT: /accounts

{

account_number:1222;

product_type:sn,

;;;;

}

I know standard way to use PUT with reference key in the uri, just wondering if without key will occur any issues?

Body:
is that ok for PUT to update an account, use this PUT: /accounts

The potential problem is that the request doesn't mean what you think it does.

One of the constraints in the REST architectural style is uniform interface constraint; broadly, that means that everybody understands requests the same way.

PUT, in HTTP, is defined to mean: replace the state of the target resource with the representation enclosed in the message body of the http request.  See RFC 7231

A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.

In other words, when you create a request like

PUT  /accounts

{ "account_number":1222, ...

You are saying that you want this block of JSON to be the thing returned when somebody sends a GET /accounts request.

What you probably want, from the your question, is to leave /accounts unchanged, and to actually be making changes to the /accounts/1222 resource.  But that's not what this request says.

The danger is not that your server will do the wrong thing - you control your server, and the server has a great deal of freedom about what it does in response to a request.

The real danger is that other general purpose components will do the wrong thing, because they will believe that the message means what it says it means, and not some other thing that only your server understands.

If the resulting confusion results in loss of property, everybody is going to (correctly) blame your server for its incorrect interpretation of the message semantics.

What kind of confusion are we talking about?  The specification of 204 No Content offers a hint: the client (and any other general purpose components) are permitted to assume that the meta data included in the 204 response apply to the target resource, which is to say the resource identified by the target-uri; in this example, the meta data will be applied to /accounts instead of the /accounts/1222.

Certainly, such a design is faulty; the fault may or may not lead to a failure.

In a project I maintained, I would immediately reject a pull-request when I discovered this fault.  It's right up there with needless breaking backwards compatibility.


问:
Firebase: Retrieve Daily Active Users via API
I am wondering whether there is a way to retrieve the data that is displayed in the firebase console, such as daily user per day etc, via an API:

Use case is that we want to create one unified dashboard and don't want to jump between applications and give everyone access to everything.

Did I miss something in the docs?

Best

Philipp

答:
No, there is no public API for Analytics data that you see in the console.

Your only supported option to get a hold of that data is through an export to BigQuery.  After that, you will have access to all the raw data to build your own dashboard.


答:
```<code>import boto3

client = boto3.client('s3')
bucket_name = "bucket_name"
prefix = ""

s3 = boto3.client("s3")

result = client.list_objects(Bucket=bucket_name, Delimiter='/')
   for obj in result.get('CommonPrefixes'):
       prefix = obj.get('Prefix')
       file_list = ListFiles(client,bucket_name,prefix)
       for file in file_list:
          if "processed/files" in file:
              print("Found",file)

def ListFiles(client, bucket_name, prefix):
    _BUCKET_NAME = bucket_name
    _PREFIX = prefix
    """List files in specific S3 URL"""
    response = client.list_objects(Bucket=_BUCKET_NAME, Prefix=_PREFIX)

    for content in response.get('Contents', []):
        #print(content)
        yield content.get('Key')

</code>```

]1

Title: search in each of the s3 bucket and see if the given folder exists

Body:
I'm trying to get the files from specific folders in s3 Buckets:

I have 4 buckets in s3 with the following names:

1 - 'PDF'
2 - 'TXT'
3 - 'PNG'
4 - 'JPG'

The folder structure for all s3 buckets looks like this:

1- PDF/analysis/pdf-to-img/processed/files
2- TXT/report/processed/files
3- PNG/analysis/reports/png-to-txt/processed/files
4- JPG/jpg-to-txt/empty

I have to check if this folder prefix processed/files is present in the bucket, and if it is present, I'll read the files present in those directories, else I'll ignore them.

Code:

buckets = ['PDF','TXT','PNG','JPG']

client = boto3.client('s3')
for i in bucket:
    result = client.list_objects(Bucket=i,Prefix = 'processed/files', Delimiter='/')
    print(result)

I can enter into each directory if the folder structure is same, but how can I handle this when the folder structure varies for each bucket?

Body:
import boto3

client = boto3.client('s3')
bucket_name = "bucket_name"
prefix = ""

s3 = boto3.client("s3")

result = client.list_objects(Bucket=bucket_name, Delimiter='/')
   for obj in result.get('CommonPrefixes'):
       prefix = obj.get('Prefix')
       file_list = ListFiles(client,bucket_name,prefix)
       for file in file_list:
          if "processed/files" in file:
              print("Found",file)

def ListFiles(client, bucket_name, prefix):
    _BUCKET_NAME = bucket_name
    _PREFIX = prefix
    """List files in specific S3 URL"""
    response = client.list_objects(Bucket=_BUCKET_NAME, Prefix=_PREFIX)

    for content in response.get('Contents', []):
        #print(content)
        yield content.get('Key')

]1


问:
validation: date today in javascript
I have a problem with the today date. I have 2 checkings.

-The first validation is to avoid that the user enters a previous date to the today date. (my validation is ok)

-My second validation is to limit the dates to 2 years maximum (my validation is ok also)

My problem is that if I enter the today date, I get an error message. Normally, my date must be ok.

I think my problem is here?

```<code>const inputDate = new Date(date_start);
const today = new Date();

if (inputDate < today) {
    document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
    return false;
}
</code>```

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date();

    if (inputDate < today) {
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const yearFromImputDate = inputDate.getFullYear();

    const now = new Date();
    const twoYearsFromNow = now.getFullYear() + 2;

    if(yearFromImputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>
</body>
</html></code>```

答:
you have that ** Obsolete date ! on today's date because inputDate is in UTC and your today is in local time hence why it will trigger the error message to fix this
convert Local time to UTC or vice versa
or set hours minutes and seconds to 0 for both and then compare them </p>

```<code>    today= new Date()
        const myToday = new Date(today.getFullYear(), today.getMonth(),
        today.getDate(), 0, 0, 0);

    //OR use getTimezoneOffset it will return the difference from UTC and your local time
    currentTimeZoneOffsetInHours = date.getTimezoneOffset() / 60
    let offset= currentTimeZoneOffsetInHours*3600000
 // and then remove offset from your local time
     today= Date.now
     let localtimeinUTC=today-offset
//and then you compare the time  localtimeinUTC with your inputTime
</code>```

<p>but i suggest you use the first approach as it simpler </p>

Title: validation: date today in javascript

Body:
I have a problem with the today date. I have 2 checkings.

-The first validation is to avoid that the user enters a previous date to the today date. (my validation is ok)

-My second validation is to limit the dates to 2 years maximum (my validation is ok also)

My problem is that if I enter the today date, I get an error message. Normally, my date must be ok.

I think my problem is here?

const inputDate = new Date(date_start);
const today = new Date();

if (inputDate < today) {
    document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
    return false;
}

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start);
    const today = new Date();

    if (inputDate < today) {
        document.getElementById('date_startError').innerHTML = " ** Obsolete date ! ";
        return false;
    }

    const yearFromImputDate = inputDate.getFullYear();

    const now = new Date();
    const twoYearsFromNow = now.getFullYear() + 2;

    if(yearFromImputDate > twoYearsFromNow) {
        document.getElementById('date_startError').innerHTML = " ** Maximum 2 years ! ";
        return false;
    }

}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">

<form action="#" onsubmit="return validation()" >

  Date start :

  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">

  <input type="submit" value="ok">
</form>

Body:
you have that ** Obsolete date ! on today's date because inputDate is in UTC and your today is in local time hence why it will trigger the error message to fix this
convert Local time to UTC or vice versa
or set hours minutes and seconds to 0 for both and then compare them

    today= new Date()
        const myToday = new Date(today.getFullYear(), today.getMonth(),
        today.getDate(), 0, 0, 0);

    //OR use getTimezoneOffset it will return the difference from UTC and your local time
    currentTimeZoneOffsetInHours = date.getTimezoneOffset() / 60
    let offset= currentTimeZoneOffsetInHours*3600000
 // and then remove offset from your local time
     today= Date.now
     let localtimeinUTC=today-offset
//and then you compare the time  localtimeinUTC with your inputTime

but i suggest you use the first approach as it simpler


问:
TensorFlow: Converting SavedModel.pb file to .tflite using Tensorflow 2.2.0

OS: Windows 10

Tensorflow Version: 2.2.0

Model Type: SavedModel (.pb)

Desired Model Type: Tensorflow Lite (.tflite)

I have been going in endless circles trying to find a python script or a command line function to convert a .pb file to .tflite. I have tried using the tflite_convert, but it returns with the error:

OSError: SavedModel file does not exist at: C:/tensorflowTraining/export_dir/saved_model.pb/{saved_model.pbtxt|saved_model.pb}

I have also tried some scripts like:

```<code>import tensorflow as to

gf = tf.compat.v1.GraphDef()

m_file = open('saved_model.pb', 'rb')

gf.ParseFromString(m_file.read())

with open('somefile.txt', 'a') as the_file:

    for n in gf.node:

        the_file.write(n.name+'\n')

file = open('somefile.txt', 'r')

data = file.readlines()

print("output name = ")

print(data[len(data)-1])

print("Input name = ")

file.seek(0)

print(file.readline())
</code>```

This returns:

Exception has occurred: DecodeError

Unexpected end-group tag.

This error happens in line 4:

```<code> gf.ParseFromString(m_file.read())
</code>```

It would be really helpful if someone could provide a working script or command line function as many I have researched return errors or do not function properly.

Thank you!

答:
You can try something like below with TF2.2.

```<code>import tensorflow as tf
graph_def_file = "./saved_model.pb"
tflite_file = 'mytflite.tflite'

input_arrays = ["input"]. # you need to change it based on your model
output_arrays = ["output"] # you need to change it based on your model
print("{} -> {}".format(graph_def_file, tflite_file))
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file=graph_def_file,
  input_arrays=input_arrays,
  output_arrays=output_arrays,input_shapes={'input_mel':[ 1, 50, 80]})
# If there are multiple inputs, then update the dictionary above
tflite_model = converter.convert()
open(tflite_file,'wb').write(tflite_model)
</code>```

In the above code, you need to use input_arrays, output_arrays, and input_shapes corresponding to your model.

Body:
OS: Windows 10

Tensorflow Version: 2.2.0

Model Type: SavedModel (.pb)

Desired Model Type: Tensorflow Lite (.tflite)

I have been going in endless circles trying to find a python script or a command line function to convert a .pb file to .tflite. I have tried using the tflite_convert, but it returns with the error:

OSError: SavedModel file does not exist at: C:/tensorflowTraining/export_dir/saved_model.pb/{saved_model.pbtxt|saved_model.pb}

I have also tried some scripts like:

import tensorflow as to

gf = tf.compat.v1.GraphDef()

m_file = open('saved_model.pb', 'rb')

gf.ParseFromString(m_file.read())

with open('somefile.txt', 'a') as the_file:

    for n in gf.node:

        the_file.write(n.name+'\n')

file = open('somefile.txt', 'r')

data = file.readlines()

print("output name = ")

print(data[len(data)-1])

print("Input name = ")

file.seek(0)

print(file.readline())

This returns:

Exception has occurred: DecodeError

Unexpected end-group tag.

This error happens in line 4:

 gf.ParseFromString(m_file.read())

It would be really helpful if someone could provide a working script or command line function as many I have researched return errors or do not function properly.

Thank you!

Body:
You can try something like below with TF2.2.

import tensorflow as tf
graph_def_file = "./saved_model.pb"
tflite_file = 'mytflite.tflite'

input_arrays = ["input"]. # you need to change it based on your model
output_arrays = ["output"] # you need to change it based on your model
print("{} -> {}".format(graph_def_file, tflite_file))
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file=graph_def_file,
  input_arrays=input_arrays,
  output_arrays=output_arrays,input_shapes={'input_mel':[ 1, 50, 80]})
# If there are multiple inputs, then update the dictionary above
tflite_model = converter.convert()
open(tflite_file,'wb').write(tflite_model)

In the above code, you need to use input_arrays, output_arrays, and input_shapes corresponding to your model.


问:
Change form_field.required inside UpdateView.form_valid
I have a field with blank=True. Inside my UpdateView form_valid method i have an if condition. Is it possible to make it so, if if cond == False, the form will act as if the field is required and throw a prompt to fill-in the field, and not a sever error.

UPDATE

The logic looks like this:

```<code>get template.checkbox.value
if template.checkbox.value is TRUE:
  if FIELD is empty:
    if SOME OTHER CONDITION FAILS:
      MAKE FIELD REQUIRED
</code>```

答: If I understand you correctly, you want to have 2 fields such that the validation of one depends on the other, correct?  If so, then you want to use a clean() method to check the 2 fields and then add a validation error on the fields you want a message to appear on.

Body:
I have a field with blank=True. Inside my UpdateView form_valid method i have an if condition. Is it possible to make it so, if if cond == False, the form will act as if the field is required and throw a prompt to fill-in the field, and not a sever error.

UPDATE

The logic looks like this:

get template.checkbox.value
if template.checkbox.value is TRUE:
  if FIELD is empty:
    if SOME OTHER CONDITION FAILS:
      MAKE FIELD REQUIRED


问:
Python: Extending a predefined named tuple
I have the following named tuple:

```<code>from collections import namedtuple
ReadElement = namedtuple('ReadElement', 'address value')
</code>```

and then I want the following:

```<code>LookupElement = namedtuple('LookupElement', 'address value lookups')
</code>```

There is duplication between the two namedtuples, how can I subclass ReadElement to contain an additional field?

```<code>class LookupElement(ReadElement):
    def __new__(self, address, value, lookups):
        self = super(LookupElement, self).__new__(address, value)
        l = list(self)
        l.append(lookups)
        return tuple(l)
</code>```

However the tuple is created there an then in the new statement, if I modify self to be a list I will loose type information, how can I avoid this?

答:
Extending Martijn Pieters' answer: there is a way to make the new namedtuple class a subclass of the other, without having to hack. Simply create the new namedtuple separately, and then use its __new__ method instead of using super:

```<code>from collections import namedtuple

class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
    def compute(self):
        return self.value + 1

_LookupElement = namedtuple('_LookupElement', ReadElement._fields + ('lookups',))

class LookupElement(_LookupElement, ReadElement):
    def __new__(self, address, value, lookups):
        return _LookupElement.__new__(LookupElement, address, value, lookups)

assert issubclass(LookupElement, ReadElement)
l = LookupElement('ad', 1, dict())
assert isinstance(l, ReadElement)
assert l.compute() == 2
</code>```

It seems that this also works without even overriding __new__ !

```<code>from collections import namedtuple

class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
    def compute(self):
        return self.value + 1

class LookupElement(namedtuple('LookupElement', ReadElement._fields + ('lookups',)),
                    ReadElement):
    """nothing special to do"""
    pass
</code>```

Body:
I have the following named tuple:

from collections import namedtuple
ReadElement = namedtuple('ReadElement', 'address value')

and then I want the following:

LookupElement = namedtuple('LookupElement', 'address value lookups')

There is duplication between the two namedtuples, how can I subclass ReadElement to contain an additional field?

class LookupElement(ReadElement):
    def __new__(self, address, value, lookups):
        self = super(LookupElement, self).__new__(address, value)
        l = list(self)
        l.append(lookups)
        return tuple(l)

However the tuple is created there an then in the new statement, if I modify self to be a list I will loose type information, how can I avoid this?

Body:
Extending Martijn Pieters' answer: there is a way to make the new namedtuple class a subclass of the other, without having to hack. Simply create the new namedtuple separately, and then use its __new__ method instead of using super:

from collections import namedtuple

class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
    def compute(self):
        return self.value + 1

_LookupElement = namedtuple('_LookupElement', ReadElement._fields + ('lookups',))

class LookupElement(_LookupElement, ReadElement):
    def __new__(self, address, value, lookups):
        return _LookupElement.__new__(LookupElement, address, value, lookups)

assert issubclass(LookupElement, ReadElement)
l = LookupElement('ad', 1, dict())
assert isinstance(l, ReadElement)
assert l.compute() == 2

It seems that this also works without even overriding __new__ !

from collections import namedtuple

class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
    def compute(self):
        return self.value + 1

class LookupElement(namedtuple('LookupElement', ReadElement._fields + ('lookups',)),
                    ReadElement):
    """nothing special to do"""
    pass


问:
Swift - Hide & Show Object
When I press the button hide to my text, after I press button to show my text. Where is my fault? My English very bad, sorry...</p>

```<code>@IBOutlet weak var myHiddenText: UILabel!

@IBAction func showBtn(sender: AnyObject) {
  myHiddenText.hidden = true

  if myHiddenText.hidden == true {
    myHiddenText.hidden = false
  }

  if myHiddenText.hidden == false {
    myHiddenText.hidden = true
  }

}
</code>```

答:
With UIKitPlus library you can do it simply like this

class MyViewController: ViewController {
    @State var hiddency = false

    override func buildUI() {
        super.buildUI()
        body {
            VStack {
                View().height(10).background(.red).hidden($hiddency)
                View().height(10).background(.green).hidden($hiddency)
                View().height(10).background(.blue).hidden($hiddency)
                Button("toggle").onTapGesture {
                    self.hiddency.toggle()
                }
            }
        }
    }
}
```

Take a look at it, it works since iOS9+ and have LivePreview.

Title: Swift - Hide & Show Object

Body:
When I press the button hide to my text, after I press button to show my text. Where is my fault? My English very bad, sorry...

@IBOutlet weak var myHiddenText: UILabel!

@IBAction func showBtn(sender: AnyObject) {
  myHiddenText.hidden = true

  if myHiddenText.hidden == true {
    myHiddenText.hidden = false
  }

  if myHiddenText.hidden == false {
    myHiddenText.hidden = true
  }

}

Body:
With UIKitPlus library you can do it simply like this

class MyViewController: ViewController {
    @State var hiddency = false

    override func buildUI() {
        super.buildUI()
        body {
            VStack {
                View().height(10).background(.red).hidden($hiddency)
                View().height(10).background(.green).hidden($hiddency)
                View().height(10).background(.blue).hidden($hiddency)
                Button("toggle").onTapGesture {
                    self.hiddency.toggle()
                }
            }
        }
    }
}

Take a look at it, it works since iOS9+ and have LivePreview.


问:
How to find all child processes?
In a Linux-based project that I am working on, I need to be able to find all of my child processes. It is not feasible to record every time one is started -- they need to be found after the fact. This needs to be pure C, and I'd like to do it without reading /proc. Does anyone know how to do this?

答:
The code in this repository will need to be adjusted to be written in plain C to meet your request, and if you are ok with doing so, if you remove all the unused functionality from my repository within your project, it shouldnt be that hard to translate into plain C.

But this is more useful for people looking to support multiple platforms and/or who prefer C++.

See the function pids_from_ppid(ppid)
https://github.com/time-killer-games/enigma-dev/blob/548dc16e96a2a32f8ad9045a4ee18b0206516e62/ENIGMAsystem/SHELL/Universal_System/Extensions/ProcInfo/procinfo.h#L101

Returns a string with each child process id separated by a pipe "|" character as the delimiter.

Ubuntu and debian users need libprocps-dev installed for missing headers.

sudo apt-get install libprocps-dev libx11-dev

The libx11-dev dependency is optional because all X11 code in the source can be omitted and the question here will still be answered, so if you need wayland and no X11 support you should remove X11 related code as it's unrelated to this question anyway.

For those who actually like/need X11 and/or C++ this will work out of the box on Windows, Mac, Linux, and FreeBSD. Support for other BSD's is not as easily viable thanks to relying on the libutil dependency. But it just uses sysctl() internally so in theory you should be able to compile the source code for libutil on the other BSD's available from FreeBSD's github repository, and then link to it after you have built it.

Title: How to find all child processes?