问:
What could be the possible cause of the Netty Decompression Exception: CRC value mismatch?
I have a service that consumes a flux of integers produced by another microservice through a WebClient (org.springframework.web.reactive.function.client.WebClient), and from time to time encounters below exception. What could be the possible cause of it?</p>

```<code>io.netty.handler.codec.compression.DecompressionException: CRC value mismatch. Expected: 3453327130, Got: 1861228094
 at io.netty.handler.codec.compression.JdkZlibDecoder.verifyCrc(JdkZlibDecoder.java:387) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.compression.JdkZlibDecoder.readGZIPFooter(JdkZlibDecoder.java:365) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.compression.JdkZlibDecoder.decode(JdkZlibDecoder.java:219) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:503) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:442) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:281) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.embedded.EmbeddedChannel.writeInbound(EmbeddedChannel.java:343) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:254) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decodeContent(HttpContentDecoder.java:161) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:150) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:47) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:88) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:326) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:300) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1478) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1227) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1274) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:503) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:442) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:281) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:502) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:407) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_141]
</code>```

答: So the possible cause could be that the data packets are corrupted before arriving to the client side for decompression. There should be nothing wrong with Netty.</p>

Body:
I have a service that consumes a flux of integers produced by another microservice through a WebClient (org.springframework.web.reactive.function.client.WebClient), and from time to time encounters below exception. What could be the possible cause of it?

io.netty.handler.codec.compression.DecompressionException: CRC value mismatch. Expected: 3453327130, Got: 1861228094
 at io.netty.handler.codec.compression.JdkZlibDecoder.verifyCrc(JdkZlibDecoder.java:387) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.compression.JdkZlibDecoder.readGZIPFooter(JdkZlibDecoder.java:365) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.compression.JdkZlibDecoder.decode(JdkZlibDecoder.java:219) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:503) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:442) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:281) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.embedded.EmbeddedChannel.writeInbound(EmbeddedChannel.java:343) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:254) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decodeContent(HttpContentDecoder.java:161) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:150) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.http.HttpContentDecoder.decode(HttpContentDecoder.java:47) ~[netty-codec-http-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:88) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:326) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:300) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1478) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1227) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1274) ~[netty-handler-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:503) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:442) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:281) ~[netty-codec-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360) [netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931) ~[netty-transport-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:502) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:407) ~[netty-transport-native-epoll-4.1.43.Final-linux-x86_64.jar!/:4.1.43.Final]
 at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.43.Final.jar!/:4.1.43.Final]
 at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_141]


来源: stackexchange

问:
Get the last string printed in C/C++
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}
```

<p>and then the tester:</p>

<pre class="lang-cpp prettyprint-override"><code>TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}
</code>```

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

答:
There is a solution ( in C ) for an API call ( cmd_rsp ) with source code here, that when called in your program, creates a separate process, and pipes to both stdin and stdout, from which it accepts a  command and returns the response via an auto sizing buffer. Similar in concept to popen(...).

A simple use case:

```<code>char *buf = NULL;

/// test cmd_rsp
buf = calloc(BUF_SIZE, 1);
if(!buf)return 0;
if (!cmd_rsp("dir /s", &buf, BUF_SIZE))//note the first argument can be any legal command that
                                       //can be sent via the CMD prompt in windows,
                                       //including a custom executable
{
    printf("%s", buf);
}
else
{
    printf("failed to send command.\n");
}
free(buf);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get the last string printed in C/C++

Body:
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}

and then the tester:

TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

Body:
There is a solution ( in C ) for an API call ( cmd_rsp ) with source code here, that when called in your program, creates a separate process, and pipes to both stdin and stdout, from which it accepts a  command and returns the response via an auto sizing buffer. Similar in concept to popen(...).

A simple use case:

char *buf = NULL;

/// test cmd_rsp
buf = calloc(BUF_SIZE, 1);
if(!buf)return 0;
if (!cmd_rsp("dir /s", &buf, BUF_SIZE))//note the first argument can be any legal command that
                                       //can be sent via the CMD prompt in windows,
                                       //including a custom executable
{
    printf("%s", buf);
}
else
{
    printf("failed to send command.\n");
}
free(buf);


问:
Find and rename unhide files to dot files (hide files)
I'm writting my dotfiles and i want to want to find unhide files in arborescence structure, after make a symbolic link into my home directory.

```<code>for f in `find ../dotfiles -mindepth 2 -type f`; do ln -sfn "${f}" ".${f}"; done
</code>```

but this code failed

enter image description here

答:
Look closer at your error log, find complains about paths like .../dotfiles/rest/of/the/path, where the three leading dots are the result of the expansion of .${f}. Since you said you wanted copies in your home directory, the desired expansion would be ~/.path (or maybe ./.path would work too, assuming you're executing find from your home directory).

A solution to that problem would be to use basename to strip the leading directories from the full file path :

```<code>for f in `find ../dotfiles -mindepth 2 -type f`; do
    filename="$(basename "$f")"
    ln -sfn "${f}" "~/.$filename"
done
</code>```

However the way you iterate over the output of find is prone to breaking over IFS : if one of the matched files contains a space for instance, it will be iterated over as two distinct elements. We might as well fix that too :

```<code>find ../dotfiles -mindepth 2 -type f -print0 | while IFS='' read -r -d $'\0' f; do
    filename="$(basename "$f")"
    ln -sfn "${f}" "~/.$filename"
done
</code>```

In this code, we use find's -print0 action to delimit its results with the ASCII NUL \0, which can't be found in filenames. Then we iterate over the output of find with a while/read loop that uses that same delimiter. This way we're guaranteed to never choke because of an unexpected character in any filename.

Body:
I'm writting my dotfiles and i want to want to find unhide files in arborescence structure, after make a symbolic link into my home directory.

for f in `find ../dotfiles -mindepth 2 -type f`; do ln -sfn "${f}" ".${f}"; done

but this code failed

enter image description here

Body:
Look closer at your error log, find complains about paths like .../dotfiles/rest/of/the/path, where the three leading dots are the result of the expansion of .${f}. Since you said you wanted copies in your home directory, the desired expansion would be ~/.path (or maybe ./.path would work too, assuming you're executing find from your home directory).

A solution to that problem would be to use basename to strip the leading directories from the full file path :

for f in `find ../dotfiles -mindepth 2 -type f`; do
    filename="$(basename "$f")"
    ln -sfn "${f}" "~/.$filename"
done

However the way you iterate over the output of find is prone to breaking over IFS : if one of the matched files contains a space for instance, it will be iterated over as two distinct elements. We might as well fix that too :

find ../dotfiles -mindepth 2 -type f -print0 | while IFS='' read -r -d $'\0' f; do
    filename="$(basename "$f")"
    ln -sfn "${f}" "~/.$filename"
done

In this code, we use find's -print0 action to delimit its results with the ASCII NUL \0, which can't be found in filenames. Then we iterate over the output of find with a while/read loop that uses that same delimiter. This way we're guaranteed to never choke because of an unexpected character in any filename.


问:
Get Selected Radio Button WITHOUT a Submit button
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

```<code>document.getElementById("results").innerHTML = NONE or A or B
</code>```

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

```

答:
$( document ).ready(function() {
    console.log( "ready!" );
    $("input[name='test']").change(function(){
      $("#results").text($("input[name='test']:checked").val());
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="testNONE" autocomplete="off" value="NONE">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testA" autocomplete="off" value="A">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testB" autocomplete="off" value="B">B
  </label>
</div>

<div id="results"></div></code>```

Body:
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

document.getElementById("results").innerHTML = NONE or A or B

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

Body:
$( document ).ready(function() {
    console.log( "ready!" );
    $("input[name='test']").change(function(){
      $("#results").text($("input[name='test']:checked").val());
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="testNONE" autocomplete="off" value="NONE">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testA" autocomplete="off" value="A">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="testB" autocomplete="off" value="B">B
  </label>
</div>

<div id="results"></div>


问:
php merge json arrays into one array
I am trying to loop through some json files, and combine them into one json file. My plan is to have a global $allData array, and just merge new candidates into them.

```<code><?php
$allData = array();
$count = 0;
if ($handle = opendir('./json/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {

            echo $entry."<br />";

            $source_file = file_get_contents('./json/'.$entry);

            $data = json_decode($source_file,TRUE);

            if($data != null){

                $allData = array_merge($allData,$data);
                echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />";
                print_r($allData);

            }
            else{
                echo "Invalid Json File";
            } //end else
        }
closedir($handle);
}

echo "<br /><br /><br /><br /> !!!! <br /><br /><br /><br />";

print_r($allData);
</code>```

However, the merge is overwriting the file. How can I combine multiple json files into one?

I would like the following result:

1.json:

```<code>{"date":"10"},{"comment":"some comment"},{"user":"john"}
</code>```

2.json:

```<code>{"date":"11"},{"comment":"another quote"},{"comment":"jim"}
</code>```

combined.json

```<code>[{"date":"10"},{"comment":"some comment"},{"user":"john"},
{"date":"11"},{"comment":"another quote"},{"comment":"jim"}]
</code>```

I am only getting one of these values after I merge the arrays.

```<code>[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]
</code>```

答: My solution is a bad one but it works: I replace the } of string one with a comma, remove the { of the second string and concatenate those two strings...</p>

ContentLicense: CC BY-SA 3.0

Title: php merge json arrays into one array

Body:
I am trying to loop through some json files, and combine them into one json file. My plan is to have a global $allData array, and just merge new candidates into them.

<?php
$allData = array();
$count = 0;
if ($handle = opendir('./json/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {

            echo $entry."
";

            $source_file = file_get_contents('./json/'.$entry);

            $data = json_decode($source_file,TRUE);

            if($data != null){

                $allData = array_merge($allData,$data);
                echo "

 !!!!

";
                print_r($allData);

            }
            else{
                echo "Invalid Json File";
            } //end else
        }
closedir($handle);
}

echo "

 !!!!

";

print_r($allData);

However, the merge is overwriting the file. How can I combine multiple json files into one?

I would like the following result:

1.json:

{"date":"10"},{"comment":"some comment"},{"user":"john"}

2.json:

{"date":"11"},{"comment":"another quote"},{"comment":"jim"}

combined.json

[{"date":"10"},{"comment":"some comment"},{"user":"john"},
{"date":"11"},{"comment":"another quote"},{"comment":"jim"}]

I am only getting one of these values after I merge the arrays.

[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]


问:
Similarity function in Ruby on Rails
For example I have a string VOLVO EW 160 C NEUER MOTOR / NEW ENG. Where VOLVO - is a brand, and EW 160 is a model.

And I have a two tables with Brands and Models.
Models table, for example, delimited by comma ,: EW, E, W, S, C, Z, 10, 16, 1.6, 10, 150, 160, EW160, EW 160.

How i can detect which is the model? Searched some documentation about same function in PostgreSQL.

RoR have some Similarity function, or what is the best way to detect similar strings?

What is the more flexible/productive way? (PostgreSQL or RoR)

UPD:
Other string example: VOLVO EW-160 1999, 9000 operating hours. Where the model is EW-160, but in database i have not this model, but have similar models EW160 or EW 160

答:
assuming the best match is the longest one that is included in string:</p>

```<code>string = 'VOLVO EW 160 C NEUER MOTOR / NEW ENG'
models = ['EW', 'E', 'W', 'S', 'C', 'Z', '10', '16', '1.6', '10', '150', '160', 'EW160', 'EW 160']

matching_models = models.select{ |m| string.include? m }

best_match = matching_models.max_by(&:length)
</code>```

Title: Similarity function in Ruby on Rails

Body:
assuming the best match is the longest one that is included in string:

string = 'VOLVO EW 160 C NEUER MOTOR / NEW ENG'
models = ['EW', 'E', 'W', 'S', 'C', 'Z', '10', '16', '1.6', '10', '150', '160', 'EW160', 'EW 160']

matching_models = models.select{ |m| string.include? m }

best_match = matching_models.max_by(&:length)


问:
AngularJs : injected a constant into a controller - how to access it in the controller's view?
In app.js, I have

```<code>(function ()
{
    angular.module('routerDemo',
        [
             'ui.router',   // Routing
         ])

})();

angular.module('routerDemo').constant('constants',  { blip: 'blop', blup: 307 });
angular.module('routerDemo').constant('another_constant',  42);
</code>```

and in controller_1.js

```<code>Controller_1.$inject = ['$rootScope', '$state', 'constants', 'another_constant'];

function Controller_1(   $rootScope,   $state,   constants,   another_constant)
{
</code>```

and in the view

```<code><div ng-controller="Controller_1 as controller_1">
    <h1>This is view 1</h1>

    <div>Controller_1.constants.blip == {{controller_1.constants.blip}}</div>
    <div>Controller_1.the_answer == {{controller_1.another_constant}}</div>
</code>```

but they display as blank (although I can view them if I breakpoint in the controller, so it's just a matter of the syntax in the view)).

What am I doing wrong?

答:
Just assign the constants to this inside your controller

```<code>// controller_1
function Controller_1($rootScope, $state, constants, another_constant){
    this.constants = constants;
    this.another_constant = another_constant;
}

// view
<div ng-controller="Controller_1 as controller_1">
<h1>This is view 1</h1>

<div>Controller_1.constants.blip == {{controller_1.constants.blip}}</div>
<div>Controller_1.the_answer == {{controller_1.another_constant}}</div>
</div>
</code>```

Body:
In app.js, I have

(function ()
{
    angular.module('routerDemo',
        [
             'ui.router',   // Routing
         ])

})();

angular.module('routerDemo').constant('constants',  { blip: 'blop', blup: 307 });
angular.module('routerDemo').constant('another_constant',  42);

and in controller_1.js

Controller_1.$inject = ['$rootScope', '$state', 'constants', 'another_constant'];

function Controller_1(   $rootScope,   $state,   constants,   another_constant)
{

and in the view

This is view 1

Controller_1.constants.blip == {{controller_1.constants.blip}}

Controller_1.the_answer == {{controller_1.another_constant}}

but they display as blank (although I can view them if I breakpoint in the controller, so it's just a matter of the syntax in the view)).

What am I doing wrong?

Body:
Just assign the constants to this inside your controller

// controller_1
function Controller_1($rootScope, $state, constants, another_constant){
    this.constants = constants;
    this.another_constant = another_constant;
}

// view
<div ng-controller="Controller_1 as controller_1">
<h1>This is view 1</h1>

<div>Controller_1.constants.blip == {{controller_1.constants.blip}}</div>
<div>Controller_1.the_answer == {{controller_1.another_constant}}</div>
</div>


问:
SQL Window function, count the number of events in a 180 day window using each event date as an index
I need to be able to find the minimum date out of a set of dates that fit the following criteria.

3 dates which are within 180 days of each other. The logic which i'm guessing would apply is that each date would be an index from which subsequent dates are compared to. I can do this using the LAG and Window functions if there are two dates. but the requirement is to find the minimum date where 3 events fit into a 180 day window and grouped by the GROUP_ID.

The test data is:

```<code>DROP TABLE #EVENT_COUNT
CREATE TABLE #EVENT_COUNT
(
    [DATE]    DATE
    ,[GROUP_ID]    INT

);

INSERT INTO #EVENT_COUNT
SELECT '2011-01-01',1
UNION ALL SELECT '2011-02-01',1 UNION ALL SELECT '2011-03-01',1
UNION ALL SELECT '2011-04-01',1 UNION ALL SELECT '2011-05-01',1
UNION ALL SELECT '2011-06-01',1 UNION ALL SELECT '2011-07-01',1
UNION ALL SELECT '2011-08-01',1 UNION ALL SELECT '2011-09-01',1
UNION ALL SELECT '2011-10-01',1 UNION ALL SELECT '2011-11-01',1
UNION ALL SELECT '2011-12-01',2 UNION ALL SELECT '2012-01-01',2
UNION ALL SELECT '2012-02-01',2 UNION ALL SELECT '2012-03-01',2
UNION ALL SELECT '2012-04-01',2 UNION ALL SELECT '2012-05-01',2
UNION ALL SELECT '2012-06-01',2 UNION ALL SELECT '2012-07-01',2
UNION ALL SELECT '2012-08-01',2 UNION ALL SELECT '2012-09-01',2
UNION ALL SELECT '2012-10-01',2 UNION ALL SELECT '2012-11-01',2
UNION ALL SELECT '2012-12-01',2;

SELECT * FROM #EVENT_COUNT;
</code>```

This is the table that is created:

```<code> DATE       |GROUP_ID
    ---------------------
    2011-01-01  |1<<This date
    2011-02-01  |1
    2011-03-01  |1
    2011-04-01  |1
    2011-05-01  |1
    2011-06-01  |1
    2011-07-01  |1
    2011-08-01  |1
    2011-09-01  |1
    2011-10-01  |1
    2011-11-01  |1
    2011-12-01  |2 << This date
    2012-01-01  |2
    2012-02-01  |2
    2012-03-01  |2
    2012-04-01  |2
    2012-05-01  |2
    2012-06-01  |2
    2012-07-01  |2
    2012-08-01  |2
    2012-09-01  |2
    2012-10-01  |2
    2012-11-01  |2
    2012-12-01  |2
</code>```

The result that I need is the two dates in bold grouped by GROUP_ID:

```<code>DATE        |GROUP_ID
---------------------
2011-01-01  |1<<This date
2011-12-01  |2 << This date
</code>```

Any help is much appreciated.

答:
You can do this by using the LEAD function and looking at the second next date from the current date. If the difference is less than 180, it would satisfy your condition:

```<code>SELECT a.Group_ID,min(Date) as Date
FROM
(SELECT *,
       lead(date,2) over(partition by group_id order by date) as lag_date2
FROM #EVENT_COUNT) a
WHERE DATEDIFF(day,date,ISNULL(lag_date2,'01Jan2100'))<=180
GROUP BY a.Group_ID
</code>```

Hope this helps.

Body:
I need to be able to find the minimum date out of a set of dates that fit the following criteria.

3 dates which are within 180 days of each other. The logic which i'm guessing would apply is that each date would be an index from which subsequent dates are compared to. I can do this using the LAG and Window functions if there are two dates. but the requirement is to find the minimum date where 3 events fit into a 180 day window and grouped by the GROUP_ID.

The test data is:

DROP TABLE #EVENT_COUNT
CREATE TABLE #EVENT_COUNT
(
    [DATE]    DATE
    ,[GROUP_ID]    INT

);

INSERT INTO #EVENT_COUNT
SELECT '2011-01-01',1
UNION ALL SELECT '2011-02-01',1 UNION ALL SELECT '2011-03-01',1
UNION ALL SELECT '2011-04-01',1 UNION ALL SELECT '2011-05-01',1
UNION ALL SELECT '2011-06-01',1 UNION ALL SELECT '2011-07-01',1
UNION ALL SELECT '2011-08-01',1 UNION ALL SELECT '2011-09-01',1
UNION ALL SELECT '2011-10-01',1 UNION ALL SELECT '2011-11-01',1
UNION ALL SELECT '2011-12-01',2 UNION ALL SELECT '2012-01-01',2
UNION ALL SELECT '2012-02-01',2 UNION ALL SELECT '2012-03-01',2
UNION ALL SELECT '2012-04-01',2 UNION ALL SELECT '2012-05-01',2
UNION ALL SELECT '2012-06-01',2 UNION ALL SELECT '2012-07-01',2
UNION ALL SELECT '2012-08-01',2 UNION ALL SELECT '2012-09-01',2
UNION ALL SELECT '2012-10-01',2 UNION ALL SELECT '2012-11-01',2
UNION ALL SELECT '2012-12-01',2;

SELECT * FROM #EVENT_COUNT;

This is the table that is created:

 DATE       |GROUP_ID
    ---------------------
    2011-01-01  |1<<This date
    2011-02-01  |1
    2011-03-01  |1
    2011-04-01  |1
    2011-05-01  |1
    2011-06-01  |1
    2011-07-01  |1
    2011-08-01  |1
    2011-09-01  |1
    2011-10-01  |1
    2011-11-01  |1
    2011-12-01  |2 << This date
    2012-01-01  |2
    2012-02-01  |2
    2012-03-01  |2
    2012-04-01  |2
    2012-05-01  |2
    2012-06-01  |2
    2012-07-01  |2
    2012-08-01  |2
    2012-09-01  |2
    2012-10-01  |2
    2012-11-01  |2
    2012-12-01  |2

The result that I need is the two dates in bold grouped by GROUP_ID:

DATE        |GROUP_ID
---------------------
2011-01-01  |1<<This date
2011-12-01  |2 << This date

Any help is much appreciated.

Body:
You can do this by using the LEAD function and looking at the second next date from the current date. If the difference is less than 180, it would satisfy your condition:

SELECT a.Group_ID,min(Date) as Date
FROM
(SELECT *,
       lead(date,2) over(partition by group_id order by date) as lag_date2
FROM #EVENT_COUNT) a
WHERE DATEDIFF(day,date,ISNULL(lag_date2,'01Jan2100'))<=180
GROUP BY a.Group_ID

Hope this helps.


问:
C#/WPF: Disable Text-Wrap of RichTextBox
Does anyone know how I can disable the text wrapping of a RichTextBox?
E.g. if I have a large string which doesn't fit in the window, the RichTextBox places the part of the string which can't be shown of a new line. I want to disable that (and make it visible only by using the Scrollbar).

Thanks a lot.

Cheers

答:
Since no answer was satisfying for me, here is my solution:

```<code>private void RichTxt_TextChanged(object sender, TextChangedEventArgs e)
{
    string text = new TextRange(richTxt.Document.ContentStart, richTxt.Document.ContentEnd).Text;
    FormattedText ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(richTxt.FontFamily, richTxt.FontStyle, richTxt.FontWeight, richTxt.FontStretch), richTxt.FontSize, Brushes.Black);
    richTxt.Document.PageWidth = ft.Width + 12;
    richTxt.HorizontalScrollBarVisibility = (richTxt.Width < ft.Width + 12) ? ScrollBarVisibility.Visible : ScrollBarVisibility.Hidden;
}
</code>```

Question is about performance depending on text length and how often it is refreshed.

Body:
Since no answer was satisfying for me, here is my solution:

private void RichTxt_TextChanged(object sender, TextChangedEventArgs e)
{
    string text = new TextRange(richTxt.Document.ContentStart, richTxt.Document.ContentEnd).Text;
    FormattedText ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(richTxt.FontFamily, richTxt.FontStyle, richTxt.FontWeight, richTxt.FontStretch), richTxt.FontSize, Brushes.Black);
    richTxt.Document.PageWidth = ft.Width + 12;
    richTxt.HorizontalScrollBarVisibility = (richTxt.Width < ft.Width + 12) ? ScrollBarVisibility.Visible : ScrollBarVisibility.Hidden;
}

Question is about performance depending on text length and how often it is refreshed.


问:
How to add Yii2 jui datepicker to filter field in GridView
I'm using the same code as I used to add in ActiveForm, but it doesn't work:

What i sthe correct way to add jui datepicker in filter field for gridview?

```<code><?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'list_id',
            [
                'attribute' => 'channel',
                'value' => 'channel.title',
            ],
            [
                'attribute' => 'list_date',
                'value' => 'list_date',
                'filter' => \yii\jui\DatePicker::widget(\yii\jui\DatePicker::className(), ['language' => 'ru', 'dateFormat' => 'dd-MM-yyyy']),
            ],
            'make_date',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</code>```

答:
```<code>        [
            'attribute' => 'updated_at',
            'value' => 'updated_at',
            //'format' => ['date', 'php:d.m.Y'],
            'options' => ['width' => '115'],
            'filter' => \yii\jui\DatePicker::widget(
                [
                    'name' => 'NewsSearch[updated_at]',
                    'value' => \yii\helpers\ArrayHelper::getValue($_GET, 'NewsSearch.updated_at'),
                    'language' => 'ru',
                    'dateFormat' => 'yyyy-MM-dd',
                    // 'model' => $searchModel,
                    // 'attribute' => 'updated_at',
                    'options' => [
                        'class' => 'form-control'
                    ],
                ]
            ),
        ],
</code>```

Avoid to use 'attribute'=> 'updated_at' in 'filter' section;

Specify direct 'name' attribute (that name will be given for corresponding input in filter row)

Body:
I'm using the same code as I used to add in ActiveForm, but it doesn't work:

What i sthe correct way to add jui datepicker in filter field for gridview?

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'list_id',
            [
                'attribute' => 'channel',
                'value' => 'channel.title',
            ],
            [
                'attribute' => 'list_date',
                'value' => 'list_date',
                'filter' => \yii\jui\DatePicker::widget(\yii\jui\DatePicker::className(), ['language' => 'ru', 'dateFormat' => 'dd-MM-yyyy']),
            ],
            'make_date',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

Body:
        [
            'attribute' => 'updated_at',
            'value' => 'updated_at',
            //'format' => ['date', 'php:d.m.Y'],
            'options' => ['width' => '115'],
            'filter' => \yii\jui\DatePicker::widget(
                [
                    'name' => 'NewsSearch[updated_at]',
                    'value' => \yii\helpers\ArrayHelper::getValue($_GET, 'NewsSearch.updated_at'),
                    'language' => 'ru',
                    'dateFormat' => 'yyyy-MM-dd',
                    // 'model' => $searchModel,
                    // 'attribute' => 'updated_at',
                    'options' => [
                        'class' => 'form-control'
                    ],
                ]
            ),
        ],

Avoid to use 'attribute'=> 'updated_at' in 'filter' section;

Specify direct 'name' attribute (that name will be given for corresponding input in filter row)


问:
SQL how to convert MM-DD-YYYY string value to date
I have a datetime variable in string format in the following form:

```<code>01-04-2020 11:50:44:569
01-03-2020 12:50:44:589
01-03-2020 01:50:44:579
</code>```

How do I extract the date part and select a range of dates?

I tried to use:

```<code>cast(substring(value,1,10) as date) as date1
date1 between '2020-01-01' and '2020-01-05'
</code>```

But it returns 0 records.

However this code worked on datetime string value in the following format:

```<code>2020-01-03T11:50:24:529Z
</code>```

It will extract the date part and store it as a timestamp and extracts records within the range, but does not work on the first example.

I'm just trying to find a method to convert string value to date value, I have no intention of confusing anyone. As for sample dataset, I think the first part of the question with the 3 records should be enough for testing because all the values under the same variable are all in the same format.

答:
I think I figured it out:</p>

```<code>cast(to_date((FROM_UNIXTIME(UNIX_TIMESTAMP(value, "MM-dd-yyyy HH:mm:ss:SSS"), "yyyy-MM-dd HH:mm:ss.SSS"))) as date) as date1
</code>```

Body:
I have a datetime variable in string format in the following form:

01-04-2020 11:50:44:569
01-03-2020 12:50:44:589
01-03-2020 01:50:44:579

How do I extract the date part and select a range of dates?

I tried to use:

cast(substring(value,1,10) as date) as date1
date1 between '2020-01-01' and '2020-01-05'

But it returns 0 records.

However this code worked on datetime string value in the following format:

2020-01-03T11:50:24:529Z

It will extract the date part and store it as a timestamp and extracts records within the range, but does not work on the first example.

I'm just trying to find a method to convert string value to date value, I have no intention of confusing anyone. As for sample dataset, I think the first part of the question with the 3 records should be enough for testing because all the values under the same variable are all in the same format.

Body:
I think I figured it out:

cast(to_date((FROM_UNIXTIME(UNIX_TIMESTAMP(value, "MM-dd-yyyy HH:mm:ss:SSS"), "yyyy-MM-dd HH:mm:ss.SSS"))) as date) as date1


问:
NOT HAVING (inverse HAVING) clause with aggregation in Oracle
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

```<code>SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]
</code>```

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

答:
I think the simplest solution is to just change it to HAVING NOT ...

```<code>SELECT [...]
FROM [...]
HAVING NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]
</code>```

But I often find NOT (...) unintuitive; as an alternative, @MichaelBroughton's answer explains how to invert the logic from NOT (x AND y) to NOT x OR NOT y

Body:
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

Body:
I think the simplest solution is to just change it to HAVING NOT ...

SELECT [...]
FROM [...]
HAVING NOT (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

But I often find NOT (...) unintuitive; as an alternative, @MichaelBroughton's answer explains how to invert the logic from NOT (x AND y) to NOT x OR NOT y


问:
Why do I have to specify the python version when creating a new conda environment?
I do conda create --name env then conda activate env.

My prompt now has (env) at the beginning of it. Then I try running python at the prompt and it returns

```<code>'python' is not recognized as an internal or external command, operable program or batch file.
</code>```

The documentation explicitly states

This environment uses the same version of Python that you are currently using because you did not specify a version.

However, if I do conda create --name env python=3.8, my environment correctly runs python 3.8. It seems like if I don't specify a version, my environment is completely empty (which it is when I look in the directory). But the documentation says that it should have the version of python from the base. What am I doing wrong?

I'm using an anaconda prompt in Windows 10.

答:
I think that bit of documentation is outdated and is a hold-over from pre-v4.4, when the recommended practice was to put the base env's bin/ directory on PATH. In Conda v4.4+, the base env is no longer accessible by default when another env is activated.

To have Python in an env, one must explicitly request it to be installed, e.g.,

```<code>conda create --name env python
</code>```

Note, one doesn't have to specify a version.

In the end, this should be seen as an advantage, since it allows users to create non-Python envs and keeps the base env isolated.

Body:
I do conda create --name env then conda activate env.

My prompt now has (env) at the beginning of it. Then I try running python at the prompt and it returns

'python' is not recognized as an internal or external command, operable program or batch file.

The documentation explicitly states

This environment uses the same version of Python that you are currently using because you did not specify a version.

However, if I do conda create --name env python=3.8, my environment correctly runs python 3.8. It seems like if I don't specify a version, my environment is completely empty (which it is when I look in the directory). But the documentation says that it should have the version of python from the base. What am I doing wrong?

I'm using an anaconda prompt in Windows 10.

Body:
I think that bit of documentation is outdated and is a hold-over from pre-v4.4, when the recommended practice was to put the base env's bin/ directory on PATH. In Conda v4.4+, the base env is no longer accessible by default when another env is activated.

To have Python in an env, one must explicitly request it to be installed, e.g.,

conda create --name env python

Note, one doesn't have to specify a version.

In the end, this should be seen as an advantage, since it allows users to create non-Python envs and keeps the base env isolated.


问:
Why we have to use Assignment Expressions in obtaining the return value from await?
```<code>import asyncio
from asyncio import StreamReader

async def echo(reader: StreamReader):
    try:
        while data := await reader.readline():
            pass
</code>```

Question> why we have to data := await here instead of data = await?

Error from python compiler:

```<code>while data = await reader.readline():
           ^ SyntaxError: invalid syntax
</code>```

答:
Assignment with = was designed expressly to not do this kind of nested side-effecting inside a larger expression. With other languages (looking at you, C) people can type = where they meant to use == and assign something by accident. See this question for more discussion of why = was designed this way.

Assignment with = is a statement and not an expression, it does not evaluate to what's on the right hand side of the equal sign. That means there isn't a value for the while to test in order to decide whether to continue. The := (AKA the walrus operator) provides a value the while can test, see this question.

Body:
import asyncio
from asyncio import StreamReader

async def echo(reader: StreamReader):
    try:
        while data := await reader.readline():
            pass

Question> why we have to data := await here instead of data = await?

Error from python compiler:

while data = await reader.readline():
           ^ SyntaxError: invalid syntax


问:
Find out if selected cell is in databodyrange
I have a macro set up to perform a chunk of code in an 'onclick' event, and I'm trying to determine if they've selected a numeric value in a table range. An example of my table is below, and I'm trying to figure out if they've selected a number > 0 in the second column. I know how to reference the second column of a specific table, something like:

```<code>ListObjects("Table1").ListColumns(2).DataBodyRange
</code>```

but I'm not sure how to figure out if the selected cell is in that range. Any suggestions? Thanks so much for your help!

答:
Assuming your table has filters then you have to check the visible cells only

Try this code:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = False

    Dim r As Range
    Set r = ListObjects(1).ListColumns(2).DataBodyRange.SpecialCells(xlCellTypeVisible)

    Dim hit As Boolean
    hit = Not Application.Intersect(r, Target) Is Nothing

    If hit Then
        Range("A1").Value = "Inside"
    Else
        Range("A1").Value = "Outside"
    End If

    Application.EnableEvents = True

End Sub
</code>```

otherwise for all visible and non-visible cells use

```<code>Set r = ListObjects(1).DataBodyRange
</code>```

Body:
I have a macro set up to perform a chunk of code in an 'onclick' event, and I'm trying to determine if they've selected a numeric value in a table range. An example of my table is below, and I'm trying to figure out if they've selected a number > 0 in the second column. I know how to reference the second column of a specific table, something like:

ListObjects("Table1").ListColumns(2).DataBodyRange

but I'm not sure how to figure out if the selected cell is in that range. Any suggestions? Thanks so much for your help!

Body:
Assuming your table has filters then you have to check the visible cells only

Try this code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.EnableEvents = False

    Dim r As Range
    Set r = ListObjects(1).ListColumns(2).DataBodyRange.SpecialCells(xlCellTypeVisible)

    Dim hit As Boolean
    hit = Not Application.Intersect(r, Target) Is Nothing

    If hit Then
        Range("A1").Value = "Inside"
    Else
        Range("A1").Value = "Outside"
    End If

    Application.EnableEvents = True

End Sub

otherwise for all visible and non-visible cells use

Set r = ListObjects(1).DataBodyRange


问:
Dataframe expanding window and applying multiple functions
I am trying to calculate stats on a timeindexed dataframe using the expanding window functionality.

```<code>date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range)),index=date_range,columns=['X'])

df['X'].expanding(min_periods=1).apply(lambda x: np.nanpercentile(x,50))

</code>```

How can I aggregate different percentiles for each date to get something like

```<code>            50Th_percentile 60Th_percentile
2015-01-01    0.373176        0.373176
2015-01-02    0.601829        0.647559
2015-01-03    0.373176        0.464637
2015-01-04    0.335774        0.358215
</code>```

Something like below doesn't work

```<code>df['X'].expanding(min_periods=1).apply(lambda x:
x.agg[np.nanpercentile(x.values,50),np.nanpercentile(x.values,60)])

</code>```

Body:
I am trying to calculate stats on a timeindexed dataframe using the expanding window functionality.

date_range=pd.date_range('2015-01-01','2019-12-31')

df=pd.DataFrame(np.random.rand(len(date_range)),index=date_range,columns=['X'])

df['X'].expanding(min_periods=1).apply(lambda x: np.nanpercentile(x,50))

How can I aggregate different percentiles for each date to get something like

            50Th_percentile 60Th_percentile
2015-01-01    0.373176        0.373176
2015-01-02    0.601829        0.647559
2015-01-03    0.373176        0.464637
2015-01-04    0.335774        0.358215

Something like below doesn't work

df['X'].expanding(min_periods=1).apply(lambda x:
x.agg[np.nanpercentile(x.values,50),np.nanpercentile(x.values,60)])

Body:
Use:

(df['X'].expanding(min_periods=1).agg({'50':lambda x: np.nanpercentile(x,50),
                                       '60':lambda x: np.nanpercentile(x,60)})
        .add_suffix('_percentile'))

            50_percentile  60_percentile
2015-01-01       0.520419       0.520419
2015-01-02       0.726755       0.768022
2015-01-03       0.547734       0.624805
2015-01-04       0.597529       0.627407
2015-01-05       0.547734       0.587570
...                   ...            ...
2019-12-27       0.485802       0.591071
2019-12-28       0.485946       0.590530
2019-12-29       0.486197       0.591342
2019-12-30       0.486448       0.591684
2019-12-31       0.486467       0.591791

[1826 rows x 2 columns]

To add more:

list_percentiles = [50,60,70,80,90]
agg_percentiles = dict(zip(map(str,list_percentiles),
                           map(lambda val: lambda x: np.nanpercentile(x,val),
                               list_percentiles)
                           )
                      )
df['X'].expanding(min_periods=1).agg(agg_percentiles).add_suffix('_percentiles')

            50_percentiles  60_percentiles  70_percentiles  80_percentiles  \
2015-01-01        0.520419        0.520419        0.520419        0.520419
2015-01-02        0.726755        0.768022        0.809290        0.850557
2015-01-03        0.547734        0.624805        0.701877        0.778948
2015-01-04        0.597529        0.627407        0.675902        0.761632
2015-01-05        0.547734        0.587570        0.627407        0.704478
...                    ...             ...             ...             ...
2019-12-27        0.485802        0.591071        0.691039        0.796903
2019-12-28        0.485946        0.590530        0.690891        0.796819
2019-12-29        0.486197        0.591342        0.691197        0.796735
2019-12-30        0.486448        0.591684        0.691088        0.796652
2019-12-31        0.486467        0.591791        0.691237        0.796568

            90_percentiles
2015-01-01        0.520419
2015-01-02        0.891824
2015-01-03        0.856020
2015-01-04        0.847361
2015-01-05        0.818785
...                    ...
2019-12-27        0.899027
2019-12-28        0.898999
2019-12-29        0.898971
2019-12-30        0.898943
2019-12-31        0.898916

[1826 rows x 5 columns]

or List Comprehensions

agg_percentiles = dict(zip(map(str,list_percentiles),
                           [lambda x: np.nanpercentile(x,val)
                            for val in list_percentiles]
                          )
                      )


问:
Which layout/template adopt with jQuery
When creating jQuery UI based websites, CSS, JS and HTML code can be splited into components:

which frameworks use for templating/splitting components?

what are the benefits and drawbacks of server side generated pages VS client side JSON calls?

how to define a navigation through components?

eclipse for development and firebugs for debugging are they enough good tools for this?

Thanks.

答:
Look at jQuery UI

Depends on the remit of the application.

See 2.

Firebug is invaluable.

For clarification or more specific answers please expand your questions so they include appropriate levels of detail

Title: Which layout/template adopt with jQuery


问:
Azure IoT Hub - Where can I see why the hub disconnects the devices?
I'm using an Azure IoT Hub. I'm still in the development phase. It used to work fine, but now the hub is disconnecting the devices almost immedially after they connect. Where can I see some logs or info about why the hub is disconnecting? And if I have to activate some services, which ones?</p>

答:
You may need to turn on diagnostics for IoT Hub for logging the device connection events and errors. Once the logs and alerts are ON for connected devices, you will get alerts, error logs when errors occur. The troubleshooting link to begin with can be https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-troubleshoot-connectivity which captures details about how to enable diagnostics, alerts and other possible troubleshooting methods. This section 'Resolve connectivity errors' has description on how to look for common issues when you receive an alert and this seems to have dependency on Azure monitor logs to be enabled. It also furnishes information in terms of problem resolution guides for the most common errors.

There are couple of services integrated with IoT Hub like Azure Monitor and Azure Resource Health that help to provide you with the data required for keeping your IoT solution running in healthy state. Azure Resource Health helps to monitor whether your IoT hub is up and running. Here is a related link on iot hub health monitor and diagnose problems that can be a additional reference for you.

Azure Monitor stores log data in a Log Analytics workspace, which is an Azure resource and a container where data is collected, aggregated, and serves as an administrative boundary as conveyed in Azure monitor logs. Data in Azure Monitor Logs is retrieved using a log query written with the Kusto query language, which allows you to quickly retrieve, consolidate, and analyze collected data.


问:
SonarQube Is there a gradle setting in detekt gradle plugin to generate report on remote host instead of in a file
When I use sonarqube plugin I'm not able to generate report on remote host on using my specific branch as lateast version is not supporting it and branch.name is deprecated

So When I use detekt plugin it generates report in file locally and not on remote host.
How can provide gradle setting to generate html report on remote host Like it generates using property sonar.host.url when we use sonarqube plugin

my build.gradle looks like

```<code> failFast = true // fail build on any finding
 buildUponDefaultConfig = true // preconfigure defaults
 config = files("$projectDir/config/detekt.yml") // point to your custom config defining rules to run, overwriting default behavior
 baseline = file("$projectDir/config/baseline.xml") // a way of suppressing issues before introducing detekt

 reports {
     html.enabled = true // observe findings in your browser with structure and code snippets
     xml.enabled = true // checkstyle like format mainly for integrations like Jenkins
     txt.enabled = true // similar to the console output, contains issue signature to manually edit baseline files
    html.destination =  "Remote host url"

 }

}```

 ```plugin {
  id("io.gitlab.arturbosch.detekt") version "1.5.1"
   id("org.sonarqube") version 2.7
 }```

```

答:
Hi my code is working for   id("org.sonarqube") version 2.7
I don't need detekt plugin

We have found for sonarqube kotlin was not enabled thats why it was always saying master branch empty when we tried to run it with any other branch, after server enabled kotlin support simply by adding sonarqube server host it's working for any branch.

Body:
When I use sonarqube plugin I'm not able to generate report on remote host on using my specific branch as lateast version is not supporting it and branch.name is deprecated

So When I use detekt plugin it generates report in file locally and not on remote host.
How can provide gradle setting to generate html report on remote host Like it generates using property sonar.host.url when we use sonarqube plugin

my build.gradle looks like

 failFast = true // fail build on any finding
 buildUponDefaultConfig = true // preconfigure defaults
 config = files("$projectDir/config/detekt.yml") // point to your custom config defining rules to run, overwriting default behavior
 baseline = file("$projectDir/config/baseline.xml") // a way of suppressing issues before introducing detekt

 reports {
     html.enabled = true // observe findings in your browser with structure and code snippets
     xml.enabled = true // checkstyle like format mainly for integrations like Jenkins
     txt.enabled = true // similar to the console output, contains issue signature to manually edit baseline files
    html.destination =  "Remote host url"

 }

}```

 ```plugin {
  id("io.gitlab.arturbosch.detekt") version "1.5.1"
   id("org.sonarqube") version 2.7
 }```


问:
Get the last string printed in C/C++
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}
```

<p>and then the tester:</p>

<pre class="lang-cpp prettyprint-override"><code>TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}
</code>```

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

答:
Redirect the standard output to a buffer.

Live on Coliru

#include <stdio.h>
#include <unistd.h>

#define BUFFER_SIZE 1024
int stdoutSave;
char outputBuffer[BUFFER_SIZE];

void replaceStdout()
{
    fflush(stdout); //clean everything first
    stdoutSave = dup(STDOUT_FILENO); //save the stdout state
    freopen("NUL", "a", stdout); //redirect stdout to null pointer
    setvbuf(stdout, outputBuffer, _IOFBF, 1024); //set buffer to stdout
}

void restoreStdout()
{
    freopen("NUL", "a", stdout); //redirect stdout to null again
    dup2(stdoutSave, STDOUT_FILENO); //restore the previous state of stdout
    setvbuf(stdout, NULL, _IONBF, BUFFER_SIZE); //disable buffer to print to screen instantly
}

void printHelloWorld()
{
    printf("hello\n");
    printf("world");
}

int main()
{
    replaceStdout();
    printHelloWorld();
    restoreStdout();
    // Use outputBuffer to test EXPECT_EQ("somthing1", outputBuffer);
    printf("Fetched output: (%s)", outputBuffer);
    return 0;
}
```

References: http://kaskavalci.com/redirecting-stdout-to-array-and-restoring-it-back-in-c/

Title: Get the last string printed in C/C++

Body:
I am trying to create a tester using googletest. the problem is that the function that I am testing is returning void and printing a result instead. I want to get the last string printed into the console so I can test the output. the string may include \n.

so I have the function itself:

void f_sequence(char sequenceStr[])
{
   //logic...
    if(condotion1)
        printf("somthing1");
    else if(condotion2)
        printf("somthing2")
(...)
}

and then the tester:

TEST(TesterGroup, TesterName)
{
    f_sequence("input");
    EXPECT_EQ("somthing1", /*how do i get the output?*/);
}

Is it possible?

The functions I test are in c, while the Test function itself (the tester) is in c++. the output is printed using printf. I cannot change the function itself. I am using CLion latest version.

Body:
Redirect the standard output to a buffer.

Live on Coliru

#include <stdio.h>
#include <unistd.h>

#define BUFFER_SIZE 1024
int stdoutSave;
char outputBuffer[BUFFER_SIZE];

void replaceStdout()
{
    fflush(stdout); //clean everything first
    stdoutSave = dup(STDOUT_FILENO); //save the stdout state
    freopen("NUL", "a", stdout); //redirect stdout to null pointer
    setvbuf(stdout, outputBuffer, _IOFBF, 1024); //set buffer to stdout
}

void restoreStdout()
{
    freopen("NUL", "a", stdout); //redirect stdout to null again
    dup2(stdoutSave, STDOUT_FILENO); //restore the previous state of stdout
    setvbuf(stdout, NULL, _IONBF, BUFFER_SIZE); //disable buffer to print to screen instantly
}

void printHelloWorld()
{
    printf("hello\n");
    printf("world");
}

int main()
{
    replaceStdout();
    printHelloWorld();
    restoreStdout();
    // Use outputBuffer to test EXPECT_EQ("somthing1", outputBuffer);
    printf("Fetched output: (%s)", outputBuffer);
    return 0;
}

References: http://kaskavalci.com/redirecting-stdout-to-array-and-restoring-it-back-in-c/


问:
excel, vlookup, error message, we found a problem with this formula
I am using a vlookup. Please see below. I am trying to do the vlookup in cell vlookup37 below. I have never received this error message before. I am very used to doing vlookups and have never had this issue. This excel file is large and has a filter on. Please see below. Thanks for your help.

```<code>=vlookup(A38, Sheet2!A2:A125,1,false)
</code>```

Error Message

We found a problem with this formula. Try clicking Insert Function on the Formulas tab to fix it, or click Help for more info on common formula problems.

答:
I fixed the issue, but I don't know why I needed to do this. I followed the directions on the popup error message and I followed the wizard. It produced the below syntax which worked.</p>

```<code>=VLOOKUP($A38|Sheet3!$A$2:$AZ$587|9|FALSE)
</code>```

Body:
I am using a vlookup. Please see below. I am trying to do the vlookup in cell vlookup37 below. I have never received this error message before. I am very used to doing vlookups and have never had this issue. This excel file is large and has a filter on. Please see below. Thanks for your help.

=vlookup(A38, Sheet2!A2:A125,1,false)

Error Message

We found a problem with this formula. Try clicking Insert Function on the Formulas tab to fix it, or click Help for more info on common formula problems.

Body:
I fixed the issue, but I don't know why I needed to do this. I followed the directions on the popup error message and I followed the wizard. It produced the below syntax which worked.

=VLOOKUP($A38|Sheet3!$A$2:$AZ$587|9|FALSE)


问:
UIPageViewController not calling delegate methods (Swift 5)
I have an extremely simple UIPageViewController setup in my project. When I create my page view controller and navigate to it, everything seems to work properly and it loads the first page properly. However, when I try to swipe or switch to other pages in the array of ViewControllers, my page controller does not call its delegate methods to do so.

Here is how I am instantiating and navigating to the page view controller from the parent view:

```<code>let tutorialPageVC = TareTutorialPageViewController()
let nc = UINavigationController(rootViewController: tutorialPageVC)
nc.modalPresentationStyle = .fullScreen
nc.definesPresentationContext = true
nc.setNavigationBarHidden(true, animated: true)
self.present(nc, animated: true, completion: nil)
</code>```

And here is my page view controller class:

```<code>import UIKit

class TareTutorialPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    var tutorialPages = [UIViewController]()
    let pageControl = UIPageControl()

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [:])

        self.dataSource = self
        self.delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let initialTutorialPage = 0

        let tutorialPage1 = TutorialPage1ViewController()
        let tutorialPage2 = TutorialPage2ViewController()
        let tutorialPage3 = TutorialPage3ViewController()

        self.tutorialPages.append(tutorialPage1)
        self.tutorialPages.append(tutorialPage2)
        self.tutorialPages.append(tutorialPage3)

        setViewControllers([tutorialPages[initialTutorialPage]], direction: .forward, animated: true, completion: nil)

        self.pageControl.frame = CGRect()
        self.pageControl.currentPageIndicatorTintColor = UIColor.white
        self.pageControl.pageIndicatorTintColor = UIColor.lightGray
        self.pageControl.numberOfPages = self.tutorialPages.count
        self.pageControl.currentPage = initialTutorialPage
        self.view.addSubview(self.pageControl)

        self.pageControl.translatesAutoresizingMaskIntoConstraints = false
        self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -5).isActive = true
        self.pageControl.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -20).isActive = true
        self.pageControl.heightAnchor.constraint(equalTo: self.view.heightAnchor, constant: 20).isActive = true
        self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        //Might not need any of this if we only want the user to move forward??
        if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewController)
        {
            if viewControllerIndex == 0
            {
                return self.tutorialPages.last
            }
            else
            {
                return self.tutorialPages[viewControllerIndex-1]
            }
        }

        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {

        if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewController)
        {
            if viewControllerIndex < self.tutorialPages.count - 1
            {
                return self.tutorialPages[viewControllerIndex + 1]
            }
            else
            {
                //Navigation to go to scale tare settings here...
                //For now just returns to first page of page view

                return self.tutorialPages.first
            }
        }

        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

        if let viewControllers = pageViewController.viewControllers {
            if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewControllers[0])
            {
                self.pageControl.currentPage = viewControllerIndex
            }
        }
    }

}
</code>```

Here is an example of one my extremely simple view controllers that are shown by the page view controller:

```<code>import UIKit

class TutorialPage1ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.black

        let label = UILabel()
        label.text = "Tutorial page 1"
        label.textColor = UIColor.white
        self.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
    }
}
</code>```

答:
The problem is not that the delegate funcs are not being called, the problem is that you are completely overlaying your UIPageViewController with a UIPageControl.

You can confirm this by adding this line:

```<code>   // existing line
   self.view.addSubview(self.pageControl)

   // add this line
   self.pageControl.backgroundColor = .orange
</code>```

Change your constraint setup like this:

```<code>    // completely remove these lines
    //self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -5).isActive = true
    //self.pageControl.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -20).isActive = true
    //self.pageControl.heightAnchor.constraint(equalTo: self.view.heightAnchor, constant: 20).isActive = true
    //self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

    let g = view.safeAreaLayoutGuide

    NSLayoutConstraint.activate([
        pageControl.widthAnchor.constraint(equalTo: g.widthAnchor, constant: -20.0),
        pageControl.centerXAnchor.constraint(equalTo: g.centerXAnchor),
        pageControl.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -5.0),
    ])
</code>```

Now you should see the page control at the bottom, and you'll be able to swipe through the pages.

By the way, UIPageViewController has a "built-in" UIPageControl that you might find works better anyway.

Body:
I have an extremely simple UIPageViewController setup in my project. When I create my page view controller and navigate to it, everything seems to work properly and it loads the first page properly. However, when I try to swipe or switch to other pages in the array of ViewControllers, my page controller does not call its delegate methods to do so.

Here is how I am instantiating and navigating to the page view controller from the parent view:

let tutorialPageVC = TareTutorialPageViewController()
let nc = UINavigationController(rootViewController: tutorialPageVC)
nc.modalPresentationStyle = .fullScreen
nc.definesPresentationContext = true
nc.setNavigationBarHidden(true, animated: true)
self.present(nc, animated: true, completion: nil)

And here is my page view controller class:

import UIKit

class TareTutorialPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    var tutorialPages = [UIViewController]()
    let pageControl = UIPageControl()

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [:])

        self.dataSource = self
        self.delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let initialTutorialPage = 0

        let tutorialPage1 = TutorialPage1ViewController()
        let tutorialPage2 = TutorialPage2ViewController()
        let tutorialPage3 = TutorialPage3ViewController()

        self.tutorialPages.append(tutorialPage1)
        self.tutorialPages.append(tutorialPage2)
        self.tutorialPages.append(tutorialPage3)

        setViewControllers([tutorialPages[initialTutorialPage]], direction: .forward, animated: true, completion: nil)

        self.pageControl.frame = CGRect()
        self.pageControl.currentPageIndicatorTintColor = UIColor.white
        self.pageControl.pageIndicatorTintColor = UIColor.lightGray
        self.pageControl.numberOfPages = self.tutorialPages.count
        self.pageControl.currentPage = initialTutorialPage
        self.view.addSubview(self.pageControl)

        self.pageControl.translatesAutoresizingMaskIntoConstraints = false
        self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -5).isActive = true
        self.pageControl.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -20).isActive = true
        self.pageControl.heightAnchor.constraint(equalTo: self.view.heightAnchor, constant: 20).isActive = true
        self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        //Might not need any of this if we only want the user to move forward??
        if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewController)
        {
            if viewControllerIndex == 0
            {
                return self.tutorialPages.last
            }
            else
            {
                return self.tutorialPages[viewControllerIndex-1]
            }
        }

        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {

        if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewController)
        {
            if viewControllerIndex < self.tutorialPages.count - 1
            {
                return self.tutorialPages[viewControllerIndex + 1]
            }
            else
            {
                //Navigation to go to scale tare settings here...
                //For now just returns to first page of page view

                return self.tutorialPages.first
            }
        }

        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

        if let viewControllers = pageViewController.viewControllers {
            if let viewControllerIndex = self.tutorialPages.firstIndex(of: viewControllers[0])
            {
                self.pageControl.currentPage = viewControllerIndex
            }
        }
    }

}

Here is an example of one my extremely simple view controllers that are shown by the page view controller:

import UIKit

class TutorialPage1ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.black

        let label = UILabel()
        label.text = "Tutorial page 1"
        label.textColor = UIColor.white
        self.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
    }
}

Body:
The problem is not that the delegate funcs are not being called, the problem is that you are completely overlaying your UIPageViewController with a UIPageControl.

You can confirm this by adding this line:

   // existing line
   self.view.addSubview(self.pageControl)

   // add this line
   self.pageControl.backgroundColor = .orange

Change your constraint setup like this:

    // completely remove these lines
    //self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -5).isActive = true
    //self.pageControl.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -20).isActive = true
    //self.pageControl.heightAnchor.constraint(equalTo: self.view.heightAnchor, constant: 20).isActive = true
    //self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

    let g = view.safeAreaLayoutGuide

    NSLayoutConstraint.activate([
        pageControl.widthAnchor.constraint(equalTo: g.widthAnchor, constant: -20.0),
        pageControl.centerXAnchor.constraint(equalTo: g.centerXAnchor),
        pageControl.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -5.0),
    ])

Now you should see the page control at the bottom, and you'll be able to swipe through the pages.

By the way, UIPageViewController has a "built-in" UIPageControl that you might find works better anyway.


问:
Unable to resolve @react-navigation/drawer in react native to create drawer navigation
I am trying to create new drawer navigation but getting this below error

```<code>Unable to resolve "react-native-screens" from "node_modules\@react-navigation\drawer\src\views\DrawerView.tsx"
Failed building JavaScript bundle.
</code>```

but same code i tried in new empty project it worked with react-native-drawer in older version of "react-navigation": "^2.6.2" but the same not working in  "react-navigation": "^4.0.10", it shows that react-native-drawer is removed and @react-native/drawer is latest so we need to use that but its not working kindly help me resolving this...Code is in below

```<code>import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';

function Feed() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Feed Screen</Text>
    </View>
  );
}

function Article() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Article Screen</Text>
    </View>
  );
}

const Drawer = createDrawerNavigator();

function MyDrawer() {
  return (
    <Drawer.Navigator>
      <Drawer.Screen name="Feed" component={Feed} />
      <Drawer.Screen name="Article" component={Article} />
    </Drawer.Navigator>
  );
}

export default function DrawerNavigator() {
  return (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  );
}
</code>```

答:
I know this is not a right solution but anyway it worked for me...

instead of @react-navigation/drawer we can use

```<code>import { createDrawerNavigator,DrawerItems} from 'react-navigation-drawer';
</code>```

this works and I have pasted my working code below

In ReactNative update they moved createDrawerNavigator and DrawerItems from react-navigation to react-navigation-drawer...

```<code>import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, ScrollView,Dimensions,Image } from 'react-native';

import { createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { createDrawerNavigator,DrawerItems} from 'react-navigation-drawer';

import Login from '../screens/Login';
import Home from '../screens/Home';

const CustomDrawComponent=(props) => (
    <SafeAreaView style={{flex:1}}>
        <View style={{paddingTop:45, backgroundColor:'green'}}>
      <View style={{height:150,alignItems:'center', justifyContent:'center'}}>
        <Image source={require('../assets/Logos/userPic.png')}
                style={{height:120,width:120,borderRadius:60}} />
      </View>
      </View>
      <ScrollView>
        <DrawerItems {...props}/>
      </ScrollView>
      <Text style={{paddingBottom:100, paddingLeft:65}}>Vision Cultura V1.0</Text>
    </SafeAreaView>
  )
const screens = createDrawerNavigator({
    Main: {
            screen: createStackNavigator({
            Home: {screen: Home},
            Login: {screen: Login},

        }, {initialRouteName: "Login"})
    },
    Home: Home,
    Login: Login

},
{
    contentComponent:CustomDrawComponent
});

const index = createAppContainer(screens);
export default index;
</code>```

Body:
I am trying to create new drawer navigation but getting this below error

Unable to resolve "react-native-screens" from "node_modules\@react-navigation\drawer\src\views\DrawerView.tsx"
Failed building JavaScript bundle.

but same code i tried in new empty project it worked with react-native-drawer in older version of "react-navigation": "^2.6.2" but the same not working in  "react-navigation": "^4.0.10", it shows that react-native-drawer is removed and @react-native/drawer is latest so we need to use that but its not working kindly help me resolving this...Code is in below

import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';

function Feed() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Feed Screen</Text>
    </View>
  );
}

function Article() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Article Screen</Text>
    </View>
  );
}

const Drawer = createDrawerNavigator();

function MyDrawer() {
  return (
    <Drawer.Navigator>
      <Drawer.Screen name="Feed" component={Feed} />
      <Drawer.Screen name="Article" component={Article} />
    </Drawer.Navigator>
  );
}

export default function DrawerNavigator() {
  return (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  );
}

Body:
I know this is not a right solution but anyway it worked for me...

instead of @react-navigation/drawer we can use

import { createDrawerNavigator,DrawerItems} from 'react-navigation-drawer';

this works and I have pasted my working code below

In ReactNative update they moved createDrawerNavigator and DrawerItems from react-navigation to react-navigation-drawer...

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, ScrollView,Dimensions,Image } from 'react-native';

import { createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { createDrawerNavigator,DrawerItems} from 'react-navigation-drawer';

import Login from '../screens/Login';
import Home from '../screens/Home';

const CustomDrawComponent=(props) => (
    <SafeAreaView style={{flex:1}}>
        <View style={{paddingTop:45, backgroundColor:'green'}}>
      <View style={{height:150,alignItems:'center', justifyContent:'center'}}>
        <Image source={require('../assets/Logos/userPic.png')}
                style={{height:120,width:120,borderRadius:60}} />
      </View>
      </View>
      <ScrollView>
        <DrawerItems {...props}/>
      </ScrollView>
      <Text style={{paddingBottom:100, paddingLeft:65}}>Vision Cultura V1.0</Text>
    </SafeAreaView>
  )
const screens = createDrawerNavigator({
    Main: {
            screen: createStackNavigator({
            Home: {screen: Home},
            Login: {screen: Login},

        }, {initialRouteName: "Login"})
    },
    Home: Home,
    Login: Login

},
{
    contentComponent:CustomDrawComponent
});

const index = createAppContainer(screens);
export default index;


问:
How to avoid line color repetition in matplotlib.pyplot?
I am comparing some algorithmic results using matplotlib.pyplot, however it is very difficult to understand what is going on since several lines have the same exact color. Is there a way to avoid this? I don't think that pyplot has only seven colors, has it?</p>

答:
Matplotlib has more than seven colors. You can specify your color in many ways (see http://matplotlib.sourceforge.net/api/colors_api.html).

For example, you can specify the color using an html hex string:

```<code>pyplot.plot(x, y, color='#112233')
</code>```

Body:
Matplotlib has more than seven colors. You can specify your color in many ways (see http://matplotlib.sourceforge.net/api/colors_api.html).

For example, you can specify the color using an html hex string:

pyplot.plot(x, y, color='#112233')


问:
Add data to list based on a data frame R
I have the following list and data frame:

```<code>my_list <- list(names = c("JEFF","PETE","JOE"),
                data = c(1,2,3),
                ascor = c("ANCHOR","BOAT"))
my_df <- data.frame(names = c("JEFF","PETE","JOE"),
                    debt = c(10,12,14))

</code>```

I would like to add a new element to the list called "debt" based on the data frame my_df. The new list should be (pardon me if I don't know how to express a list like a dataframe which shows as a table):

```<code>my_list <- list(names = c("JEFF","PETE","JOE"),
                data = c(1,2,3),
                debt = c(10,12,14),
                ascor = c("ANCHOR","BOAT"))
</code>```

I tried naively this code:

```<code>my_list %>% left_join(my_df, by = "names" )
</code>```

But it says is not applicable left join to an object list. Any help will be greatly appreciated.

答:
If we need to match and create an entry

```<code>my_list[["debt"]] <- my_df$debt[match(my_list$name, my_df$names)]
</code>```

Or with modifyList

```<code>modifyList(my_list, list(debt = my_df$debt[match(my_list$name, my_df$names)]))
</code>```

Body:
I have the following list and data frame:

my_list <- list(names = c("JEFF","PETE","JOE"),
                data = c(1,2,3),
                ascor = c("ANCHOR","BOAT"))
my_df <- data.frame(names = c("JEFF","PETE","JOE"),
                    debt = c(10,12,14))

I would like to add a new element to the list called "debt" based on the data frame my_df. The new list should be (pardon me if I don't know how to express a list like a dataframe which shows as a table):

my_list <- list(names = c("JEFF","PETE","JOE"),
                data = c(1,2,3),
                debt = c(10,12,14),
                ascor = c("ANCHOR","BOAT"))

I tried naively this code:

my_list %>% left_join(my_df, by = "names" )

But it says is not applicable left join to an object list. Any help will be greatly appreciated.

Body:
If we need to match and create an entry

my_list[["debt"]] <- my_df$debt[match(my_list$name, my_df$names)]

Or with modifyList

modifyList(my_list, list(debt = my_df$debt[match(my_list$name, my_df$names)]))


问:
How to insert missing time (by minutes) in data frame? And how to assign corresponding y values for that missing time as NA?
I have a data that looks like this:

```<code>SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:02   1
3   1/27/20 18:04   0
4   1/27/20 18:05   1
5   1/27/20 18:08   0
</code>```

How can make it look like this?

```<code>SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0
</code>```

Basically, my question is how can I insert missing timestamp and assign the corresponding MOTOR values as NA?

I would be thankful if anyone could help. I just started learning R and this is giving me headache since morning.

Thanks.

答:
You can create a dataframe with a timestamp being the sequence from the min and max values of your original dataframe  and then, make a left join (here using dplyr and lubridate):

library(lubridate)
library(dplyr)
df_or$TimeStamp = mdy_hm(df_or$TimeStamp) # Convert TimeStamp into appropriate date format

DF <- data.frame(TimeStamp = seq(min(df_or$TimeStamp),max(df_or$TimeStamp), by = "min"))
DF %>% left_join(., df_or, by = "TimeStamp")

            TimeStamp MOTOR
1 2020-01-27 18:00:00     0
2 2020-01-27 18:01:00    NA
3 2020-01-27 18:02:00     1
4 2020-01-27 18:03:00    NA
5 2020-01-27 18:04:00     0
6 2020-01-27 18:05:00     1
7 2020-01-27 18:06:00    NA
8 2020-01-27 18:07:00    NA
9 2020-01-27 18:08:00     0
```

<p><strong>Data</strong></p>

<pre class="lang-r prettyprint-override"><code>df_or <- data.frame(TimeStamp = c("1/27/20 18:00","1/27/20 18:02","1/27/20 18:04","1/27/20 18:05", "1/27/20 18:08"),
                    MOTOR = c(0,1,0,1,0))
</code>```

Body:
I have a data that looks like this:

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:02   1
3   1/27/20 18:04   0
4   1/27/20 18:05   1
5   1/27/20 18:08   0

How can make it look like this?

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0

Basically, my question is how can I insert missing timestamp and assign the corresponding MOTOR values as NA?

I would be thankful if anyone could help. I just started learning R and this is giving me headache since morning.

Thanks.

Body:
You can create a dataframe with a timestamp being the sequence from the min and max values of your original dataframe  and then, make a left join (here using dplyr and lubridate):

library(lubridate)
library(dplyr)
df_or$TimeStamp = mdy_hm(df_or$TimeStamp) # Convert TimeStamp into appropriate date format

DF <- data.frame(TimeStamp = seq(min(df_or$TimeStamp),max(df_or$TimeStamp), by = "min"))
DF %>% left_join(., df_or, by = "TimeStamp")

            TimeStamp MOTOR
1 2020-01-27 18:00:00     0
2 2020-01-27 18:01:00    NA
3 2020-01-27 18:02:00     1
4 2020-01-27 18:03:00    NA
5 2020-01-27 18:04:00     0
6 2020-01-27 18:05:00     1
7 2020-01-27 18:06:00    NA
8 2020-01-27 18:07:00    NA
9 2020-01-27 18:08:00     0

Data

df_or <- data.frame(TimeStamp = c("1/27/20 18:00","1/27/20 18:02","1/27/20 18:04","1/27/20 18:05", "1/27/20 18:08"),
                    MOTOR = c(0,1,0,1,0))