问:
Skip a page when the back button is pressed, WP7
In the current released version of WP7 you have no programmatic control over the page stack.

I start at A, go to B, and then C.  B is the data entry page for new items, so coming back from C I want to logically land at A.  Currently I listen for navigation on B that comes from C and force another back onto A.  However, the event doesn't happen soon enough to stop the page from displaying on-screen.

A -> B -> C

C -> A

A is the top level list page.  B is the new item page.  C is the item detail page.

This only occurs on one form so far so my workaround is to override OnNavigatedTo in the page I want to skip, and call "go back" programmatically.  However, this has the undesired effect of briefly showing the page and then immediately navigating off of it.

Is there a workable way to stop the flicker?

Should my workaround instead be to take full control of page navigation, including go backs?  This will leave the page stack is a strange state, but that would be hidden from the user if I control all navigation.

I know there is a new feature in Mango to pop a page from the page stack programmatically, but I'm curious to know if there is a solution to the problem in the released version.

Another motivation for this is I don't know what version will be best to target, the latest, or the one that is just enough for the app.  For the time being I'm sticking with the live version.

答:
There is no way to do it before Mango, except with the flickering way you already know.

In Mango, you can use NavigationService.RemoveBackEntry.

And it's more a question of a bad application design, than anything else. You shouldn't require a immediate page for anything.

Your workaround should be to design a application structure that doesn't require any immediate  pages.


来源: stackexchange

问:
C# and Rx: testing a timeout
I've implemented an observer for a FileSystemWatcher. The idea is to track copies in a folder and wait until copy is finished. Once done, let's do something with copied files.
I've tried my implementation on a small program and it works. What I wanted to do is to make it more formal using unit test:

```<code>[TestMethod]
    public void TestIsFileWritingFinished()
    {
        try
        {
            var dirName = Path.GetTempPath()+Path.DirectorySeparatorChar+DateTime.Now.ToString("MMddyyyy");
            if (Directory.Exists(dirName))
            {
                Directory.Delete(dirName, true);
            }
            var dir = Directory.CreateDirectory(dirName);

            var observer = new FileSystemObserver(dirName, "*.*", true)
                        .ChangedFiles
                        .Where(x => (new FileInfo(x.FullPath)).Length > 0)
                        .Select(x => x.Name);
            var timeout = observer.Timeout(/*DateTimeOffset.UtcNow.AddSeconds(1)*/TimeSpan.FromSeconds(1));
            var filesChanged = new List<string>();
            var terminated = false;
            timeout.Subscribe(Console.WriteLine, Console.WriteLine, ()=>terminated=true);

            Thread.Sleep(100);
            var origin = @"C:\Users\David\ResultA";
            CopyDirectory(origin, dirName, true);
            Thread.Sleep(100);
            Console.WriteLine("nap for 5s");
            Thread.Sleep(5000);

            //Directory.Delete(dirName, true);
            Assert.IsTrue(terminated);
        }
        catch(Exception ex)
        {
            Assert.Fail(ex.Message);
        }
    }
</code>```

So, when timeout happens, I expect the boolean to be true. But looks like it's not.
Any idea about what's wrong with my test?
Thanks in advance, your suggestions will be appreciated,

Kind regards,

答:
Even thought there is a Timeout operator, I find it is a bit of an anti-pattern. It's like programming with exceptions. I find the following pattern more useful:

```<code>IObservable<bool> query =
    Observable.Amb(
        source.LastAsync().Select(x => true),
        Observable.Timer(TimeSpan.FromSeconds(seconds)).Select(x => false));
</code>```

This is effectively running source to completion and then returns true, but if the Timer completes first it returns false.

So, in your code, I'd try something like this:

```<code>var dirName = Path.GetTempPath() + Path.DirectorySeparatorChar + DateTime.Now.ToString("MMddyyyy");
if (Directory.Exists(dirName))
{
    Directory.Delete(dirName, true);
}
var dir = Directory.CreateDirectory(dirName);

var observer =
    new FileSystemObserver(dirName, "*.*", true)
        .ChangedFiles
        .Where(x => (new FileInfo(x.FullPath)).Length > 0)
        .Select(x => x.Name);

var result =
    Observable.Amb(
        observer.ToArray().Select(x => true),
        Observable.Timer(TimeSpan.FromSeconds(1.0)).Select(x => false));

var query =
    result.Zip(Observable.Start(() =>
    {
        var origin = @"C:\Users\David\ResultA";
        CopyDirectory(origin, dirName, true);
    }), (r, s) => r);

var terminated = query.Wait();

Assert.IsTrue(terminated);
</code>```

That totally avoids any pesky sleeps.

ContentLicense: CC BY-SA 4.0

Title: C# and Rx: testing a timeout

Body:
I've implemented an observer for a FileSystemWatcher. The idea is to track copies in a folder and wait until copy is finished. Once done, let's do something with copied files.
I've tried my implementation on a small program and it works. What I wanted to do is to make it more formal using unit test:

[TestMethod]
    public void TestIsFileWritingFinished()
    {
        try
        {
            var dirName = Path.GetTempPath()+Path.DirectorySeparatorChar+DateTime.Now.ToString("MMddyyyy");
            if (Directory.Exists(dirName))
            {
                Directory.Delete(dirName, true);
            }
            var dir = Directory.CreateDirectory(dirName);

            var observer = new FileSystemObserver(dirName, "*.*", true)
                        .ChangedFiles
                        .Where(x => (new FileInfo(x.FullPath)).Length > 0)
                        .Select(x => x.Name);
            var timeout = observer.Timeout(/*DateTimeOffset.UtcNow.AddSeconds(1)*/TimeSpan.FromSeconds(1));
            var filesChanged = new List<string>();
            var terminated = false;
            timeout.Subscribe(Console.WriteLine, Console.WriteLine, ()=>terminated=true);

            Thread.Sleep(100);
            var origin = @"C:\Users\David\ResultA";
            CopyDirectory(origin, dirName, true);
            Thread.Sleep(100);
            Console.WriteLine("nap for 5s");
            Thread.Sleep(5000);

            //Directory.Delete(dirName, true);
            Assert.IsTrue(terminated);
        }
        catch(Exception ex)
        {
            Assert.Fail(ex.Message);
        }
    }

So, when timeout happens, I expect the boolean to be true. But looks like it's not.
Any idea about what's wrong with my test?
Thanks in advance, your suggestions will be appreciated,

Kind regards,

Body:
Even thought there is a Timeout operator, I find it is a bit of an anti-pattern. It's like programming with exceptions. I find the following pattern more useful:

IObservable<bool> query =
    Observable.Amb(
        source.LastAsync().Select(x => true),
        Observable.Timer(TimeSpan.FromSeconds(seconds)).Select(x => false));

This is effectively running source to completion and then returns true, but if the Timer completes first it returns false.

So, in your code, I'd try something like this:

var dirName = Path.GetTempPath() + Path.DirectorySeparatorChar + DateTime.Now.ToString("MMddyyyy");
if (Directory.Exists(dirName))
{
    Directory.Delete(dirName, true);
}
var dir = Directory.CreateDirectory(dirName);

var observer =
    new FileSystemObserver(dirName, "*.*", true)
        .ChangedFiles
        .Where(x => (new FileInfo(x.FullPath)).Length > 0)
        .Select(x => x.Name);

var result =
    Observable.Amb(
        observer.ToArray().Select(x => true),
        Observable.Timer(TimeSpan.FromSeconds(1.0)).Select(x => false));

var query =
    result.Zip(Observable.Start(() =>
    {
        var origin = @"C:\Users\David\ResultA";
        CopyDirectory(origin, dirName, true);
    }), (r, s) => r);

var terminated = query.Wait();

Assert.IsTrue(terminated);

That totally avoids any pesky sleeps.


问:
openxlsx in r: openxlsx_getOp and op.openxlsx$ returning different values for same option
Using openxlsx package in R. When I run this:

```<code>> openxlsx_getOp("dateFormat")
</code>```

I get the expected value of [1] "yyyy-mm-dd". However, this code:

```<code>> op.openxlsx$openxlsx.dateFormat
</code>```

returns [1] "mm/dd/yyyy".

Why are these different?

EDIT:
Sorry. I called options("openxlsx.dateFormat" = "yyyy-mm-dd") at the top of my source file. Looks like this is important to specify.

答:
From ?op.openxlsx:

‘openxlsx_getOp()’ retrieves the ‘"openxlsx"’ options found in
‘op.openxlsx’.  If none are set (currently ‘NULL’) retrieves the
default option from ‘op.openxlsx’.  This will also check that the
intended option is a standard option (listed in ‘op.openxlsx’) and
will provide a warning otherwise.

So I suspect it's set to "yyyy-mm-dd" in your environment, hence the discrepancy.
To double check, you can try running R --vanilla on your machine (or the equivalent under Windows) and see if it has reverted back to the default mm/dd/yyyy

Body:
Using openxlsx package in R. When I run this:

> openxlsx_getOp("dateFormat")

I get the expected value of [1] "yyyy-mm-dd". However, this code:

> op.openxlsx$openxlsx.dateFormat

returns [1] "mm/dd/yyyy".

Why are these different?

EDIT:
Sorry. I called options("openxlsx.dateFormat" = "yyyy-mm-dd") at the top of my source file. Looks like this is important to specify.


问:
Flutter run stuck on white screen
I have a Flutter issue I can't resolve. I tried all common things like flutter clean, restarting pc, wiping emulator data and few more things still getting stuck on white screen basically.

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Connecting to VM Service at ws://127.0.0.1:55863/xq7cW6jF1O8=/ws    // this statement stays as its is
</code>```
```<code>void main() => MaterialApp(
      color: Colors.black,
      home: Scaffold(
        backgroundColor: Colors.black,
      ),
    );
</code>```

Basically connection to VM is not happening.

Edit

My dartDeveloperTool says unable to connect to vm service, but it opens in chrome and doesn't show any widget just clean dartDebugger tool.

Call to OpenGL ES API with no current context (logged once per thread).

答:
Don't underestimate the importance of runApp() - If you don't use it - your app (which is one big widget) will result in an indefinite white screen because it has no constraints...

According to the documentation it:

/// Inflate the given widget and attach it to the screen. The widget is given constraints during layout that force it to fill the entire screen.

Title: Flutter run stuck on white screen

Body:
I have a Flutter issue I can't resolve. I tried all common things like flutter clean, restarting pc, wiping emulator data and few more things still getting stuck on white screen basically.

Launching lib\main.dart on Android SDK built for x86 in debug mode...
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Connecting to VM Service at ws://127.0.0.1:55863/xq7cW6jF1O8=/ws    // this statement stays as its is

void main() => MaterialApp(
      color: Colors.black,
      home: Scaffold(
        backgroundColor: Colors.black,
      ),
    );

Basically connection to VM is not happening.

Edit

My dartDeveloperTool says unable to connect to vm service, but it opens in chrome and doesn't show any widget just clean dartDebugger tool.

Call to OpenGL ES API with no current context (logged once per thread).


问:
Error: Unrecognized font family Material Design icons after installing react-native-elements?
I am a Newbie in react-native. I created a new project using react-native-cli.
I am Using react-native-elements As A UI component library for React Native. So I ran following commands

```<code>**npm i react-native-elements --save**
</code>```

After this i ran my simulator command,

react-native run-ios

not sure how to resolve this error.

答:
Solved it for me:

Shutdown simulator

Add to ios/{AppName}/info.plist

```<code>  <key>UIAppFonts</key> (Should already be there)
  <array>
    <string>MaterialIcons.ttf</string>
  </array>
</code>```

Run

```<code>  cd ios
  pod install
  cd ..
  watchman watch-del-all
</code>```

Restart simulator

NOTE: I assume you can do this for every font family you are missing.

ContentLicense: CC BY-SA 3.0

Body:
I am a Newbie in react-native. I created a new project using react-native-cli.
I am Using react-native-elements As A UI component library for React Native. So I ran following commands

**npm i react-native-elements --save**

After this i ran my simulator command,

react-native run-ios

not sure how to resolve this error.

Body:
Solved it for me:

Shutdown simulator

Add to ios/{AppName}/info.plist

  <key>UIAppFonts</key> (Should already be there)
  <array>
    <string>MaterialIcons.ttf</string>
  </array>

Run

  cd ios
  pod install
  cd ..
  watchman watch-del-all

Restart simulator

NOTE: I assume you can do this for every font family you are missing.


问:
Macro definition conflict
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

```<code>test1.h
#define TEST 123
test2.h
#define TEST 456
</code>```

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

答:
You can undefine it if you include both headers to your file as:</p>

```<code>//yourfile.cpp

#include "test2.h"  //include this before test1.h

#undef TEST   //this undefines the macro defined in test2.h

#include "test1.h"  //now this defines a macro called TEST which you need
</code>```

Title: Macro definition conflict

Body:
I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.

I have two header files

test1.h
#define TEST 123
test2.h
#define TEST 456

Now I have a program included  both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?

You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.

So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.

Body:
You can undefine it if you include both headers to your file as:

//yourfile.cpp

#include "test2.h"  //include this before test1.h

#undef TEST   //this undefines the macro defined in test2.h

#include "test1.h"  //now this defines a macro called TEST which you need


问:
Tangent by scratch
I'm completely new to Erlang and i'm using the Ubuntu command line to run the program and gedit to edit/write the code.

I'm trying to code tangent my scratch rather than using the built in math class.

I get the following errors and unsure what needs to be changed.

ERROR

```<code>** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-0.07926409746793839)
        *** argument 1: is outside the domain for this function
     in call from extra:double/1 (extra.erl, line 11)
</code>```

CODE

```<code>-module(extra).

-export([double/1]).

-import(io,[fwrite/1]).

% I am a comment.

double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * 2)),
    Tan = Num / Dem,
    io:fwrite("~w",[Tan]).
</code>```

答:
I think you should be doing a Num * Num instead of Num * 2 when calculating the sqrt for Dem.

```<code>double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * Num)),
    Tan = Num / Dem,
    io:fwrite("~w~n",[Tan]).
</code>```

As the error clearly says...

*** argument 1: is outside the domain for this function

While doing math:sqrt(1 - (Num * 2)), clearly the Num * 2 is becoming more than 1 causing a negative argument to be fed into math:sqrt, and hence the breakage.

Illustration: sqrt with negative argument

> math:sqrt(-1).
math:sqrt(-1).
** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-1)
        *** argument 1: is outside the domain for this function
```

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Title: Tangent by scratch

Body:
I'm completely new to Erlang and i'm using the Ubuntu command line to run the program and gedit to edit/write the code.

I'm trying to code tangent my scratch rather than using the built in math class.

I get the following errors and unsure what needs to be changed.

ERROR

** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-0.07926409746793839)
        *** argument 1: is outside the domain for this function
     in call from extra:double/1 (extra.erl, line 11)

CODE

-module(extra).

-export([double/1]).

-import(io,[fwrite/1]).

% I am a comment.

double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * 2)),
    Tan = Num / Dem,
    io:fwrite("~w",[Tan]).

Body:
I think you should be doing a Num * Num instead of Num * 2 when calculating the sqrt for Dem.

double(N) ->
    Num = math:sin(N),
    Dem = math:sqrt(1 - (Num * Num)),
    Tan = Num / Dem,
    io:fwrite("~w~n",[Tan]).

As the error clearly says...

*** argument 1: is outside the domain for this function

While doing math:sqrt(1 - (Num * 2)), clearly the Num * 2 is becoming more than 1 causing a negative argument to be fed into math:sqrt, and hence the breakage.

Illustration: sqrt with negative argument

> math:sqrt(-1).
math:sqrt(-1).
** exception error: an error occurred when evaluating an arithmetic expression
     in function  math:sqrt/1
        called as math:sqrt(-1)
        *** argument 1: is outside the domain for this function

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


问:
Print() for breaking line in python
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()
```

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

答:
See this ref

If no objects are given, print() will just write end.

```<code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
// From above print function signature we know end is just '\n'.
</code>```

Title: Print() for breaking line in python

Body:
I had to write a program to print the below pattern.

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Now , the code which is given is as :

num = int(input())

for i in range (1,num+1):
     for j in range (1 , i +1):
          print(j, end = " ")
     print()

But I don't understand that how a new line will be started after each loop without using \n  . My teacher told that the print() in the last is used to break line . But I don't understand that what is going on .

Body:
See this ref

If no objects are given, print() will just write end.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
// From above print function signature we know end is just '\n'.


问:
Converting NSData into NSDictionary
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.

My code is as follows:

```<code>NSURL *url = [NSURL URLWithString:@"http://www.fubar.com/sample.xml"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSLog(@"%@", data);
</code>```

To convert the data, I am using:

```<code>- (NSDictionary *)downloadPlist:(NSString *)url {
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];

    if (!err) {
        NSString *errorDescription = nil;
        NSPropertyListFormat format;
        NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];

        if (!errorDescription)
            return samplePlist;

        [errorDescription release];
    }

    return nil;
}
</code>```

Can anyone please tell me how to do that?

答:
Try this code:

```<code>NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"Login" ofType:@"plist"];
[dictionary writeToFile:path  atomically:YES];
//here Login is the plist name.
</code>```

Happy coding

Title: Converting NSData into NSDictionary

Body:
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.

My code is as follows:

NSURL *url = [NSURL URLWithString:@"http://www.fubar.com/sample.xml"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSLog(@"%@", data);

To convert the data, I am using:

- (NSDictionary *)downloadPlist:(NSString *)url {
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];

    if (!err) {
        NSString *errorDescription = nil;
        NSPropertyListFormat format;
        NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];

        if (!errorDescription)
            return samplePlist;

        [errorDescription release];
    }

    return nil;
}

Can anyone please tell me how to do that?

Body:
Try this code:

NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"Login" ofType:@"plist"];
[dictionary writeToFile:path  atomically:YES];
//here Login is the plist name.

Happy coding


问:
SwiftUI Matched Geometry Effect not working with multiple ForEach's
I am basically trying to recreate the photos app. In doing so, matched geometry effect should be the best way to recreate the animation that is used in the photos app when you click on an image/close it. However, on opening of an image it only does half of the animation. When closing the image the animation is only contained to the lazyvgrid individual image not the whole view. Also the first image of the gallery simply does not animate when closing.

Gallery view is made from a lazyvgrid and for each, full screen view is made of a tabview and for each.

Here is what it looks like:

Main view:

```<code>struct ImageSelectorView: View {
    @EnvironmentObject var isvm: ImageSelectorViewModel
    @Namespace var namespace
    @State private var selectedImages: [SelectedImagesModel] = []
    @State private var selectedImageID: String = ""
    @State private var liveEventID: String = ""
    @State var showImageFSV: Bool = false
    @State var showPicker: Bool = false
    @Binding var liveEvent: [EventModel]
    public var pickerConfig: PHPickerConfiguration {
        var config = PHPickerConfiguration(photoLibrary: .shared())
        config.filter = .any(of: [.images, .livePhotos, .videos])
        config.selectionLimit = 10
        return config
    }
    private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    private let viewHPadding: CGFloat = 30

    init(liveEvent: Binding<[EventModel]>) {
        self._liveEvent = liveEvent
    }

    var body: some View {
        ZStack {
            Color.theme.background.ignoresSafeArea()
            VStack {
                ZStack {
                    ScrollView(.vertical, showsIndicators: true) {
                        LazyVGrid(columns: self.gridItemLayout, alignment: .center, spacing: 0.5) {
                            ForEach(self.liveEvent[0].eventImages.indices) { image in
                                GalleryImage(selectedImageID: self.$selectedImageID, showImageFSV: self.$showImageFSV, image: self.liveEvent[0].eventImages[image], namespace: self.namespace)
                            }
                        }
                    }

                    if self.showImageFSV {
                        KFImagesFSV(eventImages: self.$liveEvent[0].eventImages, showImageFSV: self.$showImageFSV, selectedImageID: self.$selectedImageID, namespace: self.namespace)
                    }
                }
            }
        }
    }
}
</code>```

Gallery Image View:

```<code>struct GalleryImage: View {
    @Binding var selectedImageID: String
    @Binding var showImageFSV: Bool
    public var image: EventImage
    public var namespace: Namespace.ID
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    var body: some View {
        Button {
            DispatchQueue.main.async {
                withAnimation(.spring()) {
                    self.selectedImageID = image.id
                    if self.selectedImageID == image.id {
                        self.showImageFSV.toggle()
                    }
                }
            }
        } label: {
            KFImage(URL(string: image.url))
                .placeholder({
                    Image("topo")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                })
                .loadDiskFileSynchronously()
                .cacheMemoryOnly()
                .fade(duration: 0.2)
                .resizable()
                .matchedGeometryEffect(id: self.selectedImageID == image.id ? "" : image.id, in: self.namespace)
                .aspectRatio(contentMode: .fill)
                .frame(width: (self.viewWidth/2.9) - 3, height: (self.viewWidth/2.9) - 3)
                .clipped()
        }
    }
}
</code>```

Image full screen view (tab view):

```<code>struct KFImagesFSV: View {
    @Binding var eventImages: [EventImage]
    @Binding var showImageFSV: Bool
    @Binding var selectedImageID: String
    public var namespace: Namespace.ID
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    private let viewHPadding: CGFloat = 30
    var body: some View {
        ZStack {
            TabView(selection: self.$selectedImageID) {
                ForEach(self.eventImages.indices) { image in
                    KFImage(URL(string: self.eventImages[image].url))
                        .placeholder({
                            Image("topo")
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        })
                        .loadDiskFileSynchronously()
                        .cacheMemoryOnly()
                        .fade(duration: 0.2)
                        .resizable()
                        .tag(self.eventImages[image].id)
                        .matchedGeometryEffect(id: self.selectedImageID == self.eventImages[image].id ? self.eventImages[image].id : "", in: self.namespace)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: self.viewWidth, height: self.viewHeight)
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
        }
    }
}
</code>```

答:
This is how far I got. The zoom out from FullScreenView to GalleryView works. the only thing that doesn't, is a clean zoom in into the TabView. I suppose this is because of the wrapping by TabView.

```<code>struct ImageStruct: Identifiable {
    let id = UUID()
    var image: String = ""
}

let imagesArray = [
    ImageStruct(image: "image1"),
    ImageStruct(image: "image2"),
    ImageStruct(image: "image3"),
    ImageStruct(image: "image4"),
    ImageStruct(image: "image5"),
    ImageStruct(image: "image6"),
    ImageStruct(image: "image7"),
    ImageStruct(image: "image8")
]

struct ContentView: View {

    @Namespace var ns
    @State private var selectedImage: UUID?

    var body: some View {
//        ZStack {
            if selectedImage == nil {
                GalleryView(selectedImage: $selectedImage, ns: ns)
            } else {
                FullScreenView(selectedImage: $selectedImage, ns: ns)
            }
//        }
    }
}

struct GalleryView: View {

    @Binding var selectedImage: UUID?
    var ns: Namespace.ID

    private let columns = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]

    var body: some View {
        VStack {
            ScrollView(.vertical, showsIndicators: true) {

                LazyVGrid(columns: columns) {

                    ForEach(imagesArray) { image in

                        Color.clear.overlay(
                            Image(image.image)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .matchedGeometryEffect(id: image.id, in: ns, isSource: true)
                        )
                            .clipped()
                            .aspectRatio(1, contentMode: .fit)

                            .onTapGesture {
                                withAnimation {
                                    selectedImage = image.id
                                }
                            }
                    }
                }
            }
        }
    }
}

struct FullScreenView: View {

    @Binding var selectedImage: UUID?
    var ns: Namespace.ID

    init(selectedImage: Binding<UUID?>, ns: Namespace.ID) {
        print(selectedImage)
        self._selectedImage = selectedImage
        self.ns = ns
        // initialize selctedTab to selectedImage
        self._selectedTab = State(initialValue: selectedImage.wrappedValue ?? UUID())
    }

    @State private var selectedTab: UUID

    var body: some View {

        TabView(selection: $selectedTab) {

            ForEach(imagesArray) { image in

                Image(image.image)
                    .resizable()
                    .scaledToFit()
                    // ternary applying effect only for selected tab
                    .matchedGeometryEffect(id: image.id == selectedTab ? selectedTab : UUID(),
                                           in: ns, isSource: true)

                    .tag(image.id)

                    .onTapGesture {
                        withAnimation {
                            selectedImage = nil
                        }
                    }
            }
        }
        .tabViewStyle(.page)
    }
}
</code>```

Body:
I am basically trying to recreate the photos app. In doing so, matched geometry effect should be the best way to recreate the animation that is used in the photos app when you click on an image/close it. However, on opening of an image it only does half of the animation. When closing the image the animation is only contained to the lazyvgrid individual image not the whole view. Also the first image of the gallery simply does not animate when closing.

Gallery view is made from a lazyvgrid and for each, full screen view is made of a tabview and for each.

Here is what it looks like:

Main view:

struct ImageSelectorView: View {
    @EnvironmentObject var isvm: ImageSelectorViewModel
    @Namespace var namespace
    @State private var selectedImages: [SelectedImagesModel] = []
    @State private var selectedImageID: String = ""
    @State private var liveEventID: String = ""
    @State var showImageFSV: Bool = false
    @State var showPicker: Bool = false
    @Binding var liveEvent: [EventModel]
    public var pickerConfig: PHPickerConfiguration {
        var config = PHPickerConfiguration(photoLibrary: .shared())
        config.filter = .any(of: [.images, .livePhotos, .videos])
        config.selectionLimit = 10
        return config
    }
    private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    private let viewHPadding: CGFloat = 30

    init(liveEvent: Binding<[EventModel]>) {
        self._liveEvent = liveEvent
    }

    var body: some View {
        ZStack {
            Color.theme.background.ignoresSafeArea()
            VStack {
                ZStack {
                    ScrollView(.vertical, showsIndicators: true) {
                        LazyVGrid(columns: self.gridItemLayout, alignment: .center, spacing: 0.5) {
                            ForEach(self.liveEvent[0].eventImages.indices) { image in
                                GalleryImage(selectedImageID: self.$selectedImageID, showImageFSV: self.$showImageFSV, image: self.liveEvent[0].eventImages[image], namespace: self.namespace)
                            }
                        }
                    }

                    if self.showImageFSV {
                        KFImagesFSV(eventImages: self.$liveEvent[0].eventImages, showImageFSV: self.$showImageFSV, selectedImageID: self.$selectedImageID, namespace: self.namespace)
                    }
                }
            }
        }
    }
}

Gallery Image View:

struct GalleryImage: View {
    @Binding var selectedImageID: String
    @Binding var showImageFSV: Bool
    public var image: EventImage
    public var namespace: Namespace.ID
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    var body: some View {
        Button {
            DispatchQueue.main.async {
                withAnimation(.spring()) {
                    self.selectedImageID = image.id
                    if self.selectedImageID == image.id {
                        self.showImageFSV.toggle()
                    }
                }
            }
        } label: {
            KFImage(URL(string: image.url))
                .placeholder({
                    Image("topo")
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                })
                .loadDiskFileSynchronously()
                .cacheMemoryOnly()
                .fade(duration: 0.2)
                .resizable()
                .matchedGeometryEffect(id: self.selectedImageID == image.id ? "" : image.id, in: self.namespace)
                .aspectRatio(contentMode: .fill)
                .frame(width: (self.viewWidth/2.9) - 3, height: (self.viewWidth/2.9) - 3)
                .clipped()
        }
    }
}

Image full screen view (tab view):

struct KFImagesFSV: View {
    @Binding var eventImages: [EventImage]
    @Binding var showImageFSV: Bool
    @Binding var selectedImageID: String
    public var namespace: Namespace.ID
    private let viewWidth: CGFloat = UIScreen.main.bounds.width
    private let viewHeight: CGFloat = UIScreen.main.bounds.height
    private let viewHPadding: CGFloat = 30
    var body: some View {
        ZStack {
            TabView(selection: self.$selectedImageID) {
                ForEach(self.eventImages.indices) { image in
                    KFImage(URL(string: self.eventImages[image].url))
                        .placeholder({
                            Image("topo")
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        })
                        .loadDiskFileSynchronously()
                        .cacheMemoryOnly()
                        .fade(duration: 0.2)
                        .resizable()
                        .tag(self.eventImages[image].id)
                        .matchedGeometryEffect(id: self.selectedImageID == self.eventImages[image].id ? self.eventImages[image].id : "", in: self.namespace)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: self.viewWidth, height: self.viewHeight)
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
        }
    }
}

Body:
This is how far I got. The zoom out from FullScreenView to GalleryView works. the only thing that doesn't, is a clean zoom in into the TabView. I suppose this is because of the wrapping by TabView.

struct ImageStruct: Identifiable {
    let id = UUID()
    var image: String = ""
}

let imagesArray = [
    ImageStruct(image: "image1"),
    ImageStruct(image: "image2"),
    ImageStruct(image: "image3"),
    ImageStruct(image: "image4"),
    ImageStruct(image: "image5"),
    ImageStruct(image: "image6"),
    ImageStruct(image: "image7"),
    ImageStruct(image: "image8")
]

struct ContentView: View {

    @Namespace var ns
    @State private var selectedImage: UUID?

    var body: some View {
//        ZStack {
            if selectedImage == nil {
                GalleryView(selectedImage: $selectedImage, ns: ns)
            } else {
                FullScreenView(selectedImage: $selectedImage, ns: ns)
            }
//        }
    }
}

struct GalleryView: View {

    @Binding var selectedImage: UUID?
    var ns: Namespace.ID

    private let columns = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]

    var body: some View {
        VStack {
            ScrollView(.vertical, showsIndicators: true) {

                LazyVGrid(columns: columns) {

                    ForEach(imagesArray) { image in

                        Color.clear.overlay(
                            Image(image.image)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .matchedGeometryEffect(id: image.id, in: ns, isSource: true)
                        )
                            .clipped()
                            .aspectRatio(1, contentMode: .fit)

                            .onTapGesture {
                                withAnimation {
                                    selectedImage = image.id
                                }
                            }
                    }
                }
            }
        }
    }
}

struct FullScreenView: View {

    @Binding var selectedImage: UUID?
    var ns: Namespace.ID

    init(selectedImage: Binding<UUID?>, ns: Namespace.ID) {
        print(selectedImage)
        self._selectedImage = selectedImage
        self.ns = ns
        // initialize selctedTab to selectedImage
        self._selectedTab = State(initialValue: selectedImage.wrappedValue ?? UUID())
    }

    @State private var selectedTab: UUID

    var body: some View {

        TabView(selection: $selectedTab) {

            ForEach(imagesArray) { image in

                Image(image.image)
                    .resizable()
                    .scaledToFit()
                    // ternary applying effect only for selected tab
                    .matchedGeometryEffect(id: image.id == selectedTab ? selectedTab : UUID(),
                                           in: ns, isSource: true)

                    .tag(image.id)

                    .onTapGesture {
                        withAnimation {
                            selectedImage = nil
                        }
                    }
            }
        }
        .tabViewStyle(.page)
    }
}


答:
Your teacher is right. By default, print() wraps. That said, you have to modify your code because this not return the output that you need.
There are many more optimized ways to do this but we'll base it on what you've done.

Try this

```<code>num = int(input())
for i in range(num, 0, -1):
    for j in range(1, i+1):
        print(j, end=' ')
    print()
</code>```

Title: Print() for breaking line in python

Body:
Your teacher is right. By default, print() wraps. That said, you have to modify your code because this not return the output that you need.
There are many more optimized ways to do this but we'll base it on what you've done.

Try this

num = int(input())
for i in range(num, 0, -1):
    for j in range(1, i+1):
        print(j, end=' ')
    print()


问:
How to sum all Object using index with an arrays
how can I search duplicate data using index key object here is my object :

```<code> const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }
</code>```

and I have an arrays

```<code>const arr = ["product1", "product2" ]
</code>```

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

```<code>const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

</code>```

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

```<code> const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }
</code>```

答:
Your problem is that the obj will never contain the key product1 twice. When that object is created during runtime the last value of product1 is what is stored in the object. Even if you had a JSON object with those two keys, when you go to parse it, the last key will be the value. The only way I can think to do what you want is that you need to change the data prior to the object being created.

You added to unique keys, which isn't going to help you as now you'll need to iterate through all the keys to make sure you are getting all of them. You are better off putting the key in the object, and use an array of objects.

const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]
```
<p>You can then use Array.reduce to combine the values, or other methods.</p>
<p>Now to get only product 1 and 2 use filter:</p>
<pre class="lang-js prettyprint-override"><code>const desiredProducts = obj.filter(p => ['product1','product2'].includes(p.key));
``

Or you can combine any matching keys using Array.reduce()

```js
const combinedResult = obj.reduce((cur, acc) => {
  const s = cur.find(c => c.key === acc.key);
  if (s)
    s.price += acc.price;
  else
   cur.push(acc);

}, []);

```

Body:
how can I search duplicate data using index key object here is my object :

 const obj = {
        product1: { name: 'paper', price: 4 },
        product2: { name: 'ball', price: 2 },
        product3: { name: 'ice-cream', price: 9 }
        product1: { name: 'paper', price: 2 }
    }

and I have an arrays

const arr = ["product1", "product2" ]

I want to get only product1 and product2 data then sum price together my output shold look like this 4+2+2 = 8

Here is what I try to do

const newArr = _.map(arr, (name:string) => {
    return obj[name]
})

then I sum

    const sum = newArr.reduce((data, obj)=> data + obj.price, 0);

the problem is in _.map when I map data if I return like this it will get only 1 product1 I want to get all of product name in arr

### UPDATE ####

I changed my object to unique but I still want to use arr to find some word not sure Can I use includes or indexOf in and Objects?

 const obj = {
        "product1 Hello": { name: 'paper', price: 4 },
        "product2 test": { name: 'ball', price: 2 },
        "product3 Hello3": { name: 'ice-cream', price: 9 }
        "product1 Hello4": { name: 'paper', price: 2 }
    }

Body:
Your problem is that the obj will never contain the key product1 twice. When that object is created during runtime the last value of product1 is what is stored in the object. Even if you had a JSON object with those two keys, when you go to parse it, the last key will be the value. The only way I can think to do what you want is that you need to change the data prior to the object being created.

You added to unique keys, which isn't going to help you as now you'll need to iterate through all the keys to make sure you are getting all of them. You are better off putting the key in the object, and use an array of objects.

const obj = [
  {key: 'product1', name: 'paper', price: 4},
  {key: 'product2', name: 'ball', price: 2},
  {key: 'product3', name: 'ice-cream', price: 9},
  {key: 'product1', name: 'paper', price: 2},
]

You can then use Array.reduce to combine the values, or other methods.

Now to get only product 1 and 2 use filter:

const desiredProducts = obj.filter(p => ['product1','product2'].includes(p.key));
``

Or you can combine any matching keys using Array.reduce()

```js
const combinedResult = obj.reduce((cur, acc) => {
  const s = cur.find(c => c.key === acc.key);
  if (s)
    s.price += acc.price;
  else
   cur.push(acc);

}, []);


问:
Fixed List is not updating with for loop - Flutter
I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().</p>
```<code>class MyClubController extends GetxController {

    List goldLane = List.filled(3, null, growable: false);

    void _alterLanesOnContractEnds() {
    for (var i in goldLane) {
      print("\n\n I: $i");
      if (i == null ||
          DateTime.parse(i['contractEnds']).isBefore(
            DateTime.now(),
          )) {
        i = null;
        print('Can be removed');
      } else {
        print('Cannot be removed');
      }
    }
    update();
  }

}
</code>```

答:
I solved it by using

```<code>goldLane.forEach(
      (element) {
        print('\n\n ELEMENT: $element');
        if (element == null ||
            DateTime.parse(element['contractEnds']).isBefore(
              DateTime.now(),
            )) {
          int ix = goldLane.indexWhere(
            (element) => element != null
                ? DateTime.parse(element['contractEnds']).isBefore(
                    DateTime.now(),
                  )
                : true,
          );
          goldLane[ix] = null;
        } else {
          print('Cannot be removed');
        }
      },
    );
</code>```

Yet I'll test the other answers. Thank You.

Body:
I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().

class MyClubController extends GetxController {

    List goldLane = List.filled(3, null, growable: false);

    void _alterLanesOnContractEnds() {
    for (var i in goldLane) {
      print("\n\n I: $i");
      if (i == null ||
          DateTime.parse(i['contractEnds']).isBefore(
            DateTime.now(),
          )) {
        i = null;
        print('Can be removed');
      } else {
        print('Cannot be removed');
      }
    }
    update();
  }

}

Body:
I solved it by using

goldLane.forEach(
      (element) {
        print('\n\n ELEMENT: $element');
        if (element == null ||
            DateTime.parse(element['contractEnds']).isBefore(
              DateTime.now(),
            )) {
          int ix = goldLane.indexWhere(
            (element) => element != null
                ? DateTime.parse(element['contractEnds']).isBefore(
                    DateTime.now(),
                  )
                : true,
          );
          goldLane[ix] = null;
        } else {
          print('Cannot be removed');
        }
      },
    );

Yet I'll test the other answers. Thank You.


问:
Upload large video to GCS use signed url but video is broken
I have a application for Google App Engine(GAE), using Vue.js on the frontend and Flask on the backend.
My app allows users to upload large video and will analyze it. But since GAE's upload size limit is 32MB, so I allow users to upload directly to Google Cloud Storage(GCS) using signed url.

The problem I am facing is that the user can successfully upload the video to GCS, but on the backend(flask) when downloading the video for analysis, get the error below:

```<code>*** OSError: MoviePy error: failed to read the duration of file /tmp/source_video.mp4.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.2.2-static https://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8 (Debian 8.3.0-6)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7444500] Format mov,mp4,m4a,3gp,3g2,mj2 detected only with low score of 1, misdetection possible!
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7444500] moov atom not found
/tmp/source_video.mp4: Invalid data found when processing input
</code>```

Flask code download:

```<code>class Analyser:
    def __init__(self):
        self.gcs_bucket = 'bucket_name'
        self.gcs_blob_video = 'videos/'

    def __storage_bucket(self):
        client = storage.Client()
        bucket = client.get_bucket(self.gcs_bucket)
        bucket.cors = [
            {
                "origin": ["*"],
                "responseHeader": [
                    "Access-Control-Allow-Origin"
                ],
                "method": ['PUT', 'POST', 'GET'],
                "maxAgeSeconds": 3600
            }
        ]
        bucket.patch()
        return bucket

    def __generate_upload_signed_url(self, bucket, blob):
        blob = bucket.blob(blob)
        return blob.generate_signed_url(
            version='v4',
            expiration=datetime.timedelta(minutes=15),
            method='PUT',
        )

    def analyze_video(self, pid):
        src_filepath = '/tmp/source_video.mp4'

        bucket = self.__storage_bucket()
        blob = bucket.blob(self.gcs_blob_video + 'filename.mp4')
        blob.download_to_filename(src_filepath)

        #error is here
        video = VideoFileClip(src_filepath)
</code>```

Vuejs code upload:

note: Uploaded successfully, on gcs there is a file to upload.

```<code>async uploadVideo(_: any, video: File): Promise<string> {
      signed_url = "https://storage.googleapis.com/bucket_name...." #signed url is return from flask
      const formData = new FormData();
      formData.append('file', video);
      const response_upload_file = await fetch(
        signed_url,
        {
          method: 'PUT',
          body: formData
        }
      )
      return true
}
</code>```

I've searched on google quite a bit and still haven't found a solution.

I really don't know if it's broken during the upload or when I download for analysis.
I would be very grateful if someone could suggest me a solution to solve this problem.

Thanks for reading.

答:
You are using formData with the HTTP PUT method which corrupts the upload as a binary data stream is expected and not MIME data.

To use formdata:

Upload an object with HTML forms

Body:
I have a application for Google App Engine(GAE), using Vue.js on the frontend and Flask on the backend.
My app allows users to upload large video and will analyze it. But since GAE's upload size limit is 32MB, so I allow users to upload directly to Google Cloud Storage(GCS) using signed url.

The problem I am facing is that the user can successfully upload the video to GCS, but on the backend(flask) when downloading the video for analysis, get the error below:

*** OSError: MoviePy error: failed to read the duration of file /tmp/source_video.mp4.
Here are the file infos returned by ffmpeg:

ffmpeg version 4.2.2-static https://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8 (Debian 8.3.0-6)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7444500] Format mov,mp4,m4a,3gp,3g2,mj2 detected only with low score of 1, misdetection possible!
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7444500] moov atom not found
/tmp/source_video.mp4: Invalid data found when processing input

Flask code download:

class Analyser:
    def __init__(self):
        self.gcs_bucket = 'bucket_name'
        self.gcs_blob_video = 'videos/'

    def __storage_bucket(self):
        client = storage.Client()
        bucket = client.get_bucket(self.gcs_bucket)
        bucket.cors = [
            {
                "origin": ["*"],
                "responseHeader": [
                    "Access-Control-Allow-Origin"
                ],
                "method": ['PUT', 'POST', 'GET'],
                "maxAgeSeconds": 3600
            }
        ]
        bucket.patch()
        return bucket

    def __generate_upload_signed_url(self, bucket, blob):
        blob = bucket.blob(blob)
        return blob.generate_signed_url(
            version='v4',
            expiration=datetime.timedelta(minutes=15),
            method='PUT',
        )

    def analyze_video(self, pid):
        src_filepath = '/tmp/source_video.mp4'

        bucket = self.__storage_bucket()
        blob = bucket.blob(self.gcs_blob_video + 'filename.mp4')
        blob.download_to_filename(src_filepath)

        #error is here
        video = VideoFileClip(src_filepath)

Vuejs code upload:

note: Uploaded successfully, on gcs there is a file to upload.

async uploadVideo(_: any, video: File): Promise<string> {
      signed_url = "https://storage.googleapis.com/bucket_name...." #signed url is return from flask
      const formData = new FormData();
      formData.append('file', video);
      const response_upload_file = await fetch(
        signed_url,
        {
          method: 'PUT',
          body: formData
        }
      )
      return true
}

I've searched on google quite a bit and still haven't found a solution.

I really don't know if it's broken during the upload or when I download for analysis.
I would be very grateful if someone could suggest me a solution to solve this problem.

Thanks for reading.


问:
When I'm creating Flutter new project lib folder is missing in Android Studio

When I am creating a new Flutter project in Android Studio, lib folder is missing. How to fix it?

I run Flutter doctor,  everything is fine but I am facing this problem.

答:
As "Devarsh Ranpara" comment

change Android directory to Project


问:
How to check that no ItemizedOverlay is Taped on the MapView?
I created an MapView with 2 different Overlays.
One Overlay shows the POIs on the map and the second shows a "bubble" when you click / tab one of the POIs.

Now I want to remove the second overlay when it is visible and no POI is tapped!
I only need to know how to check if I click only the map or one of the POIs??? (also the bubble can be clicked).

答:
In your code, when defining your </p>

```<code>    public class MyItemizedOverlay extends ItemizedOverlay<MyObject>
</code>```

<p>you can override </p>

```<code>    @Override
    protected boolean onTap(final int index) {
        // Called when you tap on an overlay
        return true;
    }

    @Override
    public boolean onTap(GeoPoint p, MapView mapView) {
        // Called when you tap somewhere with no overlay
        // So remove the second overlay here
    }
</code>```

Body:
In your code, when defining your

    public class MyItemizedOverlay extends ItemizedOverlay<MyObject>

you can override

    @Override
    protected boolean onTap(final int index) {
        // Called when you tap on an overlay
        return true;
    }

    @Override
    public boolean onTap(GeoPoint p, MapView mapView) {
        // Called when you tap somewhere with no overlay
        // So remove the second overlay here
    }


问:
Hide the content based on Children class
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

```<code><div class="course-content">
    <h2 class="accesshide"></h2>
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="row">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- Second block Div --

```<code><div class="course-content">
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="single-section">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-content">
        <h2 class="accesshide"></h2>
        <ul class="topics">
            <li class="data-list">Content not to Display</li>
        </ul>
        <div class="row">
            <p>Content to Display (this statement is inaccurate)</p>
        </div>
    </div>

    <div class="course-content">
        <ul class="topics">
            <li class="data-list">Content not to Display (this statement is inaccurate)</li>
        </ul>
        <div class="single-section">
            <p>Content to Display</p>
        </div>
    </div></code>```

答:
Since the controls are independent events, they should be evaluated separately. Therefore, two separate if blocks should be used. In the second event in the solution below, the first child element of the parent element of the selected element is hidden by selecting it.

$(document).ready(function () {
  if ($(".course-content").find(".accesshide")) {
      $(".course-content > .accesshide").find(".topics").show();
  }

  // Because both
 elements have the ".topics" class style applied, the ".single-section"
  // element is selected and the first child element of the parent element is hidden.
  if ($(".course-content").find(".single-section")) {
      $(".course-content > .single-section").parent().children(':first-child').hide();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="course-content">
  <h2 class="accesshide"></h2>

  <ul class="topics">
      <li class="data-list">Content not to Display</li>
  </ul>

  <div class="row">
      <p>Content to Display</p>
  </div>
</div>

<hr>

<div class="course-content">
  <ul class="topics">
      <li class="data-list">Content not to Display</li>
  </ul>

  <div class="single-section">
      <p>Content to Display</p>
  </div>
</div></code>```

Body:
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

Content not to Display

Content to Display

-- Second block Div --

Content not to Display

Content to Display

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});

Content not to Display

Content to Display (this statement is inaccurate)

Content not to Display (this statement is inaccurate)

Content to Display

Body:
Since the controls are independent events, they should be evaluated separately. Therefore, two separate if blocks should be used. In the second event in the solution below, the first child element of the parent element of the selected element is hidden by selecting it.

$(document).ready(function () {
  if ($(".course-content").find(".accesshide")) {
      $(".course-content > .accesshide").find(".topics").show();
  }

  // Because both <div> elements have the ".topics" class style applied, the ".single-section"
  // element is selected and the first child element of the parent element is hidden.
  if ($(".course-content").find(".single-section")) {
      $(".course-content > .single-section").parent().children(':first-child').hide();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="course-content">
  <h2 class="accesshide"></h2>

  <ul class="topics">
      <li class="data-list">Content not to Display</li>
  </ul>

  <div class="row">
      <p>Content to Display</p>
  </div>
</div>

<hr>

<div class="course-content">
  <ul class="topics">
      <li class="data-list">Content not to Display</li>
  </ul>

  <div class="single-section">
      <p>Content to Display</p>
  </div>
</div>


问:
Use thesholds parameter in tf.keras.metrics.Recall
I would like to know how recall gets calculated when multiple thresholds are specified.
Below is the snippet of description from https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Recall

thresholds: (Optional) A float value or a python list/tuple of float threshold values in [0, 1]. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is true, below is false). One metric value is generated for each threshold value. If neither thresholds nor top_k are set, the default is to calculate recall with thresholds=0.5.

I am trying to passing a list of 3 threshold values , and as per the description I expected 3 recall values would be generated (i.e one recall per threshold) , but it isnt working in this way, only 1 recall metric is generated.

```<code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding,Flatten,Dense
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.layers import Dropout
from tensorflow.keras import layers
model=Sequential()
model.add(Embedding(len(tokens)+1,embedding_dim,input_length=MAX_TEXT_LEN,weights=[embedding_matrix]))
model.add(LSTM(128))
model.add(Dropout(0.5))
model.add(Dense(9,activation='sigmoid'))
opt=tf.keras.optimizers.Adam(lr=0.0001)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=[tf.keras.metrics.Recall(thresholds=[0.2,0.4,0.8]))
</code>```

答:
UPDATE

To be able to see metric values for each threshold during training, it is possible to write a custom callback that will log the value for every threshold at the end of each epoch, e.g.

```<code>class CustCallback(callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        print(
            "The validation recall for epoch {} is {} ".format(
                epoch, logs['val_recall_mult_thr']
            )
        )

history = model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    callbacks=[CustCallback()],
    batch_size=64, epochs=3, verbose=2
)
</code>```

I was confused by the "One metric value is generated for each threshold value" language in the documentation too.  It's not what actually happens. The metric  generated is actually the arithmetic mean of the metric across all threshold values you specify in the list.  Here is a binary classification example, where for both True Positives and Recall, one metric is generated with the 0.5 decision threshold and one metric is generated for the provided list of threshold values.

```<code>import numpy as np

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

from tensorflow import keras
from tensorflow.keras import (
    callbacks,
    initializers,
    layers,
    metrics,
    optimizers,
)

from sklearn import __version__ as sk_version
from tensorflow import __version__ as tf_version
print(f"The sklearn version is {sk_version}.")
# The sklearn version is 1.0.2.
print(f"The tensorflow version is {tf_version}.")
# The tensorflow version is 2.7.0.

X1, Y1 = make_classification(
    n_samples=10**6, n_features=10, n_redundant=0, n_informative=4,
    n_clusters_per_class=1, n_classes=2, weights=[0.8, 0.2], random_state=42,
)

X_train, X_test, y_train, y_test = train_test_split(
    X1, Y1, test_size=10**6 // 3, random_state=42
)

model = keras.Sequential()
ki = initializers.RandomNormal(mean=0.0, stddev=0.05, seed=123)
model.add(
    layers.Dense(
        5,
        kernel_initializer=ki,
        bias_initializer="zeros",
        input_shape=(X_train.shape[1],),
        activation="relu",
    )
)
model.add(
    layers.Dense(
        1, activation="sigmoid"
    )
)

opt = optimizers.Adam(learning_rate=0.01)
thresh_list = list(np.arange(0.05, 1, 0.05))

model.compile(
    loss='binary_crossentropy',
    optimizer=opt,
    metrics=[
        metrics.TruePositives(thresholds=0.5, name="tp_0_5"),
        metrics.TruePositives(thresholds=thresh_list, name='tp_mult_thr'),
        metrics.FalsePositives(name="fp"),
        metrics.TrueNegatives(name="tn"),
        metrics.FalseNegatives(name="fn"),
        metrics.Recall(thresholds=0.5, name='recall_0_5'),
        metrics.Recall(
            thresholds=thresh_list,
            name="recall_mult_thr",
        ),
    ],
)

model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    batch_size=64, epochs=3, verbose=2
)

# Epoch 1/3
# 10417/10417 - 23s - loss: 0.0857 - tp_0_5: 123905.0000 - tp_mult_thr: 121617.1016 -
# fp: 5823.0000 - tn: 525617.0000 - fn: 11322.0000 - recall_0_5: 0.9163 -
# recall_mult_thr: 0.8994 - val_loss: 0.0809 - val_tp_0_5: 61862.0000 -
# val_tp_mult_thr: 60766.5781 - val_fp: 2210.0000 - val_tn: 263435.0000 -
# val_fn: 5826.0000 - val_recall_0_5: 0.9139 - val_recall_mult_thr: 0.8977 -
# 23s/epoch - 2ms/step
# Epoch 2/3
# 10417/10417 - 24s - loss: 0.0806 - tp_0_5: 124853.0000 - tp_mult_thr: 122652.4766 -
# fp: 5573.0000 - tn: 525867.0000 - fn: 10374.0000 - recall_0_5: 0.9233 -
# recall_mult_thr: 0.9070 - val_loss: 0.0789 - val_tp_0_5: 62789.0000 -
# val_tp_mult_thr: 61644.4219 - val_fp: 2889.0000 - val_tn: 262756.0000 -
# val_fn: 4899.0000 - val_recall_0_5: 0.9276 - val_recall_mult_thr: 0.9107 -
# 24s/epoch - 2ms/step
# Epoch 3/3
# 10417/10417 - 25s - loss: 0.0777 - tp_0_5: 125268.0000 - tp_mult_thr: 123142.8984 -
# fp: 5556.0000 - tn: 525884.0000 - fn: 9959.0000 - recall_0_5: 0.9264 -
# recall_mult_thr: 0.9106 - val_loss: 0.0781 - val_tp_0_5: 61261.0000 -
# val_tp_mult_thr: 60321.4727 - val_fp: 1638.0000 - val_tn: 264007.0000 -
# val_fn: 6427.0000 - val_recall_0_5: 0.9050 - val_recall_mult_thr: 0.8912 -
# 25s/epoch - 2ms/step
</code>```

The validation set Recall for the 0.5 threshold (.9050) is as expected:

```<code>from sklearn.metrics import recall_score

pred_probs = model.predict(X_test)

for t in thresh_list:
    print(
        f"threshold: {t:.2f}, "
        f"recall: {recall_score(y_test, (pred_probs >= t).astype('int8'))}"
    )
# threshold: 0.05, recall: 0.9748847653941615
# threshold: 0.10, recall: 0.9671876846708427
# threshold: 0.15, recall: 0.9597565299609975
# threshold: 0.20, recall: 0.9526947169365323
# threshold: 0.25, recall: 0.9446726155300792
# threshold: 0.30, recall: 0.9371971398179885
# threshold: 0.35, recall: 0.9298546271126344
# threshold: 0.40, recall: 0.9214779576882165
# threshold: 0.45, recall: 0.9133967616121026
# threshold: 0.50, recall: 0.905049639522515  <---
# threshold: 0.55, recall: 0.8952990190284836
# threshold: 0.60, recall: 0.8855483985344522
# threshold: 0.65, recall: 0.8741283536225033
# threshold: 0.70, recall: 0.8619105306701336
# threshold: 0.75, recall: 0.8483039829807352
# threshold: 0.80, recall: 0.8315654177993145
# threshold: 0.85, recall: 0.8107640940787141
# threshold: 0.90, recall: 0.7819258952842454
# threshold: 0.95, recall: 0.7366002836544143
</code>```

But the validation set Recall for multiple thresholds (.8912) is the mean of recalls across all thresholds:

```<code>np.mean([recall_score(y_test, (pred_probs >= t).astype('int8')) for t in thresh_list])
# 0.8911693902052141
</code>```

The same applies to True Positives:

```<code>from sklearn.metrics import confusion_matrix

for t in thresh_list:
    print(
        f"threshold: {t:.2f}, "
        f"TPs: {confusion_matrix(y_test, (pred_probs >= t).astype('int8'))[1, 1]}"
    )
# threshold: 0.05, TPs: 65988
# threshold: 0.10, TPs: 65467
# threshold: 0.15, TPs: 64964
# threshold: 0.20, TPs: 64486
# threshold: 0.25, TPs: 63943
# threshold: 0.30, TPs: 63437
# threshold: 0.35, TPs: 62940
# threshold: 0.40, TPs: 62373
# threshold: 0.45, TPs: 61826
# threshold: 0.50, TPs: 61261 <---
# threshold: 0.55, TPs: 60601
# threshold: 0.60, TPs: 59941
# threshold: 0.65, TPs: 59168
# threshold: 0.70, TPs: 58341
# threshold: 0.75, TPs: 57420
# threshold: 0.80, TPs: 56287
# threshold: 0.85, TPs: 54879
# threshold: 0.90, TPs: 52927
# threshold: 0.95, TPs: 49859
</code>```

And:

```<code>tp_list = list()
for t in thresh_list:
    tp_list.append(
        confusion_matrix(y_test, (pred_probs >= t).astype('int8'))[1, 1]
    )

print(f"Avg TPs across all thresholds: {np.mean(tp_list)}")
# Avg TPs across all thresholds: 60321.47368421053
</code>```

Body:
I would like to know how recall gets calculated when multiple thresholds are specified.
Below is the snippet of description from https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Recall

thresholds: (Optional) A float value or a python list/tuple of float threshold values in [0, 1]. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is true, below is false). One metric value is generated for each threshold value. If neither thresholds nor top_k are set, the default is to calculate recall with thresholds=0.5.

I am trying to passing a list of 3 threshold values , and as per the description I expected 3 recall values would be generated (i.e one recall per threshold) , but it isnt working in this way, only 1 recall metric is generated.

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding,Flatten,Dense
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.layers import Dropout
from tensorflow.keras import layers
model=Sequential()
model.add(Embedding(len(tokens)+1,embedding_dim,input_length=MAX_TEXT_LEN,weights=[embedding_matrix]))
model.add(LSTM(128))
model.add(Dropout(0.5))
model.add(Dense(9,activation='sigmoid'))
opt=tf.keras.optimizers.Adam(lr=0.0001)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=[tf.keras.metrics.Recall(thresholds=[0.2,0.4,0.8]))

Body:
UPDATE

To be able to see metric values for each threshold during training, it is possible to write a custom callback that will log the value for every threshold at the end of each epoch, e.g.

class CustCallback(callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        print(
            "The validation recall for epoch {} is {} ".format(
                epoch, logs['val_recall_mult_thr']
            )
        )

history = model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    callbacks=[CustCallback()],
    batch_size=64, epochs=3, verbose=2
)

I was confused by the "One metric value is generated for each threshold value" language in the documentation too.  It's not what actually happens. The metric  generated is actually the arithmetic mean of the metric across all threshold values you specify in the list.  Here is a binary classification example, where for both True Positives and Recall, one metric is generated with the 0.5 decision threshold and one metric is generated for the provided list of threshold values.

import numpy as np

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

from tensorflow import keras
from tensorflow.keras import (
    callbacks,
    initializers,
    layers,
    metrics,
    optimizers,
)

from sklearn import __version__ as sk_version
from tensorflow import __version__ as tf_version
print(f"The sklearn version is {sk_version}.")
# The sklearn version is 1.0.2.
print(f"The tensorflow version is {tf_version}.")
# The tensorflow version is 2.7.0.

X1, Y1 = make_classification(
    n_samples=10**6, n_features=10, n_redundant=0, n_informative=4,
    n_clusters_per_class=1, n_classes=2, weights=[0.8, 0.2], random_state=42,
)

X_train, X_test, y_train, y_test = train_test_split(
    X1, Y1, test_size=10**6 // 3, random_state=42
)

model = keras.Sequential()
ki = initializers.RandomNormal(mean=0.0, stddev=0.05, seed=123)
model.add(
    layers.Dense(
        5,
        kernel_initializer=ki,
        bias_initializer="zeros",
        input_shape=(X_train.shape[1],),
        activation="relu",
    )
)
model.add(
    layers.Dense(
        1, activation="sigmoid"
    )
)

opt = optimizers.Adam(learning_rate=0.01)
thresh_list = list(np.arange(0.05, 1, 0.05))

model.compile(
    loss='binary_crossentropy',
    optimizer=opt,
    metrics=[
        metrics.TruePositives(thresholds=0.5, name="tp_0_5"),
        metrics.TruePositives(thresholds=thresh_list, name='tp_mult_thr'),
        metrics.FalsePositives(name="fp"),
        metrics.TrueNegatives(name="tn"),
        metrics.FalseNegatives(name="fn"),
        metrics.Recall(thresholds=0.5, name='recall_0_5'),
        metrics.Recall(
            thresholds=thresh_list,
            name="recall_mult_thr",
        ),
    ],
)

model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    batch_size=64, epochs=3, verbose=2
)

# Epoch 1/3
# 10417/10417 - 23s - loss: 0.0857 - tp_0_5: 123905.0000 - tp_mult_thr: 121617.1016 -
# fp: 5823.0000 - tn: 525617.0000 - fn: 11322.0000 - recall_0_5: 0.9163 -
# recall_mult_thr: 0.8994 - val_loss: 0.0809 - val_tp_0_5: 61862.0000 -
# val_tp_mult_thr: 60766.5781 - val_fp: 2210.0000 - val_tn: 263435.0000 -
# val_fn: 5826.0000 - val_recall_0_5: 0.9139 - val_recall_mult_thr: 0.8977 -
# 23s/epoch - 2ms/step
# Epoch 2/3
# 10417/10417 - 24s - loss: 0.0806 - tp_0_5: 124853.0000 - tp_mult_thr: 122652.4766 -
# fp: 5573.0000 - tn: 525867.0000 - fn: 10374.0000 - recall_0_5: 0.9233 -
# recall_mult_thr: 0.9070 - val_loss: 0.0789 - val_tp_0_5: 62789.0000 -
# val_tp_mult_thr: 61644.4219 - val_fp: 2889.0000 - val_tn: 262756.0000 -
# val_fn: 4899.0000 - val_recall_0_5: 0.9276 - val_recall_mult_thr: 0.9107 -
# 24s/epoch - 2ms/step
# Epoch 3/3
# 10417/10417 - 25s - loss: 0.0777 - tp_0_5: 125268.0000 - tp_mult_thr: 123142.8984 -
# fp: 5556.0000 - tn: 525884.0000 - fn: 9959.0000 - recall_0_5: 0.9264 -
# recall_mult_thr: 0.9106 - val_loss: 0.0781 - val_tp_0_5: 61261.0000 -
# val_tp_mult_thr: 60321.4727 - val_fp: 1638.0000 - val_tn: 264007.0000 -
# val_fn: 6427.0000 - val_recall_0_5: 0.9050 - val_recall_mult_thr: 0.8912 -
# 25s/epoch - 2ms/step

The validation set Recall for the 0.5 threshold (.9050) is as expected:

from sklearn.metrics import recall_score

pred_probs = model.predict(X_test)

for t in thresh_list:
    print(
        f"threshold: {t:.2f}, "
        f"recall: {recall_score(y_test, (pred_probs >= t).astype('int8'))}"
    )
# threshold: 0.05, recall: 0.9748847653941615
# threshold: 0.10, recall: 0.9671876846708427
# threshold: 0.15, recall: 0.9597565299609975
# threshold: 0.20, recall: 0.9526947169365323
# threshold: 0.25, recall: 0.9446726155300792
# threshold: 0.30, recall: 0.9371971398179885
# threshold: 0.35, recall: 0.9298546271126344
# threshold: 0.40, recall: 0.9214779576882165
# threshold: 0.45, recall: 0.9133967616121026
# threshold: 0.50, recall: 0.905049639522515  <---
# threshold: 0.55, recall: 0.8952990190284836
# threshold: 0.60, recall: 0.8855483985344522
# threshold: 0.65, recall: 0.8741283536225033
# threshold: 0.70, recall: 0.8619105306701336
# threshold: 0.75, recall: 0.8483039829807352
# threshold: 0.80, recall: 0.8315654177993145
# threshold: 0.85, recall: 0.8107640940787141
# threshold: 0.90, recall: 0.7819258952842454
# threshold: 0.95, recall: 0.7366002836544143

But the validation set Recall for multiple thresholds (.8912) is the mean of recalls across all thresholds:

np.mean([recall_score(y_test, (pred_probs >= t).astype('int8')) for t in thresh_list])
# 0.8911693902052141

The same applies to True Positives:

from sklearn.metrics import confusion_matrix

for t in thresh_list:
    print(
        f"threshold: {t:.2f}, "
        f"TPs: {confusion_matrix(y_test, (pred_probs >= t).astype('int8'))[1, 1]}"
    )
# threshold: 0.05, TPs: 65988
# threshold: 0.10, TPs: 65467
# threshold: 0.15, TPs: 64964
# threshold: 0.20, TPs: 64486
# threshold: 0.25, TPs: 63943
# threshold: 0.30, TPs: 63437
# threshold: 0.35, TPs: 62940
# threshold: 0.40, TPs: 62373
# threshold: 0.45, TPs: 61826
# threshold: 0.50, TPs: 61261 <---
# threshold: 0.55, TPs: 60601
# threshold: 0.60, TPs: 59941
# threshold: 0.65, TPs: 59168
# threshold: 0.70, TPs: 58341
# threshold: 0.75, TPs: 57420
# threshold: 0.80, TPs: 56287
# threshold: 0.85, TPs: 54879
# threshold: 0.90, TPs: 52927
# threshold: 0.95, TPs: 49859

And:

tp_list = list()
for t in thresh_list:
    tp_list.append(
        confusion_matrix(y_test, (pred_probs >= t).astype('int8'))[1, 1]
    )

print(f"Avg TPs across all thresholds: {np.mean(tp_list)}")
# Avg TPs across all thresholds: 60321.47368421053


问:
Outside context error when working from blueprint flask python
I have this simple webapp written in python (Flask)

models.py

```<code>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Coin(db.Model):
    __tablename__ = "coins"
    id = db.Column(db.Integer, primary_key=True)
    pair = db.Column(db.String)
    sell_amt = db.Column(db.Float)
    buy_amt = db.Column(db.Float)
</code>```

app.py

```<code>from flask import Flask
from ui import ui
from models import db , Coin

app = Flask(__name__)
app.register_blueprint(ui)
db.init_app(app)

if __name__ == "__main__":
    app.run(port=8080)
</code>```

__init__.py in ui folder

```<code>from flask import Blueprint ,current_app
from models import db, Coin
from threading import Thread
ui = Blueprint('ui', __name__)

def intro():
    global bot_state
    with current_app.app_context():
        all_coins = Coin.query.filter_by().all()
    while bot_state:
        sleep(3)
        print (f" Current time : {time()}")

@ui.route('/startbot')
def start_bot():
    global bot_thread, bot_state
    bot_state = True

    bot_thread = Thread(target=intro ,daemon=True)
    bot_thread.start()
    return "bot started "

@ui.route('/stopbot')
def stop_bot():
    global bot_state
    bot_state = False
    bot_thread.join()
    return  " bot stopped"
</code>```

When create a request to /startbot the app throws the error the it is working outside the app context

```<code>RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.
</code>```

but when trying to create a database object for example new = Coin() it works fine, how do you give a function the context of the application without making a function that returns the app, because doing so creates another error that is (circular import)

Note this is the bare minimum example and there are other files that require access to the models.py folder (to add orders to the data base created by the bot )

答:
There has to be a better way of doing it but this is what I managed to do, we create two apps the first one is the main web app, and looks sth like this

app = Flask(__name__)
app.register_blueprint(some_blueprint)
db.init_app(app)
```
<p>and the second app will be for the bot and will be declared in the same file where the bot core code is written and can be imported into the blueprint and looks like this</p>
<pre class="lang-py prettyprint-override"><code>bot_app = Flask(__name__)
db.init_app(app)
</code>```

Now intro will look sth like this

from bot_file import bot_app

def intro(app):
    with bot_app.app_context():
        all_coins = Coin.query.all()

```

this way we can use the bot_app in the bot_core class with out importing the main web app

This isn't the most preferable code out there but it does solve this problem

Body:
I have this simple webapp written in python (Flask)

models.py

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Coin(db.Model):
    __tablename__ = "coins"
    id = db.Column(db.Integer, primary_key=True)
    pair = db.Column(db.String)
    sell_amt = db.Column(db.Float)
    buy_amt = db.Column(db.Float)

app.py

from flask import Flask
from ui import ui
from models import db , Coin

app = Flask(__name__)
app.register_blueprint(ui)
db.init_app(app)

if __name__ == "__main__":
    app.run(port=8080)

__init__.py in ui folder

from flask import Blueprint ,current_app
from models import db, Coin
from threading import Thread
ui = Blueprint('ui', __name__)

def intro():
    global bot_state
    with current_app.app_context():
        all_coins = Coin.query.filter_by().all()
    while bot_state:
        sleep(3)
        print (f" Current time : {time()}")

@ui.route('/startbot')
def start_bot():
    global bot_thread, bot_state
    bot_state = True

    bot_thread = Thread(target=intro ,daemon=True)
    bot_thread.start()
    return "bot started "

@ui.route('/stopbot')
def stop_bot():
    global bot_state
    bot_state = False
    bot_thread.join()
    return  " bot stopped"

When create a request to /startbot the app throws the error the it is working outside the app context

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

but when trying to create a database object for example new = Coin() it works fine, how do you give a function the context of the application without making a function that returns the app, because doing so creates another error that is (circular import)

Note this is the bare minimum example and there are other files that require access to the models.py folder (to add orders to the data base created by the bot )

Body:
There has to be a better way of doing it but this is what I managed to do, we create two apps the first one is the main web app, and looks sth like this

app = Flask(__name__)
app.register_blueprint(some_blueprint)
db.init_app(app)

and the second app will be for the bot and will be declared in the same file where the bot core code is written and can be imported into the blueprint and looks like this

bot_app = Flask(__name__)
db.init_app(app)

Now intro will look sth like this

from bot_file import bot_app

def intro(app):
    with bot_app.app_context():
        all_coins = Coin.query.all()

this way we can use the bot_app in the bot_core class with out importing the main web app

This isn't the most preferable code out there but it does solve this problem