问:
Detect that a PDFView did scroll
Does PDFKit on iOS expose a PDFView's underlying UIScrollView or is there any other way to directly detect that the user has scrolled a PDFView?

My use case is to hide a nav bar when the document is scrolled so as a workaround I've added my own pan gesture recogniser to the PDFView's parent and I do the hiding in gestureRecognizerShouldBegin and always return false but I expect there's something more like UIScrollViewDelegate that I'm missing in the docs.

答:
Does PDFKit on iOS expose a PDFView's underlying UIScrollView

No, but hopefully Apple will add this in the future. I remember that UIWebView didn't have it originally and it was added later.

or is there any other way to directly detect that the user has scrolled a PDFView

No, it looks like none of the notifications provided by PDFViewDelegate address this.

I'm migrating from UIWebView to PDFView and am using scrollViewDidScroll for a bunch of stuff, so I didn't want to rely on just adding a pan gesture recognizer. Building from @Matthijs's answer, I'm finding the UIScrollView inside the PDFView, making my class its delegate, then passing any events back to the scroll view (which was its own delegate before my class became the delegate) so it can respond to them, too. With UIWebView, this last step was not necessary, but with PDFView, zooming and possibly other functions won't work without it.

I'm overriding all the documented delegate methods to reduce the chance that this will break if Apple changes the internal function of PDFView. However, I had to check respondsToSelector in each method, because the original scroll view delegate doesn't currently implement all of them.

```<code>- (void)viewDidLoad {
    // create the PDFView and find its inner scrollView
    self.pdfView = [[PDFView alloc] init];
    for (UIView *subview in self.pdfView.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            self.scrollView = (UIScrollView *)subview;
        } else {
            for (UIView *subsubview in subview.subviews) {
                if ([subsubview isKindOfClass:[UIScrollView class]]) {
                    self.scrollView = (UIScrollView *)subsubview;
                }
            }
        }
    }
}

- (void)loadPDFDocument:(NSString *)URL {
    // load a document, then become the delegate for the scrollView (we have to do that after loading the document)
    PDFDocument *document = [[PDFDocument alloc] initWithURL:URL];
    self.pdfView.document = document;
    self.scrollView.delegate = self;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // *** respond to scroll events here ***

    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
        [scrollViewDelegate scrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
        [scrollViewDelegate scrollViewWillBeginDragging:scrollView];
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:)]) {
        [scrollViewDelegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) {
        [scrollViewDelegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
    }
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewShouldScrollToTop:)]) {
        return [scrollViewDelegate scrollViewShouldScrollToTop:scrollView];
    }
    return TRUE;
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidScrollToTop:)]) {
        [scrollViewDelegate scrollViewDidScrollToTop:scrollView];
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)]) {
        [scrollViewDelegate scrollViewWillBeginDecelerating:scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) {
        [scrollViewDelegate scrollViewDidEndDecelerating:scrollView];
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
        return [scrollViewDelegate viewForZoomingInScrollView:scrollView];
    }
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginZooming:withView:)]) {
        [scrollViewDelegate scrollViewWillBeginZooming:scrollView withView:view];
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)]) {
        [scrollViewDelegate scrollViewDidEndZooming:scrollView withView:view atScale:scale];
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidZoom:)]) {
        [scrollViewDelegate scrollViewDidZoom:scrollView];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)]) {
        [scrollViewDelegate scrollViewDidEndScrollingAnimation:scrollView];
    }
}

- (void)scrollViewDidChangeAdjustedContentInset:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidChangeAdjustedContentInset:)]) {
        [scrollViewDelegate scrollViewDidChangeAdjustedContentInset:scrollView];
    }
}
</code>```

Title: Detect that a PDFView did scroll

Body:
Does PDFKit on iOS expose a PDFView's underlying UIScrollView

No, but hopefully Apple will add this in the future. I remember that UIWebView didn't have it originally and it was added later.

or is there any other way to directly detect that the user has scrolled a PDFView

No, it looks like none of the notifications provided by PDFViewDelegate address this.

I'm migrating from UIWebView to PDFView and am using scrollViewDidScroll for a bunch of stuff, so I didn't want to rely on just adding a pan gesture recognizer. Building from @Matthijs's answer, I'm finding the UIScrollView inside the PDFView, making my class its delegate, then passing any events back to the scroll view (which was its own delegate before my class became the delegate) so it can respond to them, too. With UIWebView, this last step was not necessary, but with PDFView, zooming and possibly other functions won't work without it.

I'm overriding all the documented delegate methods to reduce the chance that this will break if Apple changes the internal function of PDFView. However, I had to check respondsToSelector in each method, because the original scroll view delegate doesn't currently implement all of them.

- (void)viewDidLoad {
    // create the PDFView and find its inner scrollView
    self.pdfView = [[PDFView alloc] init];
    for (UIView *subview in self.pdfView.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            self.scrollView = (UIScrollView *)subview;
        } else {
            for (UIView *subsubview in subview.subviews) {
                if ([subsubview isKindOfClass:[UIScrollView class]]) {
                    self.scrollView = (UIScrollView *)subsubview;
                }
            }
        }
    }
}

- (void)loadPDFDocument:(NSString *)URL {
    // load a document, then become the delegate for the scrollView (we have to do that after loading the document)
    PDFDocument *document = [[PDFDocument alloc] initWithURL:URL];
    self.pdfView.document = document;
    self.scrollView.delegate = self;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // *** respond to scroll events here ***

    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidScroll:)]) {
        [scrollViewDelegate scrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) {
        [scrollViewDelegate scrollViewWillBeginDragging:scrollView];
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillEndDragging:withVelocity:targetContentOffset:)]) {
        [scrollViewDelegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) {
        [scrollViewDelegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
    }
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewShouldScrollToTop:)]) {
        return [scrollViewDelegate scrollViewShouldScrollToTop:scrollView];
    }
    return TRUE;
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidScrollToTop:)]) {
        [scrollViewDelegate scrollViewDidScrollToTop:scrollView];
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)]) {
        [scrollViewDelegate scrollViewWillBeginDecelerating:scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) {
        [scrollViewDelegate scrollViewDidEndDecelerating:scrollView];
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) {
        return [scrollViewDelegate viewForZoomingInScrollView:scrollView];
    }
    return nil;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewWillBeginZooming:withView:)]) {
        [scrollViewDelegate scrollViewWillBeginZooming:scrollView withView:view];
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)]) {
        [scrollViewDelegate scrollViewDidEndZooming:scrollView withView:view atScale:scale];
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidZoom:)]) {
        [scrollViewDelegate scrollViewDidZoom:scrollView];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)]) {
        [scrollViewDelegate scrollViewDidEndScrollingAnimation:scrollView];
    }
}

- (void)scrollViewDidChangeAdjustedContentInset:(UIScrollView *)scrollView {
    UIScrollView <UIScrollViewDelegate> *scrollViewDelegate = (UIScrollView <UIScrollViewDelegate> *)self.scrollView;
    if ([scrollViewDelegate respondsToSelector:@selector(scrollViewDidChangeAdjustedContentInset:)]) {
        [scrollViewDelegate scrollViewDidChangeAdjustedContentInset:scrollView];
    }
}


来源: stackexchange

问:
Visual Studio 2010 - Debug Breakpoint
Ive just created a new web site project , added a few lines of code in my .cs file set a break point, and nada, website works, but debug point is not hit.
Any ideas?

Im starting the project with Debugging, running on windows 7 64bit

thanks

答: Debugging with edit and continue in .net while running 64 bit code is not possible. Switch to forced x86 to start debugging.</p>

ContentLicense: CC BY-SA 3.0

Title: Visual Studio 2010 - Debug Breakpoint


问:
Update a record in Entity Framework Core
I have an existing record from database that I have retrieved using Entity Framework:

```<code> MyDataObject myExistingObject= _dbContext.data
   .Where(s => s.Id == myId).FirstOrDefaultAsync();
</code>```

Externally, I have received another MyDataObject newDataObjectForSameRow that contains updated information for myExistingObject - all fields except Primary Key, that is initially set to 0 in the newDataObjectForSameRow.

How can I instruct Entity Framework "replace the row that has currently myExistingObject by newDataObjectForSameRow, however keeping the same Primary Key"?

答:
Try to use below code:</p>

```<code>newDataObjectForSameRow.Id = myId;
MyDataObject myExistingObject = _dbContext.data.Where(s => s.Id == myId).FirstOrDefaultAsync();
_dbContext.Entry(myExistingObject).CurrentValues.SetValues(newDataObjectForSameRow);
_dbContext.SaveChanges();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an existing record from database that I have retrieved using Entity Framework:

 MyDataObject myExistingObject= _dbContext.data
   .Where(s => s.Id == myId).FirstOrDefaultAsync();

Externally, I have received another MyDataObject newDataObjectForSameRow that contains updated information for myExistingObject - all fields except Primary Key, that is initially set to 0 in the newDataObjectForSameRow.

How can I instruct Entity Framework "replace the row that has currently myExistingObject by newDataObjectForSameRow, however keeping the same Primary Key"?

Body:
Try to use below code:

newDataObjectForSameRow.Id = myId;
MyDataObject myExistingObject = _dbContext.data.Where(s => s.Id == myId).FirstOrDefaultAsync();
_dbContext.Entry(myExistingObject).CurrentValues.SetValues(newDataObjectForSameRow);
_dbContext.SaveChanges();


问:
How can I change the terminal line width in Visual Studio Code?
I'm using Visual Studio Code 1.18.1 on Mac OSX and the integrated terminal seems to have a fixed width of 36 characters that doesn't increase when I make the terminal window wider.

How can change the number of characters per line in the terminal?
Is it possible to make the lines wrap based on the terminal window width?

答:
UPDATE 1: As of now there is no option to disable word-wrap in VS Code integrated terminal ( internally running program like bash or zsh will get the same width as the vscode terminal area you can check with echo "COLUMNS=$COLUMNS" ) even popular terminal emulator like iTerm don't have this feature see this open issue #1790

now if you can not do this at vscode level you can try doing it on program lever ( like bash or zsh ) maybe there is some way by defining a setting in bashrc or zshrc but I can not find anything on internet

However there is a program which can make horizontal scroll available for you at program level and that is less -S you can pipe any output ( with help of | oprator ) in it like

```<code>echo " this is very long lorem ipsum text sldkfjdslfk jsdlfkj sldfkj sldfkj sdlfjs dlfkjsd flsd jfsdlkfsdlfkj slfkjs lflskdfjsldfjsdlfksdlfkjsdflksdjflsdkfj ssldfkjsdlkf jsdlfkj sdlfsjdlfksdf lsdfjk " | less -S
</code>```

you can scroll horizontally with help of arrow key for more shortcut see

```<code> h  H                 Display help.
 q  :q  Q  :Q  ZZ     Exit.
</code>```

I am using version 1.42.1 and it works as expected maybe you can try updating it to the latest version

I also checked the configuration ( command + , ) there wasn't any setting related to width of the integrated terminal

Body:
UPDATE 1: As of now there is no option to disable word-wrap in VS Code integrated terminal ( internally running program like bash or zsh will get the same width as the vscode terminal area you can check with echo "COLUMNS=$COLUMNS" ) even popular terminal emulator like iTerm don't have this feature see this open issue #1790

now if you can not do this at vscode level you can try doing it on program lever ( like bash or zsh ) maybe there is some way by defining a setting in bashrc or zshrc but I can not find anything on internet

However there is a program which can make horizontal scroll available for you at program level and that is less -S you can pipe any output ( with help of | oprator ) in it like

echo " this is very long lorem ipsum text sldkfjdslfk jsdlfkj sldfkj sldfkj sdlfjs dlfkjsd flsd jfsdlkfsdlfkj slfkjs lflskdfjsldfjsdlfksdlfkjsdflksdjflsdkfj ssldfkjsdlkf jsdlfkj sdlfsjdlfksdf lsdfjk " | less -S

you can scroll horizontally with help of arrow key for more shortcut see

 h  H                 Display help.
 q  :q  Q  :Q  ZZ     Exit.

I am using version 1.42.1 and it works as expected maybe you can try updating it to the latest version

I also checked the configuration ( command + , ) there wasn't any setting related to width of the integrated terminal


问:
WebRequest on .NET Core 3.0 fails the second time due to SSL handshake exception
The problem is that the code below succeeds if you run it once but fails if you run it twice during the same lifetime of a program.

var request = (HttpWebRequest)WebRequest.Create("https://google.com");
var response = (HttpWebResponse)await request.GetResponseAsync();
```

<p>I have <strong>.NET Core 3.0</strong> and <strong>SDK Version 3.0.100</strong>.</p>

<h1>Reproduce:</h1>

<ol>
<li><code>dotnet new console -n test-ssl</code> <code>cd test-ssl</code>.</li>
<li>Open <code>Program.cs</code>.</li>
<li>Replace content with:</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace test_ssl
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await CallGoogle();
            await CallGoogle();
        }

        private static async Task CallGoogle()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://google.com");
            var response = (HttpWebResponse)await request.GetResponseAsync();
            var jsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
            Console.WriteLine(jsonResponse);
        }
    }
}
</code>```

dotnet run.

This will crash with the exception:

```<code>Unhandled exception. System.Net.WebException: The SSL connection could not be established, see inner exception. The handshake failed due to an unexpected packet format.
 ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Security.SslStream.ThrowIfExceptional()
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at System.Net.HttpWebRequest.SendRequest()
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebRequest.<>c.<GetResponseAsync>b__68_2(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at test_ssl.Program.CallGoogle() in C:\Users\me\source\Workspaces\tests\test-ssl\Program.cs:line 19
   at test_ssl.Program.Main(String[] args) in C:\Users\me\source\Workspaces\tests\test-ssl\Program.cs:line 13
   at test_ssl.Program.<Main>(String[] args)
</code>```

Why would it fail the second time?

This issue is posted in .NET Core on github also since it seems related to that: https://github.com/dotnet/core/issues/3847

Further tests to narrow down the problem

.NET Framework 4.8 - WORKING

Using .NET Framework 4.8 Console app does work however. So using the original Program.cs file works here. Seems like the real problem is in .NET Core 3.0

.NET Core 3.0 in Docker - WORKING

```<code>docker run --rm -it mcr.microsoft.com/dotnet/core/sdk:3.0
dotnet new console -n test-ssl
cd test-ssl
// Replace content of Program.cs again.
dotnet run
// Everything works.
</code>```

This leads me to believe that there is something on my machine that is broken and perhaps not a firewall problem either since in the end the docker container will go through the same firewall as my computer to reach google.

Powershell Test - WORKING

test-ssl.ps1

```<code>Invoke-WebRequest -Uri 'https://google.com'
Invoke-WebRequest -Uri 'https://google.com'
</code>```

HttpClient .NET Core 3.0 - NOT WORKING

Using HttpClient gives the same error. So replacing the content of CallGoogle with the below doesn't work:

```<code>var client = new HttpClient();
await client.GetStringAsync("https://google.com");
</code>```

答: Seems like the system must have been corrupt somehow since it's basically working everywhere else. Got a new PC that is working.</p>

Body:
The problem is that the code below succeeds if you run it once but fails if you run it twice during the same lifetime of a program.

var request = (HttpWebRequest)WebRequest.Create("https://google.com");
var response = (HttpWebResponse)await request.GetResponseAsync();

I have .NET Core 3.0 and SDK Version 3.0.100.

Reproduce:

dotnet new console -n test-ssl cd test-ssl.

Open Program.cs.

Replace content with:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace test_ssl
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await CallGoogle();
            await CallGoogle();
        }

        private static async Task CallGoogle()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://google.com");
            var response = (HttpWebResponse)await request.GetResponseAsync();
            var jsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
            Console.WriteLine(jsonResponse);
        }
    }
}

dotnet run.

This will crash with the exception:

Unhandled exception. System.Net.WebException: The SSL connection could not be established, see inner exception. The handshake failed due to an unexpected packet format.
 ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.IO.IOException: The handshake failed due to an unexpected packet format.
   at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Security.SslStream.ThrowIfExceptional()
   at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
   at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
   at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at System.Net.HttpWebRequest.SendRequest()
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebRequest.<>c.<GetResponseAsync>b__68_2(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at test_ssl.Program.CallGoogle() in C:\Users\me\source\Workspaces\tests\test-ssl\Program.cs:line 19
   at test_ssl.Program.Main(String[] args) in C:\Users\me\source\Workspaces\tests\test-ssl\Program.cs:line 13
   at test_ssl.Program.(String[] args)

Why would it fail the second time?

This issue is posted in .NET Core on github also since it seems related to that: https://github.com/dotnet/core/issues/3847

Further tests to narrow down the problem

.NET Framework 4.8 - WORKING

Using .NET Framework 4.8 Console app does work however. So using the original Program.cs file works here. Seems like the real problem is in .NET Core 3.0

.NET Core 3.0 in Docker - WORKING

docker run --rm -it mcr.microsoft.com/dotnet/core/sdk:3.0
dotnet new console -n test-ssl
cd test-ssl
// Replace content of Program.cs again.
dotnet run
// Everything works.

This leads me to believe that there is something on my machine that is broken and perhaps not a firewall problem either since in the end the docker container will go through the same firewall as my computer to reach google.

Powershell Test - WORKING

test-ssl.ps1

Invoke-WebRequest -Uri 'https://google.com'
Invoke-WebRequest -Uri 'https://google.com'

HttpClient .NET Core 3.0 - NOT WORKING

Using HttpClient gives the same error. So replacing the content of CallGoogle with the below doesn't work:

var client = new HttpClient();
await client.GetStringAsync("https://google.com");


问:
How can I wait until a HttpServer has finished (i.e. join its background thread)?
I have this code:

import com.sun.net.httpserver.HttpServer;

...

DatabaseConnection dbConnection = ...
HttpServer server = HttpServer.create();
server.createContext("/endpoint", new MyHandler(dbConnection));
server.start();

// What should I do here in order to wait until `server` stops?

dbConnection.close()
```

The com.sun.net.httpserver.HttpServer#start documentation states: "Starts this server in a new background thread."

I would like to call dbConnection.close() after server's background thread stops executing (which may happen e.g. because I press Ctrl+C). But the HttpServer documentation doesn't specify any way to access the background thread, so I can't figure out how to .join() it.

How can I wait until the HttpServer's background thread stops? Or is there another way I can ensure that dbConnection.close() is called when my app shuts down?

答:
One way to ensure that dbConnection gets closed when the Java process terminates is to add a shutdown hook:

```<code>Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    dbConnection.close();
}));
</code>```

In order to use this approach, dbConnection must be effectively final so that it can be captured in the lambda.

Body:
I have this code:

import com.sun.net.httpserver.HttpServer;

...

DatabaseConnection dbConnection = ...
HttpServer server = HttpServer.create();
server.createContext("/endpoint", new MyHandler(dbConnection));
server.start();

// What should I do here in order to wait until `server` stops?

dbConnection.close()

The com.sun.net.httpserver.HttpServer#start documentation states: "Starts this server in a new background thread."

I would like to call dbConnection.close() after server's background thread stops executing (which may happen e.g. because I press Ctrl+C). But the HttpServer documentation doesn't specify any way to access the background thread, so I can't figure out how to .join() it.

How can I wait until the HttpServer's background thread stops? Or is there another way I can ensure that dbConnection.close() is called when my app shuts down?

Body:
One way to ensure that dbConnection gets closed when the Java process terminates is to add a shutdown hook:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    dbConnection.close();
}));

In order to use this approach, dbConnection must be effectively final so that it can be captured in the lambda.


问:
Add a Class with byte[] to NSUserDefaults in iOS Share Extension (Xamarin)
In Xamarin.iOS Share Extension, I'd like to store my selected files (like pdf, images, word etc.) in my NSUserDefaults and when the main application starts, I'll have access to the files stored in it.

Here is my file class :

```<code>public class MyClass {
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}
</code>```

So in LoadItem in DidSelectPost methods, I create by object by using byte[] of files. Then for saving datas in NSUserDefaults, I convert my object to JSON like this (by using Newtonsoft.Json library):

```<code>string jsonString = JsonConvert.SerializeObject(myFileObject);
</code>```

and I set it to NSUserDefaults object like that:

```<code>NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing" + count));
</code>```

or

```<code>NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing"+ count));
</code>```

And after I'll synchronise my items : NSUser.Synchronize());

Everything goes well, but when the main application open, the new data is not here.

```<code>string toDesralize = nSUser.StringForKey("FileSharing0");
</code>```

I've tried for many files, and I've found out that this issue works only for files with low height and it doesn't work for files like 14mb. How can i save files with high height in NSUserDefaults? Is there any other way for doing the same job ?

答:
You can use file system to store and read data in Xamarin.iOS:

```<code>    var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var filename = Path.Combine(documents, "Write.txt");
    //save text
    File.WriteAllText(filename, "Write this text into a file");
    //save bytes
    File.WriteAllBytes(filename,yourBytes);
</code>```

And the read methods:

```<code>    var text = File.ReadAllText("TestData/ReadMe.txt");
    Console.WriteLine(text);
    var bytes = File.ReadAllBytes("path");
</code>```

Body:
In Xamarin.iOS Share Extension, I'd like to store my selected files (like pdf, images, word etc.) in my NSUserDefaults and when the main application starts, I'll have access to the files stored in it.

Here is my file class :

public class MyClass {
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

So in LoadItem in DidSelectPost methods, I create by object by using byte[] of files. Then for saving datas in NSUserDefaults, I convert my object to JSON like this (by using Newtonsoft.Json library):

string jsonString = JsonConvert.SerializeObject(myFileObject);

and I set it to NSUserDefaults object like that:

NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing" + count));

or

NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing"+ count));

And after I'll synchronise my items : NSUser.Synchronize());

Everything goes well, but when the main application open, the new data is not here.

string toDesralize = nSUser.StringForKey("FileSharing0");

I've tried for many files, and I've found out that this issue works only for files with low height and it doesn't work for files like 14mb. How can i save files with high height in NSUserDefaults? Is there any other way for doing the same job ?

Body:
You can use file system to store and read data in Xamarin.iOS:

    var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var filename = Path.Combine(documents, "Write.txt");
    //save text
    File.WriteAllText(filename, "Write this text into a file");
    //save bytes
    File.WriteAllBytes(filename,yourBytes);

And the read methods:

    var text = File.ReadAllText("TestData/ReadMe.txt");
    Console.WriteLine(text);
    var bytes = File.ReadAllBytes("path");


问:
Webclient map nested object
I'm using WebClient to consume ai API

The node I need from the response is nested inside

example API response

```<code>{
    "api": {
        "results": 129,
        "countries": [
            {
                "country": "Albania",
                "code": "AL",
                "flag": "https:\/\/media.api-football.com\/flags\/al.svg"
            },
            {
                "country": "Algeria",
                "code": "DZ",
                "flag": "https:\/\/media.api-football.com\/flags\/dz.svg"
            }

        ]
    }
}
</code>```

I only need to map each country to a POJO but the only way I was able to do it so was by composing complex objects in order to achieve the same representation as to the API response.

```<code>public class CountryResponse {
    private Countries api;
}

public class Countries {
    private int results;
    private List<Country> countries;
}

public class Country {
    private String country;
    private String code;
    private String flag
}
</code>```

And then I call the API

```<code>CountryResponse countryResponse = webClient
            .get()
            .uri("countries")
            .retrieve()
            .bodyToMono(CountryResponse.class)
            .block();
</code>```

I would like to avoid the need for creating very complex objects only to be able to map a given node inside the JSON response from the API

答:
I only need to map each country to a POJO but the only way I was able
  to do it so was by composing complex objects

Pardon me but I fail to see any complex objects provided in your example. On the contrary a POJO is the simplest object there is in the language. It's just a data container without any behavior.

So what you're doing is fetching some data from an API and flesh it out in POJOs in order to use them in your application. I see nothing wrong with that.

Now, if you want to simplify so bad you could do something about Countries.results since you may obtain that information from Countries.countries.Size(), but again I'm not sure if it's worth the effort or if it's going to put you in more trouble.

Title: Webclient map nested object

Body:
I'm using WebClient to consume ai API

The node I need from the response is nested inside

example API response

{
    "api": {
        "results": 129,
        "countries": [
            {
                "country": "Albania",
                "code": "AL",
                "flag": "https:\/\/media.api-football.com\/flags\/al.svg"
            },
            {
                "country": "Algeria",
                "code": "DZ",
                "flag": "https:\/\/media.api-football.com\/flags\/dz.svg"
            }

        ]
    }
}

I only need to map each country to a POJO but the only way I was able to do it so was by composing complex objects in order to achieve the same representation as to the API response.

public class CountryResponse {
    private Countries api;
}

public class Countries {
    private int results;
    private List<Country> countries;
}

public class Country {
    private String country;
    private String code;
    private String flag
}

And then I call the API

CountryResponse countryResponse = webClient
            .get()
            .uri("countries")
            .retrieve()
            .bodyToMono(CountryResponse.class)
            .block();

I would like to avoid the need for creating very complex objects only to be able to map a given node inside the JSON response from the API


问:
Why does this recursive algorithm (sudoku solver) prints the board back into its original state?
I am learning about backtracking and recursion and I don't understand (or can't visualize in my head) why my initial algorithm prints the board back into its original state, instead of printing the solution.

Here is my first attempt to solve the problem:

```<code>
grid = [
    [7,8,0,4,0,0,1,2,0],
    [6,0,0,0,7,5,0,0,9],
    [0,0,0,6,0,1,0,7,8],
    [0,0,7,0,4,0,2,6,0],
    [0,0,1,0,5,0,9,3,0],
    [9,0,4,0,6,0,0,0,5],
    [0,7,0,3,0,0,0,1,2],
    [1,2,0,0,0,7,4,0,0],
    [0,4,9,2,0,6,0,0,7]
]

def print_grid(grid):
    rows = len(grid)
    cols = len(grid[0])

    for y in range(rows):
        if y % 3 == 0 and y != 0:
            print("- " * (cols + 3))
        for x in range(cols):
            if x % 3 == 0 and x != 0:
                print(" | ", end="")
            if x == 8:
                print(grid[y][x])
            else:
                print(str(grid[y][x]) + " ", end="")

def find_empty(grid):
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                return (y, x)

def possible(grid, y, x, n):
    # check rows
    for i in range(9):
        if grid[i][x] == n:
            return False

    # check cols
    for i in range(9):
        if grid[y][i] == n:
            return False

    # check subgrid
    y0 = (y // 3) * 3
    x0 = (x // 3) * 3
    for i in range(3):
        for j in range(3):
            if grid[y0+i][x0+j] == n:
                return False
    return True

def solve(grid):
    empty = find_empty(grid)
    if not empty:
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            solve(grid)
            grid[y][x] = 0

solve(grid)
print_grid(grid)

</code>```

After changing the solve function to the code below, I got the expected result.

```<code>def solve(grid):
    empty = find_empty(grid)
    if not empty:
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            # changed this part
            if solve(grid):
                return True
            grid[y][x] = 0
</code>```

Wouldn't the first exit point in the function "if not empty" be enough?

答:
I also had a hard time wrapping my head around all these crazy recursion, but I kind of managed to understand. Your error is due to the line

```<code>grid[y][x] = 0
</code>```

because this actually overwrites the correct board (try adding print_grid(grid) inside the condition if not empty:) after it is solved.

I think it is faster to understand the correct code instead of understanding why the original code did not work.
I added some printing lines so it is easier to understand.

```<code>def solve(grid):
    empty = find_empty(grid)
    if not empty:
        print("board completed")
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            if solve(grid):
                print("board is completed! do not reset anymore")
                return True
            print((y,x), " is not", n, " !!! reset this!!!")
            grid[y][x] = 0
</code>```

which prints:

```<code>(0, 4)  is not 9  !!! reset this!!!
(0, 2)  is not 3  !!! reset this!!!
(2, 1)  is not 9  !!! reset this!!!
(2, 0)  is not 3  !!! reset this!!!
(2, 1)  is not 3  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 2  !!! reset this!!!
(4, 8)  is not 4  !!! reset this!!!
(4, 5)  is not 2  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 8  !!! reset this!!!
(3, 8)  is not 1  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 5  !!! reset this!!!
(3, 0)  is not 3  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 2  !!! reset this!!!
(4, 8)  is not 4  !!! reset this!!!
(4, 5)  is not 2  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 8  !!! reset this!!!
(3, 8)  is not 1  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 3  !!! reset this!!!
(3, 0)  is not 5  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 3  !!! reset this!!!
(3, 5)  is not 3  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(6, 5)  is not 4  !!! reset this!!!
(6, 4)  is not 8  !!! reset this!!!
(7, 3)  is not 5  !!! reset this!!!
(7, 2)  is not 8  !!! reset this!!!
(6, 6)  is not 8  !!! reset this!!!
(6, 5)  is not 4  !!! reset this!!!
(6, 4)  is not 9  !!! reset this!!!
(6, 2)  is not 6  !!! reset this!!!
board completed
</code>```

basically, not empty is only going to be true when the board is filled correctly. Because if any of the number is in the wrong position, eventually that wrong number is going to be reset by grid[y][x] = 0, and tested with another number.

If the board is completed and   if not empty: return True was executed, if solve(grid): will know that it shouldn't reset the board anymore, so it returns True. This will escape from the function, which means grid[y][x] = 0 line is going to be skipped.

If you don't understand, try printing in between each line so you can get the idea of what is going on. Hope this helped :)

Body:
I am learning about backtracking and recursion and I don't understand (or can't visualize in my head) why my initial algorithm prints the board back into its original state, instead of printing the solution.

Here is my first attempt to solve the problem:

grid = [
    [7,8,0,4,0,0,1,2,0],
    [6,0,0,0,7,5,0,0,9],
    [0,0,0,6,0,1,0,7,8],
    [0,0,7,0,4,0,2,6,0],
    [0,0,1,0,5,0,9,3,0],
    [9,0,4,0,6,0,0,0,5],
    [0,7,0,3,0,0,0,1,2],
    [1,2,0,0,0,7,4,0,0],
    [0,4,9,2,0,6,0,0,7]
]

def print_grid(grid):
    rows = len(grid)
    cols = len(grid[0])

    for y in range(rows):
        if y % 3 == 0 and y != 0:
            print("- " * (cols + 3))
        for x in range(cols):
            if x % 3 == 0 and x != 0:
                print(" | ", end="")
            if x == 8:
                print(grid[y][x])
            else:
                print(str(grid[y][x]) + " ", end="")

def find_empty(grid):
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                return (y, x)

def possible(grid, y, x, n):
    # check rows
    for i in range(9):
        if grid[i][x] == n:
            return False

    # check cols
    for i in range(9):
        if grid[y][i] == n:
            return False

    # check subgrid
    y0 = (y // 3) * 3
    x0 = (x // 3) * 3
    for i in range(3):
        for j in range(3):
            if grid[y0+i][x0+j] == n:
                return False
    return True

def solve(grid):
    empty = find_empty(grid)
    if not empty:
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            solve(grid)
            grid[y][x] = 0

solve(grid)
print_grid(grid)

After changing the solve function to the code below, I got the expected result.

def solve(grid):
    empty = find_empty(grid)
    if not empty:
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            # changed this part
            if solve(grid):
                return True
            grid[y][x] = 0

Wouldn't the first exit point in the function "if not empty" be enough?

Body:
I also had a hard time wrapping my head around all these crazy recursion, but I kind of managed to understand. Your error is due to the line

grid[y][x] = 0

because this actually overwrites the correct board (try adding print_grid(grid) inside the condition if not empty:) after it is solved.

I think it is faster to understand the correct code instead of understanding why the original code did not work.
I added some printing lines so it is easier to understand.

def solve(grid):
    empty = find_empty(grid)
    if not empty:
        print("board completed")
        return True
    y, x = empty
    for n in range(1, 10):
        if possible(grid, y, x, n):
            grid[y][x] = n
            if solve(grid):
                print("board is completed! do not reset anymore")
                return True
            print((y,x), " is not", n, " !!! reset this!!!")
            grid[y][x] = 0

which prints:

(0, 4)  is not 9  !!! reset this!!!
(0, 2)  is not 3  !!! reset this!!!
(2, 1)  is not 9  !!! reset this!!!
(2, 0)  is not 3  !!! reset this!!!
(2, 1)  is not 3  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 2  !!! reset this!!!
(4, 8)  is not 4  !!! reset this!!!
(4, 5)  is not 2  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 8  !!! reset this!!!
(3, 8)  is not 1  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 5  !!! reset this!!!
(3, 0)  is not 3  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 2  !!! reset this!!!
(4, 8)  is not 4  !!! reset this!!!
(4, 5)  is not 2  !!! reset this!!!
(4, 3)  is not 7  !!! reset this!!!
(4, 1)  is not 6  !!! reset this!!!
(4, 0)  is not 8  !!! reset this!!!
(3, 8)  is not 1  !!! reset this!!!
(3, 5)  is not 8  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 3  !!! reset this!!!
(3, 0)  is not 5  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(3, 3)  is not 9  !!! reset this!!!
(3, 1)  is not 3  !!! reset this!!!
(3, 5)  is not 3  !!! reset this!!!
(3, 3)  is not 1  !!! reset this!!!
(6, 5)  is not 4  !!! reset this!!!
(6, 4)  is not 8  !!! reset this!!!
(7, 3)  is not 5  !!! reset this!!!
(7, 2)  is not 8  !!! reset this!!!
(6, 6)  is not 8  !!! reset this!!!
(6, 5)  is not 4  !!! reset this!!!
(6, 4)  is not 9  !!! reset this!!!
(6, 2)  is not 6  !!! reset this!!!
board completed

basically, not empty is only going to be true when the board is filled correctly. Because if any of the number is in the wrong position, eventually that wrong number is going to be reset by grid[y][x] = 0, and tested with another number.

If the board is completed and   if not empty: return True was executed, if solve(grid): will know that it shouldn't reset the board anymore, so it returns True. This will escape from the function, which means grid[y][x] = 0 line is going to be skipped.

If you don't understand, try printing in between each line so you can get the idea of what is going on. Hope this helped :)


问:
Change axios Response Schema
As axios GitHub page states, default response of axios request is:

```<code>{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}
</code>```

Problem:

My API response schema is:

```<code>{
  success: true,
  message: '',
  data: {}
}
</code>```

So every time I make a request, I have to handle the response like:

```<code>(...).then((res) => res.data.data);
</code>```

How can I change the response schema of axios to avoid doing .data.data every time?

答:
You can use a response interceptor to change the value of the promise:

axios.interceptors.response.use(function (response) {
  return response.data.data
})
```

<p>You'd just do this once and then it would apply to all requests made via the default <code>axios</code> instance. A similar approach can be taken if you're creating your own <code>axios</code> instances using <code>axios.create</code>.</p>

<p>You may also need to consider how to handle error cases but the approach is much the same.</p>

<p>Documentation: https://github.com/axios/axios#interceptors</p>

<p><strong>Update:</strong></p>

<p>If you need access to <code>success</code>, <code>message</code> and <code>data</code> you would just need this instead:</p>

<pre class="lang-js prettyprint-override"><code>axios.interceptors.response.use(function (response) {
  return response.data
})
</code>```

Destructuring would potentially be useful when you write the then handler:

(...).then(({ data, success, message }) => {

});
```

Title: Change axios Response Schema

Body:
As axios GitHub page states, default response of axios request is:

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

Problem:

My API response schema is:

{
  success: true,
  message: '',
  data: {}
}

So every time I make a request, I have to handle the response like:

(...).then((res) => res.data.data);

How can I change the response schema of axios to avoid doing .data.data every time?

Body:
You can use a response interceptor to change the value of the promise:

axios.interceptors.response.use(function (response) {
  return response.data.data
})

You'd just do this once and then it would apply to all requests made via the default axios instance. A similar approach can be taken if you're creating your own axios instances using axios.create.

You may also need to consider how to handle error cases but the approach is much the same.

Documentation: https://github.com/axios/axios#interceptors

Update:

If you need access to success, message and data you would just need this instead:

axios.interceptors.response.use(function (response) {
  return response.data
})

Destructuring would potentially be useful when you write the then handler:

(...).then(({ data, success, message }) => {

});


答:
The best way to ensure that something will always close is to use a Try with Resources
this construct will always close whatever Closeable is supplied to the parenthesis when the block of code is finished executing.

Here is an example.

```<code>try(dbConnection) {
// do any sort of work inside this block.
}
</code>```

The dbConnection or Closeable will ensured to be closed this way.

Try with Resources
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Title: How can I wait until a HttpServer has finished (i.e. join its background thread)?

Body:
The best way to ensure that something will always close is to use a Try with Resources
this construct will always close whatever Closeable is supplied to the parenthesis when the block of code is finished executing.

Here is an example.

try(dbConnection) {
// do any sort of work inside this block.
}

The dbConnection or Closeable will ensured to be closed this way.

Try with Resources
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


问:
How to make the progressbar work, It freezes the window
I tried making the progressbar but instead of working, it freezes the tkinter window, I also tried closing it but it froze the window

```<code>from tkinter import *
from tkinter.ttk import *
import time

root = Tk()

pbar = Progressbar(root, orient = HORIZONTAL,
                       length = 100, mode = 'determinate')

def bar():
    pbar['value'] = 20
    time.sleep(0.5)

    pbar['value'] = 40
    time.sleep(0.5)

    pbar['value'] = 60
    time.sleep(0.5)

    pbar['value'] = 80
    time.sleep(0.5)

    pbar['value'] = 100

pbar.pack()

Button(root, text = 'Start Bar', command = bar).pack()

root.mainloop()
</code>```

How to make it work !

答:
While the answer seems to work, it locks your GUI during the 0.5 second time.sleep intervals.

A more straight forward way is to use root.after:

```<code>...

def bar():
    pbar['value']+=20
    if pbar["value"]!=100:
        root.after(500, bar)

pbar.pack()

...
</code>```

Body:
I tried making the progressbar but instead of working, it freezes the tkinter window, I also tried closing it but it froze the window

from tkinter import *
from tkinter.ttk import *
import time

root = Tk()

pbar = Progressbar(root, orient = HORIZONTAL,
                       length = 100, mode = 'determinate')

def bar():
    pbar['value'] = 20
    time.sleep(0.5)

    pbar['value'] = 40
    time.sleep(0.5)

    pbar['value'] = 60
    time.sleep(0.5)

    pbar['value'] = 80
    time.sleep(0.5)

    pbar['value'] = 100

pbar.pack()

Button(root, text = 'Start Bar', command = bar).pack()

root.mainloop()

How to make it work !

Body:
While the answer seems to work, it locks your GUI during the 0.5 second time.sleep intervals.

A more straight forward way is to use root.after:

...

def bar():
    pbar['value']+=20
    if pbar["value"]!=100:
        root.after(500, bar)

pbar.pack()

...


问:
Dice Simulator project in Python 3
My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop? </p>

<hr>

```<code>import random

min = 1
max = 6

prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)

while roll_dice:

    if roll_dice == "yes":
        print ("you rolled", random.randint(min, max), random.randint(min, max))
        input(prompt)

    elif roll_dice == "no":
        print ("see you later!")
        break

    else:
        print ("invalid answer")
        break
</code>```

答:
You can modify the code in this manner:

```<code>while roll_dice =="yes":
      print ("you rolled", random.randint(min, max), random.randint(min, max))
      roll_dice = input(prompt)
</code>```

You must include roll_dice for getting the return value from the input function and validating if the response is yes, no or invalid.

In your code, input returns a value but that value is never checked after the if statement is executed once.

```<code>while roll_dice =="yes":
      print ("you rolled", random.randint(min, max), random.randint(min, max))
      input(prompt)
</code>```

Title: Dice Simulator project in Python 3

Body:
My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop?

import random

min = 1
max = 6

prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)

while roll_dice:

    if roll_dice == "yes":
        print ("you rolled", random.randint(min, max), random.randint(min, max))
        input(prompt)

    elif roll_dice == "no":
        print ("see you later!")
        break

    else:
        print ("invalid answer")
        break

Body:
You can modify the code in this manner:

while roll_dice =="yes":
      print ("you rolled", random.randint(min, max), random.randint(min, max))
      roll_dice = input(prompt)

You must include roll_dice for getting the return value from the input function and validating if the response is yes, no or invalid.

In your code, input returns a value but that value is never checked after the if statement is executed once.

while roll_dice =="yes":
      print ("you rolled", random.randint(min, max), random.randint(min, max))
      input(prompt)


问:
How to avoid use of crawler in aws glue
AWS glue crawler has cost associated with it, how to avoid us of the crawler in aws glue.

Is there any way we can avoid the use of crawler and infer schema from any other option, so that cost can be reduced.

答:
In addition to what bdcloud has said, it's also possible to add tables to the data catalogue using the 'AWS::Glue::Table' resource in CloudFormation.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html

It's easier to do this if you have a table schema you can use as a template (aws glue get-table --database-name <db name> --name
 will give you JSON that is pretty close to what CloudFormation is expecting).

Again, you need to know your schema in advance, but choose the approach that best fits the workflow you're going with.

Title: How to avoid use of crawler in aws glue

Body:
In addition to what bdcloud has said, it's also possible to add tables to the data catalogue using the 'AWS::Glue::Table' resource in CloudFormation.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html

It's easier to do this if you have a table schema you can use as a template (aws glue get-table --database-name <db name> --name <table name> will give you JSON that is pretty close to what CloudFormation is expecting).

Again, you need to know your schema in advance, but choose the approach that best fits the workflow you're going with.


问:
How can I get additional data from one promise to another?
I have one promise that relies on the return value of another promise. I'm successfully passing that value to the second promise, but there's additional data that's created in the first promise that I'd like to get into the second promise somehow.

Here's my code:

```<code>const getAlbumInfo = async (album, artist) => {
        let hostname = 'http://www.musicbrainz.org';
        let path = `/ws/2/release-group/?query=release:${album}%20AND%20artist:${artist}&fmt=json`;
        let res = await fetch(hostname + path);
        return res.json();
};

const getAlbumArt = async (albumInfo) => {
    let res = await fetch(`${albumInfo.url}`);
    return res.json();
};

let artist = '', album = '';

getAlbumInfo(album, artist)
    .then((res) => {
        const metadata = {
            album: res['album'],
            artist: res['artist'],
            url: res['url']
        };

        return getAlbumArt(metadata);
    })
    .then((res) => {
        console.log(res);  // prints result from getAlbumArt

        // I also need the contents of metadata here
    })
    .catch(e => { console.error(e); });
</code>```

So I'm getting album metadata in the first promise, which includes a URL, and then I'm running a fetch on that URL, which returns a second promise. The problem is that I need access to the album metadata in the second promise.

Since I'm returning/passing the metadata into the second promise, I tried using Object.assign() inside getAlbumArt() to combine the metadata and the fetch result, but that didn't seem to work.

答:
Since you could use async/await, we could solve the problem using this too. It's better to consistent using async/await instead of mix it with Promise.

To do that, we need IIFE

(async () => { // define IIFE
  try { // try-catch to ensure error is catched
    const res = await getAlbumInfo(album, artist);

    const metadata = {
      album: res["album"],
      artist: res["artist"],
      url: res["url"]
    };

    const res2 = await getAlbumArt(metadata);

    console.log(res2);
    console.log(metadata);

  } catch (error) {
    console.error(error);
  }
})();
```

Hope it helps

Body:
I have one promise that relies on the return value of another promise. I'm successfully passing that value to the second promise, but there's additional data that's created in the first promise that I'd like to get into the second promise somehow.

Here's my code:

const getAlbumInfo = async (album, artist) => {
        let hostname = 'http://www.musicbrainz.org';
        let path = `/ws/2/release-group/?query=release:${album}%20AND%20artist:${artist}&fmt=json`;
        let res = await fetch(hostname + path);
        return res.json();
};

const getAlbumArt = async (albumInfo) => {
    let res = await fetch(`${albumInfo.url}`);
    return res.json();
};

let artist = '', album = '';

getAlbumInfo(album, artist)
    .then((res) => {
        const metadata = {
            album: res['album'],
            artist: res['artist'],
            url: res['url']
        };

        return getAlbumArt(metadata);
    })
    .then((res) => {
        console.log(res);  // prints result from getAlbumArt

        // I also need the contents of metadata here
    })
    .catch(e => { console.error(e); });

So I'm getting album metadata in the first promise, which includes a URL, and then I'm running a fetch on that URL, which returns a second promise. The problem is that I need access to the album metadata in the second promise.

Since I'm returning/passing the metadata into the second promise, I tried using Object.assign() inside getAlbumArt() to combine the metadata and the fetch result, but that didn't seem to work.

Body:
Since you could use async/await, we could solve the problem using this too. It's better to consistent using async/await instead of mix it with Promise.

To do that, we need IIFE

(async () => { // define IIFE
  try { // try-catch to ensure error is catched
    const res = await getAlbumInfo(album, artist);

    const metadata = {
      album: res["album"],
      artist: res["artist"],
      url: res["url"]
    };

    const res2 = await getAlbumArt(metadata);

    console.log(res2);
    console.log(metadata);

  } catch (error) {
    console.error(error);
  }
})();

Hope it helps


问:
React hooks update sort of whenever they feel like it
So, I'm using hooks to manage the state of a set of forms, set up like so:

```<code>    const [fieldValues, setFieldValues] = useState({}) // Nothing, at first
</code>```

When setting the value, the state doesn't update:

```<code>    const handleSetValues = values => {
        const _fieldValues = {
            ...fieldValues,
            ...values
        }

        setFieldValues(_fieldValues)

        console.log(fieldValues) // these won't be updated

        setTimeout(() => {
            console.log(fieldValues) // after ten seconds, it's still not updated
        },10000)
    }
</code>```

If I call the function a second time, it'll have updated, but that's not gonna work for me.
I never saw behaviour like this in class components.

Is it meant to... like, not update? Or just update whenever it feels like it? Really confusing behaviour.

答:
setFieldValues(_fieldValues) is an async call, means you won't able to get the result in the very next line of this.

You can use useEffect hook.

```<code>useEffect(() => {
    // do your work here
  }, [fieldValues]);
</code>```

It seems from your question that you have background of Class components of React, so useEffect is similar to componentDidMount and componentDidUpdate lifecycle methods.

useEffect calls whenever the state in the dependency array (in your case [fieldValues]) changes and you get the updated value in useEffect body.

You can also perform componentWillUnmount work in useEffect as well.

Have a brief guide.

Body:
So, I'm using hooks to manage the state of a set of forms, set up like so:

    const [fieldValues, setFieldValues] = useState({}) // Nothing, at first

When setting the value, the state doesn't update:

    const handleSetValues = values => {
        const _fieldValues = {
            ...fieldValues,
            ...values
        }

        setFieldValues(_fieldValues)

        console.log(fieldValues) // these won't be updated

        setTimeout(() => {
            console.log(fieldValues) // after ten seconds, it's still not updated
        },10000)
    }

If I call the function a second time, it'll have updated, but that's not gonna work for me.
I never saw behaviour like this in class components.

Is it meant to... like, not update? Or just update whenever it feels like it? Really confusing behaviour.

Body:
setFieldValues(_fieldValues) is an async call, means you won't able to get the result in the very next line of this.

You can use useEffect hook.

useEffect(() => {
    // do your work here
  }, [fieldValues]);

It seems from your question that you have background of Class components of React, so useEffect is similar to componentDidMount and componentDidUpdate lifecycle methods.

useEffect calls whenever the state in the dependency array (in your case [fieldValues]) changes and you get the updated value in useEffect body.

You can also perform componentWillUnmount work in useEffect as well.

Have a brief guide.


问:
How do you represent this character in python? 
The empty box character shows up in a text, in place of a non-ascii character, so I need to replace that character in python, but I get an error:

SyntaxError: Non-ASCII character '\xef' in file pyautoGuiTiReg/main.py on line 197, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details.

I am not sure what encoding to use as this is a very weird symbol:

答: As @AnshumanTiwari mentioned in the comments, utf-8 is the way to go when in doubt. By adding # -*- coding: utf-8 -*- to the top of the code, it ends up working perfectly.


问:
extjs checkbox grid delete rails
i am using ExtJS with Rails...I am trying to delete records selected in grid through "Checkbox column"...i dnt have any idea as to how can i handle "Array" of selected records of grid through rails controller...plzz guide me...
the code on delete button is as follows :

```<code>var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();
    Ext.Ajax.request({
        url: 'products/delete',
        //   method:'DELETE',
        params: {
            'prodid': sel
        }

    });

});
</code>```

How can i iterate through "sel" array in my Rails controller?? plzz help

答:
use Ext.each to iterate an array :

```<code>var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();

    Ext.each(sel,function(data){

        /// your stuff
        Ext.Ajax.request({
           url: 'products/delete',
           //   method:'DELETE',
           params: {
               'prodid': data.id // the parameter
           }
        });
        ///// end

    },this);
});
</code>```

Title: extjs checkbox grid delete rails

Body:
i am using ExtJS with Rails...I am trying to delete records selected in grid through "Checkbox column"...i dnt have any idea as to how can i handle "Array" of selected records of grid through rails controller...plzz guide me...
the code on delete button is as follows :

var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();
    Ext.Ajax.request({
        url: 'products/delete',
        //   method:'DELETE',
        params: {
            'prodid': sel
        }

    });

});

How can i iterate through "sel" array in my Rails controller?? plzz help

Body:
use Ext.each to iterate an array :

var sm = prodgrid.getSelectionModel();
delbtn.on("click", function () {
    var sel = sm.getSelections();

    Ext.each(sel,function(data){

        /// your stuff
        Ext.Ajax.request({
           url: 'products/delete',
           //   method:'DELETE',
           params: {
               'prodid': data.id // the parameter
           }
        });
        ///// end

    },this);
});


问:
For loop to drop columns based on null values
Hello I have a data frame called lc. And in the shape of the data frame is (235607,146)
I was able to write a code that shows me the percentage of null values in each column(np.sum(lc.isnull())/lc.shape[0]*100). And now I need help in writing a for loop that drops all the columns with null values greater than 70 percent

答:
You can use boolean indexing. Taken mean to check the percent of null values in each column. As false will be returned in case of columns that don't meet the criteria, they will not be shotlisted.

```<code>import numpy as np
df.loc[:,df.isin([0,' ',np.nan,None]).mean()<0.7]
</code>```

Body:
You can use boolean indexing. Taken mean to check the percent of null values in each column. As false will be returned in case of columns that don't meet the criteria, they will not be shotlisted.

import numpy as np
df.loc[:,df.isin([0,' ',np.nan,None]).mean()<0.7]


问:
How to replace a pure component with shouldComponentUpdate in react
I have the following react component.

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

import Backdrop from 'components/ui/backdrop/backdrop.component';

class BaseModal extends Component {
  shouldComponentUpdate(nextProps: INextProps) {
    return nextProps.show !== this.props.show || nextProps.children !== this.props.children;
  }

  render() {
    const { show, modalClosed } = this.props;

    return (
      <div>
        <Backdrop show={show} onClick={modalClosed} />

        <div
          className='modalClass'
          style={{
            transform: show ? 'translateY(0)' : 'translateY(-100vh)',
            opacity: this.props.show ? '1' : '0',
          }}>
          >{this.props.children}
        </div>
      </div>
    );
  }
}

interface IProps {
  show: boolean;
  modalClosed: boolean;
  children: any;
}

interface INextProps {
  show: boolean;
  children: any;
}

export default BaseModal;
</code>```

I would like to use a pure component here. Does that mean that I can remove the shouldComponentUpdate life cycle method from this component? If so, how should I do it?

答:
You can safely remove the shouldComponentUpdate lifecycle method here. This lifecycle shouldn't usually be used if all you do is compare props by reference, you can safely replace it's functionality by using PureComponent (read more about when you should use either https://codeburst.io/when-to-use-component-or-purecomponent-a60cfad01a81)

You can also remove INextProps interface, as it isn't actually needed (you should use the same interface IProps in shouldComponentUpdate as well).

Here an improved version to your component, which uses PureComponent instead of Component.

```<code>import React from 'react';

import Backdrop from 'components/ui/backdrop/backdrop.component';

class BaseModal extends React.PureComponent {
  render() {
    const { show, modalClosed, children } = this.props;

    return (
      <div>
        <Backdrop show={show} onClick={modalClosed} />

        <div
          className='modalClass'
          style={{
            transform: show ? 'translateY(0)' : 'translateY(-100vh)',
            opacity: show ? '1' : '0',
          }}>
          >
          {children}
        </div>
      </div>
    );
  }
}

interface IProps {
  show: boolean;
  // by the way you are using it, it seems like modalClosed is a function not a bool
  modalClosed: () => void;
  children: any;
}

export default BaseModal;
</code>```

Body:
I have the following react component.

import React, { Component } from 'react';

import Backdrop from 'components/ui/backdrop/backdrop.component';

class BaseModal extends Component {
  shouldComponentUpdate(nextProps: INextProps) {
    return nextProps.show !== this.props.show || nextProps.children !== this.props.children;
  }

  render() {
    const { show, modalClosed } = this.props;

    return (

        <Backdrop show={show} onClick={modalClosed} />

          >{this.props.children}

    );
  }
}

interface IProps {
  show: boolean;
  modalClosed: boolean;
  children: any;
}

interface INextProps {
  show: boolean;
  children: any;
}

export default BaseModal;

I would like to use a pure component here. Does that mean that I can remove the shouldComponentUpdate life cycle method from this component? If so, how should I do it?

Body:
You can safely remove the shouldComponentUpdate lifecycle method here. This lifecycle shouldn't usually be used if all you do is compare props by reference, you can safely replace it's functionality by using PureComponent (read more about when you should use either https://codeburst.io/when-to-use-component-or-purecomponent-a60cfad01a81)

You can also remove INextProps interface, as it isn't actually needed (you should use the same interface IProps in shouldComponentUpdate as well).

Here an improved version to your component, which uses PureComponent instead of Component.

import React from 'react';

import Backdrop from 'components/ui/backdrop/backdrop.component';

class BaseModal extends React.PureComponent {
  render() {
    const { show, modalClosed, children } = this.props;

    return (
      <div>
        <Backdrop show={show} onClick={modalClosed} />

        <div
          className='modalClass'
          style={{
            transform: show ? 'translateY(0)' : 'translateY(-100vh)',
            opacity: show ? '1' : '0',
          }}>
          >
          {children}
        </div>
      </div>
    );
  }
}

interface IProps {
  show: boolean;
  // by the way you are using it, it seems like modalClosed is a function not a bool
  modalClosed: () => void;
  children: any;
}

export default BaseModal;


问:
IsDigit() in c reading char as digit in C
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not. </p>

<p>I can't seem to find out where the bug is in my code. </p>

```<code>#include<stdio.h>
#include <stdbool.h>

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.
</code>```

答:
You can modify your isdigit() check.
Even though isdigit() takes an integer as an argument, the character is passed to the function. Internally, the character is converted to its ASCII value for the check.

logic: for non-numeric argument isdigit() will return 0 and for numeric argument will return non-zero unsigned integer

Modification:

```<code>if (isdigit( ch ) == 0)
     return False;
 else
    return True;
</code>```

Body:
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not.

I can't seem to find out where the bug is in my code.

#include<stdio.h>
#include <stdbool.h>

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.

Body:
You can modify your isdigit() check.
Even though isdigit() takes an integer as an argument, the character is passed to the function. Internally, the character is converted to its ASCII value for the check.

logic: for non-numeric argument isdigit() will return 0 and for numeric argument will return non-zero unsigned integer

Modification:

if (isdigit( ch ) == 0)
     return False;
 else
    return True;


问:
NoClassDefFoundError: org/apache/http/HttpEntity in Selenium for FirefoxDriver
I am not trying to do much here.

I am just trying to run an example given in Selenium website, to just open Google page and enter a search string in the edit box

But I get the following error:

*> Exception in thread "main"

java.lang.NoClassDefFoundError:
  org/apache/http/client/ClientProtocolException
    at
  org.openqa.selenium.ie.InternetExplorerDriver.setup(InternetExplorerDriver.java:92)
    at
  org.openqa.selenium.ie.InternetExplorerDriver.(InternetExplorerDriver.java:56)
    at
  com.testscripts.Selenium2Example.main(Selenium2Example.java:16)*

I have no idea what this ClientProtocolException
 Class is and where to find this.

Could any one of you please help ?

Code Is

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.ie.*;

public class Selenium2Example  {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        System.setProperty("webdriver.firefox.bin", "C:\\Documents and Settings\\Vikas Kashyap\\Local Settings\\Application Data\\Mozilla Firefox\\firefox");

        WebDriver driver = new FirefoxDriver();

        //WebDriver driver = new InternetExplorerDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();

    }
}
</code>```

Regards,

Vikas

答:
Thanks for the reply.

I found out the mistake that I had done.

I am using Eclipse as my IDE.
In the list of externally referenced JAR files, I had included "selenium-java-2.0b3.jar"

Actually I had to include "selenium-server-standalone-2.0b3.jar"

Selenium website doesnt really say which jar file to download for the server! This created all the confusion.

Using the right jar file, there's no more "NoClassDefFoundError" .

Regards
Vikas

Body:
I am not trying to do much here.

I am just trying to run an example given in Selenium website, to just open Google page and enter a search string in the edit box

But I get the following error:

*> Exception in thread "main"

java.lang.NoClassDefFoundError:
  org/apache/http/client/ClientProtocolException
    at
  org.openqa.selenium.ie.InternetExplorerDriver.setup(InternetExplorerDriver.java:92)
    at
  org.openqa.selenium.ie.InternetExplorerDriver.(InternetExplorerDriver.java:56)
    at
  com.testscripts.Selenium2Example.main(Selenium2Example.java:16)*

I have no idea what this ClientProtocolException
 Class is and where to find this.

Could any one of you please help ?

Code Is

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.ie.*;

public class Selenium2Example  {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        System.setProperty("webdriver.firefox.bin", "C:\\Documents and Settings\\Vikas Kashyap\\Local Settings\\Application Data\\Mozilla Firefox\\firefox");

        WebDriver driver = new FirefoxDriver();

        //WebDriver driver = new InternetExplorerDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        //Close the browser
        driver.quit();

    }
}

Regards,

Vikas


问:
how to load data from AWS RDS to Google BigQuery in streaming mode?
how to load data from AWS RDS to Google BigQuery in streaming mode?
Description: I have data in RDS (SQL Server), and wanted to load this data into Google BigQuery in real-time.</p>

答:
There is no direct way to insert changes from Amazon RDS to Google Cloud BigQuery. It could be done with a pipeline like this

Amazon RDS ----Lambda/DMS----> Kinesis Data Streams -----Lambda----> BigQuery

Read changes from Amazon RDS to Kinesis Data Streams using Lambda or use Cloud DMS. You can also push it to Kinesis Firehose for aggregating/batching records.

Use Lambda to read from Kinesis streams/Firehose to insert into BigQuery using tabledata.insertAll (BQ streaming API). Code will be something similar to this.


问:
Import txt file in graph-tool
I have a directed, weighted network stored in a txt file as a list of 3 elements:

```<code>node1 node2 weight
node1 node3 weight
...
</code>```

So for example the triplet:

```<code>1 10 50
</code>```

means that I got an edge between node 1 and node 10 with weight 50.

Can someone please explain in detail how can I import this  into graph tool to perform a community detection analysis using the SBM.

Thanks a lot.

答:
```<code>graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'})
</code>```

This will help you load a csv file with delimiter=space. I am still trying to read the documentation as to how to associate a weight to the edges: https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load

Title: Import txt file in graph-tool

Body:
I have a directed, weighted network stored in a txt file as a list of 3 elements:

node1 node2 weight
node1 node3 weight
...

So for example the triplet:

1 10 50

means that I got an edge between node 1 and node 10 with weight 50.

Can someone please explain in detail how can I import this  into graph tool to perform a community detection analysis using the SBM.

Thanks a lot.

Body:
graph_tool.load_graph_from_csv(file_name, csv_options={'delimiter': ' ', 'quotechar': '"'})

This will help you load a csv file with delimiter=space. I am still trying to read the documentation as to how to associate a weight to the edges: https://graph-tool.skewed.de/static/doc/graph_tool.html?highlight=load#graph_tool.Graph.load


答:
setFieldValues is an asynchronous function, so logging the value below the statement will not have any effect.

Regarding using setTimeout, the function would capture the current value of props being passed to it and hence that would be the value printed to the console. This is true to any JS function, see the snippet below:

function init(val) {
  setTimeout(() => {
      console.log(val);
  }, 1000);
}

let counterVal = 1;

init(counterVal);
counterVal++;```
</div>
</div>
</p>

<p>So how can we print the values when the value changes? The easy mechanism is to use a <code>useEffect</code>:</p>

```useEffect(() => {
  console.log(fieldValues)
}, [fieldValues]);
```

Title: React hooks update sort of whenever they feel like it

Body:
setFieldValues is an asynchronous function, so logging the value below the statement will not have any effect.

Regarding using setTimeout, the function would capture the current value of props being passed to it and hence that would be the value printed to the console. This is true to any JS function, see the snippet below:

function init(val) {
  setTimeout(() => {
      console.log(val);
  }, 1000);
}

let counterVal = 1;

init(counterVal);
counterVal++;

So how can we print the values when the value changes? The easy mechanism is to use a useEffect:

useEffect(() => {
  console.log(fieldValues)
}, [fieldValues]);