问:
Adding Metadata to NITF and GeoTiff files
I am building an application to add metadata to nitf and geotiff images. I am using tkinter and gdal to add and edit metadata, which I have been able to do using file.SetMetadata.

What I am not sure about is if metadata I add is being saved or if it gets overwritten every time I add new metadata.For example:

Users add a tag and content in two entry fields in tkinter. The tag and content get appended to two lists, which are zipped into a dictionary that gets passed to SetMetadata

```<code>ds2.SetMetadata((dict(zip(TAGs2, Content2))))
</code>```

The added metadata shows in the .aux file and when I print gdal.info()

When I close the application and run it again with new metadata, only the new metadata shows in the .aux and in gdal.info. It seems like metadata I created previously is being overwritten. I am unfamilliar with gdal and was hoping someone could confirm this before I continue.

Thank you

Body:
I am building an application to add metadata to nitf and geotiff images. I am using tkinter and gdal to add and edit metadata, which I have been able to do using file.SetMetadata.

What I am not sure about is if metadata I add is being saved or if it gets overwritten every time I add new metadata.For example:

Users add a tag and content in two entry fields in tkinter. The tag and content get appended to two lists, which are zipped into a dictionary that gets passed to SetMetadata

ds2.SetMetadata((dict(zip(TAGs2, Content2))))

The added metadata shows in the .aux file and when I print gdal.info()

When I close the application and run it again with new metadata, only the new metadata shows in the .aux and in gdal.info. It seems like metadata I created previously is being overwritten. I am unfamilliar with gdal and was hoping someone could confirm this before I continue.

Thank you


来源: stackexchange

问:
Can't understand why not from visual tree items bindings to other view elements don't work in wpf
I have a simple sample project - MainWindow that initializes another window (BorderWondow) and its child control (UserControl1) and view model for UserControl1 (UserControlViewModel).

```<code> public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var win = new BorderWindow();
            var control = new UserControl1();
            control.UserControlVM.DoSomething();
            win.Show(control);
        }
    }
</code>```
```<code>public partial class BorderWindow : Window
{
    public BorderWindow()
    {
        InitializeComponent();
    }

    public void Show(UserControl control)
    {
        ContentBorder.Child = control;
        Show();
    }
}
</code>```
```<code>    public partial class UserControl1 : UserControl
    {
        public UserControlViewModel UserControlVM;
        public UserControl1()
        {
            InitializeComponent();
            UserControlVM = new UserControlViewModel();
            DataContext = UserControlVM;

        }
    }
</code>```
```<code>public class UserControlViewModel
{
    private void ShowCompleteMessage()
    {
        MessageBox.Show("Complete!");
    }

    public void DoSomething()
    {
        //do something
        ShowCompleteMessage();
    }
}
</code>```
```<code>UserControl x:Class="WpfApp3.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:s="http://schemas.abtsoftware.co.uk/scichart"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0">
            <ToggleButton IsChecked="True" Width="Auto" Height="25" Content="MouseWheelEnable" x:Name="tglBtn"/>
        </StackPanel>
        <s:SciChartSurface Grid.Row="1">
            <s:SciChartSurface.XAxis >
                <s:NumericAxis/>
            </s:SciChartSurface.XAxis>
            <s:SciChartSurface.YAxis>
                <s:NumericAxis/>
            </s:SciChartSurface.YAxis>
            <s:SciChartSurface.ChartModifier>
                <s:ModifierGroup>
                    <s:MouseWheelZoomModifier IsEnabled="{Binding ElementName=tglBtn, Path=IsChecked}"/>
                </s:ModifierGroup>
            </s:SciChartSurface.ChartModifier>
        </s:SciChartSurface>
    </Grid>
</UserControl>
</code>```

As you can see, in UserControl1 xaml markup I have toggle button and MouseWheelZoomModifier (element not from the visual tree), whose IsEnabled property is binding to toggle button IsChecked property.

In MainWindow class, if i call DoSomething method from my UserControl1 view model, and then call win.Show(control) method (as a result of executing the method, it will open a MessageBox), my binding will failure. But If I switch this calls (first call - win.Show(control), second - DoSomething()), binding will work correctly! Also, regardless of the order of calls, the binding will work if I bind the toggle button and the MouseWheelZoomModifier to the view model property.

I can't understand why if I show MessageBox (or another custom window) before showing window with user control, binding of my UserControl1 fails (exactly of an element not from the visual tree to a property not from the view model, but to a property of another visual element).

ContentLicense: CC BY-SA 4.0

Body:
I have a simple sample project - MainWindow that initializes another window (BorderWondow) and its child control (UserControl1) and view model for UserControl1 (UserControlViewModel).

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var win = new BorderWindow();
            var control = new UserControl1();
            control.UserControlVM.DoSomething();
            win.Show(control);
        }
    }

public partial class BorderWindow : Window
{
    public BorderWindow()
    {
        InitializeComponent();
    }

    public void Show(UserControl control)
    {
        ContentBorder.Child = control;
        Show();
    }
}

    public partial class UserControl1 : UserControl
    {
        public UserControlViewModel UserControlVM;
        public UserControl1()
        {
            InitializeComponent();
            UserControlVM = new UserControlViewModel();
            DataContext = UserControlVM;

        }
    }

public class UserControlViewModel
{
    private void ShowCompleteMessage()
    {
        MessageBox.Show("Complete!");
    }

    public void DoSomething()
    {
        //do something
        ShowCompleteMessage();
    }
}

UserControl x:Class="WpfApp3.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:s="http://schemas.abtsoftware.co.uk/scichart"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0">
            <ToggleButton IsChecked="True" Width="Auto" Height="25" Content="MouseWheelEnable" x:Name="tglBtn"/>
        </StackPanel>
        <s:SciChartSurface Grid.Row="1">
            <s:SciChartSurface.XAxis >
                <s:NumericAxis/>
            </s:SciChartSurface.XAxis>
            <s:SciChartSurface.YAxis>
                <s:NumericAxis/>
            </s:SciChartSurface.YAxis>
            <s:SciChartSurface.ChartModifier>
                <s:ModifierGroup>
                    <s:MouseWheelZoomModifier IsEnabled="{Binding ElementName=tglBtn, Path=IsChecked}"/>
                </s:ModifierGroup>
            </s:SciChartSurface.ChartModifier>
        </s:SciChartSurface>
    </Grid>
</UserControl>

As you can see, in UserControl1 xaml markup I have toggle button and MouseWheelZoomModifier (element not from the visual tree), whose IsEnabled property is binding to toggle button IsChecked property.

In MainWindow class, if i call DoSomething method from my UserControl1 view model, and then call win.Show(control) method (as a result of executing the method, it will open a MessageBox), my binding will failure. But If I switch this calls (first call - win.Show(control), second - DoSomething()), binding will work correctly! Also, regardless of the order of calls, the binding will work if I bind the toggle button and the MouseWheelZoomModifier to the view model property.

I can't understand why if I show MessageBox (or another custom window) before showing window with user control, binding of my UserControl1 fails (exactly of an element not from the visual tree to a property not from the view model, but to a property of another visual element).


问:
How can I create a pie/gauge chart showing the lines between the bar gaps with recharts?
I would like to create a semi circle chart showing both the bars information and the information between the bar gaps.

Today the chart looks like this:

stability_graph_before

But I would like to have something like:

stability_graph_after

It's possible to do this using recharts lib?


问:
JSONException: No value for myRating even when value exist on same node
My app was working fine but suddenly it start giving me erros JSONException: No value for myRating. I know it's means the value doesn't exist on JSON but i cross check dozens times that myRating exist in JSON i received and i am also able to get other values from same node.

Here is my JSON

```<code>{
    "status": "SUCCESS",
    "uData": [
        {
            "User_ID": "210",
            "First_Name": "Alex ",
            "Image": "947d051925ba2014f231f17ffc04db6616645163211632870246.jpg",
            "coverPhoto": "1ce295d101204be40363f1e11301ed97d41d8cd98f00b204e9800998ecf8427e16645163211188778355.jpg",
            "Gender": "Male",
            "login_status": "0",
            "myRating": "5.00",
            "coverImageID": "354",
            "ProfileImageID": "343",
            "show_onlineStatus_check": "1",
            "verify": "1"
        },
        {
            "User_ID": "4",
            "First_Name": "John",
            "Image": "cf867d87b655591cbda928287da1ca3616520548151008802.jpg",
            "coverPhoto": "0323e6cfa77488abce52aa273e2f5f8e16523048561229563452.jpg",
            "Gender": "Female",
            "login_status": "0",
            "myRating": "5.00",
            "distance_check": "1",
            "coverImageID": "173",
            "ProfileImageID": "174",
            "show_onlineStatus_check": "1",
            "verify": "2"
        }
    ],
    "record": 3,
    "uCounter": "50"
}
</code>```

That's how i am parsing JSON into my app

```<code>JSONObject parentArray = new JSONObject(completeJSON);
Log.d(TAG, "Parent Array " + parentArray);
JSONArray jsonArray = parentArray.getJSONArray("uData");
String profileCounter = parentArray.getString("uCounter");
Log.d(TAG, "JSON Array Of UDATA " + jsonArray); // User Data Where I have myRating node

String ImageURL, UserID, Distance, CoverPhoto, myRatings = null;
int Rec_Online_Status;
int distance_check, onlineStatus, verifyProfile;

for (int i = 0; i < jsonArray.length(); i++) {

    JSONObject childObject = jsonArray.getJSONObject(i);
    String Fname = childObject.getString("First_Name");

    ImageURL = childObject.getString("Image");
    CoverPhoto = childObject.getString("coverPhoto");

    UserID = childObject.getString("User_ID");

    String gender = childObject.getString("Gender");
    Rec_Online_Status = childObject.getInt("login_status");

    distance_check = Integer.parseInt(childObject.getString("distance_check"));
    onlineStatus = Integer.parseInt(childObject.getString("show_onlineStatus_check"));
    verifyProfile = Integer.parseInt(childObject.getString("verify"));
    boolean testValue = childObject.has("myRating");
    Log.d(TAG, "doInBackground: Test Log = "+testValue);// This also return False
    myRatings = childObject.getString("myRating");// JSONException: No value for myRating

    int profileID = Integer.parseInt(childObject.getString("ProfileImageID"));
    int coverID = Integer.parseInt(childObject.getString("coverImageID"));
}
</code>```

I am really not sure what i am doing wrong and when value exist in same node it should get fetched but as you can see i am  getting exception. Can anyone help me out in this. The is required to run app so i am not using has or optString.

Body:
My app was working fine but suddenly it start giving me erros JSONException: No value for myRating. I know it's means the value doesn't exist on JSON but i cross check dozens times that myRating exist in JSON i received and i am also able to get other values from same node.

Here is my JSON

{
    "status": "SUCCESS",
    "uData": [
        {
            "User_ID": "210",
            "First_Name": "Alex ",
            "Image": "947d051925ba2014f231f17ffc04db6616645163211632870246.jpg",
            "coverPhoto": "1ce295d101204be40363f1e11301ed97d41d8cd98f00b204e9800998ecf8427e16645163211188778355.jpg",
            "Gender": "Male",
            "login_status": "0",
            "myRating": "5.00",
            "coverImageID": "354",
            "ProfileImageID": "343",
            "show_onlineStatus_check": "1",
            "verify": "1"
        },
        {
            "User_ID": "4",
            "First_Name": "John",
            "Image": "cf867d87b655591cbda928287da1ca3616520548151008802.jpg",
            "coverPhoto": "0323e6cfa77488abce52aa273e2f5f8e16523048561229563452.jpg",
            "Gender": "Female",
            "login_status": "0",
            "myRating": "5.00",
            "distance_check": "1",
            "coverImageID": "173",
            "ProfileImageID": "174",
            "show_onlineStatus_check": "1",
            "verify": "2"
        }
    ],
    "record": 3,
    "uCounter": "50"
}

That's how i am parsing JSON into my app

JSONObject parentArray = new JSONObject(completeJSON);
Log.d(TAG, "Parent Array " + parentArray);
JSONArray jsonArray = parentArray.getJSONArray("uData");
String profileCounter = parentArray.getString("uCounter");
Log.d(TAG, "JSON Array Of UDATA " + jsonArray); // User Data Where I have myRating node

String ImageURL, UserID, Distance, CoverPhoto, myRatings = null;
int Rec_Online_Status;
int distance_check, onlineStatus, verifyProfile;

for (int i = 0; i < jsonArray.length(); i++) {

    JSONObject childObject = jsonArray.getJSONObject(i);
    String Fname = childObject.getString("First_Name");

    ImageURL = childObject.getString("Image");
    CoverPhoto = childObject.getString("coverPhoto");

    UserID = childObject.getString("User_ID");

    String gender = childObject.getString("Gender");
    Rec_Online_Status = childObject.getInt("login_status");

    distance_check = Integer.parseInt(childObject.getString("distance_check"));
    onlineStatus = Integer.parseInt(childObject.getString("show_onlineStatus_check"));
    verifyProfile = Integer.parseInt(childObject.getString("verify"));
    boolean testValue = childObject.has("myRating");
    Log.d(TAG, "doInBackground: Test Log = "+testValue);// This also return False
    myRatings = childObject.getString("myRating");// JSONException: No value for myRating

    int profileID = Integer.parseInt(childObject.getString("ProfileImageID"));
    int coverID = Integer.parseInt(childObject.getString("coverImageID"));
}

I am really not sure what i am doing wrong and when value exist in same node it should get fetched but as you can see i am  getting exception. Can anyone help me out in this. The is required to run app so i am not using has or optString.


问:
How to tracker screen time of a component in React Application?
I want to track time for which a given component was rendered with given props and active screen in React. What is the best possible way to approach this problem ? I wasn't able to find any good library that would allow this.

Start timer - When component mounts

Pause timer - if user navigates to different screen or switches the tab or loses focus.

Stop timer when the component is unmounted or on navigation.


问:
Docker authorization. Read model stocked in google bucket
I have a docker file that use a model .pkl stocked in a bucket on Google cloud. When I build the docker and I run it in local I receive this error:

I used this code:

```<code>def load_model_from_cloud():
    fs = gcsfs.GCSFileSystem(project="gclou-project")
    client = storage.Client.from_service_account_json("key.json")
    bucket = client.bucket("name_bucket")
    blob = bucket.blob("model.pkl")
    with fs.open(f'name_bucket/{blob.name}') as f:
        model = joblib.load(f)
    return model
</code>```

and I received this error:

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

I need stock the model in a bucket, it will be constantly updated and an api stocked in container registry that can take the updated model and give me my prediction

Body:
I have a docker file that use a model .pkl stocked in a bucket on Google cloud. When I build the docker and I run it in local I receive this error:

I used this code:

def load_model_from_cloud():
    fs = gcsfs.GCSFileSystem(project="gclou-project")
    client = storage.Client.from_service_account_json("key.json")
    bucket = client.bucket("name_bucket")
    blob = bucket.blob("model.pkl")
    with fs.open(f'name_bucket/{blob.name}') as f:
        model = joblib.load(f)
    return model

and I received this error:

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

I need stock the model in a bucket, it will be constantly updated and an api stocked in container registry that can take the updated model and give me my prediction


问:
Page not found (404) Error in Django How can access to my Aboutus Page
When i click my about us button in my web site it gives me this error:

```<code>Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/aboutus
Raised by:  django.views.static.serve
</code>```

My home/urls.py

```<code>from home import views

urlpatterns = [
    path('home/', include('home.urls')),
    path('aboutus/', views.aboutus , name='aboutus'),
]
</code>```

My home/views.py:

```<code>from django.http import HttpResponse
from django.shortcuts import render

from home.models import Setting

def index(request):
    setting=Setting.objects.get(pk=1)
    context={'setting':setting, 'page':'home'}
    return render(request,'index.html',context)

def aboutus(request):
    setting=Setting.objects.get(pk=1)
    context={'setting':setting , 'page':'aboutus'}
    return render(request,'aboutus.html',context)
</code>```

Body:
When i click my about us button in my web site it gives me this error:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/aboutus
Raised by:  django.views.static.serve

My home/urls.py

from home import views

urlpatterns = [
    path('home/', include('home.urls')),
    path('aboutus/', views.aboutus , name='aboutus'),
]

My home/views.py:

from django.http import HttpResponse
from django.shortcuts import render

from home.models import Setting

def index(request):
    setting=Setting.objects.get(pk=1)
    context={'setting':setting, 'page':'home'}
    return render(request,'index.html',context)

def aboutus(request):
    setting=Setting.objects.get(pk=1)
    context={'setting':setting , 'page':'aboutus'}
    return render(request,'aboutus.html',context)


问:
Spring Reactive Web Flux/REST API, filtering data
I am trying to stream data from an API (using a sample API from sampleapis.com) using a given JSON API. Bear with me, I'm new to this.

I have successfully modeled the data from the countries API (found here: https://sampleapis.com/api-list/countries), and I have managed to create a simple script to stream this unfiltered data. I want to be able to do  a form on the index page which allows me to specify some criteria by which to filter/search this data. For example, ordering countries by population, or inputting a value x into a form and returns the countries/country data for whichever countries exceed that input number.

Here is my REST Controller currently (taking no inputs, just streaming the raw API data):
(Can I create other Controllers for other functions I perform on the stream? Or can the main REST Controller handle what I need if I just add some criteria to it??)

```<code>
@RestController
public class Controller {

    @GetMapping(path = "/countries", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<Countries> countries(){
        return WebClient.create("https://api.sampleapis.com/countries/countries")
                .get()
                .retrieve()
                .bodyToFlux(Countries.class)
                .delayElements(Duration.ofSeconds(2));

    }
}

</code>```

And here is my View Controller

```<code>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ViewController {

    @GetMapping("/")
    String index(){
        return "index";

    }

}

</code>```

Here is what I'm doing on the index.HTML

```<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>abbreviation</h1>
<h1 id = "abbreviation"></h1>

<h1>capital</h1>
<h1 id = "capital"></h1>

<h1>currency</h1>
<h1 id = "currency"></h1>

<h1>name</h1>
<h1 id = "name"></h1>

<h1>phone</h1>
<h1 id = "phone"></h1>

<h1>population</h1>
<h1 id = "population"></h1>

<h1>mediaflag</h1>
<h1 id = "mediaflag"></h1>

<h1>mediaemblem</h1>
<h1 id = "mediaemblem"></h1>

<h1>mediaorthographic</h1>
<h1 id = "mediaorthographic"></h1>

<script>

    var source = new EventSource("http://localhost:8080/countries");

    source.onopen = function(){
        console.log("connection opened")
    }

    source.onerror = function(error){
        console.log("error occurred", error);
    };

    source.onmessage = function(event){
        var number = event.data;
        var h1 = document.getElementById("number");
        h1.innerHTML = number;
    };

    source.onmessage = function(event){
        var parsedJSON = JSON.parse(event.data);

        document.getElementById("abbreviation").innerHTML = parsedJSON.abbreviation;
        document.getElementById("currency").innerHTML = parsedJSON.currency;
        document.getElementById("capital").innerHTML  = parsedJSON.capital;
        document.getElementById("name").innerHTML  = parsedJSON.name;
        document.getElementById("phone").innerHTML  = parsedJSON.phone;
        document.getElementById("population").innerHTML  = parsedJSON.population;
        document.getElementById("mediaflag").innerHTML  = parsedJSON.media.flag;
        document.getElementById("mediaemblem").innerHTML  = parsedJSON.media.emblem;
        document.getElementById("mediaorthographic").innerHTML = parsedJSON.media.orthographic;
    }

</script>

</body>
</html>

</code>```

And here is how I've modeled the data

```<code>
public class Countries {

    private String abbreviation;

    private String capital;

    private String currency;

    private String name;

    private String phone;

    private int population;

    private Media media;

    public Countries(){

    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public Media getMedia() {
        return media;
    }

    public void setMedia(Media media) {
        this.media = media;
    }
}

</code>```

l

```<code>
public class Media {

    private String flag;

    private String emblem;

    private String orthographic;

    public Media(){

    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getEmblem() {
        return emblem;
    }

    public void setEmblem(String emblem) {
        this.emblem = emblem;
    }

    public String getOrthographic() {
        return orthographic;
    }

    public void setOrthographic(String orthographic) {
        this.orthographic = orthographic;
    }
}

</code>```

As an aside, I'm not sure if this is correct, but I created another controller which takes an input int value and returns the countries whose populations exceed this value. If I put a value /populations/intVALUE into my web browser it successfully returns those objects - I'm just not sure how to access this data in normal HTML! Am I doing it right here? Regardless, my main question is regarding filtering the stream data based on my inputs.

Here is that code snippet:

```<code>
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.example.assignmentreactivesystemsv2.models.Countries;
import reactor.core.publisher.Flux;

@RestController
public class Test {

    @GetMapping(path = "/population/{x}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<Countries> countries(@PathVariable int x){
        return WebClient.create("https://api.sampleapis.com/countries/countries")
                .get()
                .retrieve()
                .bodyToFlux(Countries.class)
                .filter(s -> (s.getPopulation()>x));

    }
}

</code>```

Thanks very much in advance.

Body:
I am trying to stream data from an API (using a sample API from sampleapis.com) using a given JSON API. Bear with me, I'm new to this.

I have successfully modeled the data from the countries API (found here: https://sampleapis.com/api-list/countries), and I have managed to create a simple script to stream this unfiltered data. I want to be able to do  a form on the index page which allows me to specify some criteria by which to filter/search this data. For example, ordering countries by population, or inputting a value x into a form and returns the countries/country data for whichever countries exceed that input number.

Here is my REST Controller currently (taking no inputs, just streaming the raw API data):
(Can I create other Controllers for other functions I perform on the stream? Or can the main REST Controller handle what I need if I just add some criteria to it??)

@RestController
public class Controller {

    @GetMapping(path = "/countries", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<Countries> countries(){
        return WebClient.create("https://api.sampleapis.com/countries/countries")
                .get()
                .retrieve()
                .bodyToFlux(Countries.class)
                .delayElements(Duration.ofSeconds(2));

    }
}

And here is my View Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ViewController {

    @GetMapping("/")
    String index(){
        return "index";

    }

}

Here is what I'm doing on the index.HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

abbreviation

capital

currency

name

phone

population

mediaflag

mediaemblem

mediaorthographic

And here is how I've modeled the data

public class Countries {

    private String abbreviation;

    private String capital;

    private String currency;

    private String name;

    private String phone;

    private int population;

    private Media media;

    public Countries(){

    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public Media getMedia() {
        return media;
    }

    public void setMedia(Media media) {
        this.media = media;
    }
}

l

public class Media {

    private String flag;

    private String emblem;

    private String orthographic;

    public Media(){

    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public String getEmblem() {
        return emblem;
    }

    public void setEmblem(String emblem) {
        this.emblem = emblem;
    }

    public String getOrthographic() {
        return orthographic;
    }

    public void setOrthographic(String orthographic) {
        this.orthographic = orthographic;
    }
}

As an aside, I'm not sure if this is correct, but I created another controller which takes an input int value and returns the countries whose populations exceed this value. If I put a value /populations/intVALUE into my web browser it successfully returns those objects - I'm just not sure how to access this data in normal HTML! Am I doing it right here? Regardless, my main question is regarding filtering the stream data based on my inputs.

Here is that code snippet:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import com.example.assignmentreactivesystemsv2.models.Countries;
import reactor.core.publisher.Flux;

@RestController
public class Test {

    @GetMapping(path = "/population/{x}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    Flux<Countries> countries(@PathVariable int x){
        return WebClient.create("https://api.sampleapis.com/countries/countries")
                .get()
                .retrieve()
                .bodyToFlux(Countries.class)
                .filter(s -> (s.getPopulation()>x));

    }
}

Thanks very much in advance.


问:
Quotation marks in secondary fonts CSS
Hi I am doing styles for my website but I'd like to know what's the best pracice for the font-family property in CSS:

Should I use quotation marks for the font's names?

```<code>font-family: Sora-Bold, sans-serif;
</code>```

or

```<code>font-family: 'Sora-Bold', 'sans-serif';
</code>```

Thanks

The first font is one downloaded from Google Fonts while the second is a secondary font specific to the Operating System.

Title: Quotation marks in secondary fonts CSS

Body:
Hi I am doing styles for my website but I'd like to know what's the best pracice for the font-family property in CSS:

Should I use quotation marks for the font's names?

font-family: Sora-Bold, sans-serif;

or

font-family: 'Sora-Bold', 'sans-serif';

Thanks

The first font is one downloaded from Google Fonts while the second is a secondary font specific to the Operating System.


问:
failed to import pywin32 (even if it already installed) while starting supervisord in windows nanoserver container
I am trying to bring two process up in a windows Nanoserver container using supervisord (pip install supervisor-win )

Everything is setup in supervisord.conf, while starting it I am facing below issue,

```<code>C:\data>supervisord -n
C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\options.py:480: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (inc
luding its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  self.warnings.warn(
Traceback (most recent call last):
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 220, in _disable_inheritance_filehandler
    import win32api
 oduleNotFoundError: No module named 'win32api'
D
 uring handling of the above exception, another exception occurred:
T
 raceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\python-3.11.1-embed-amd64\Scripts\supervisord.exe\__main__.py", line 7, in <module>
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 403, in main
    go(options)
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 415, in go
    d.main()
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 77, in main
    self.options.make_logger()
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\options.py", line 1221, in make_logger
    loggers.handle_file(
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 444, in handle_file
    handler = RotatingFileHandler(filename, 'a', maxbytes, backups)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 211, in __init__
    self._disable_inheritance_filehandler()  # fix file used by others process
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 223, in _disable_inheritance_filehandler
    raise ImportWarning("log rotation requires the installation of the \"pywin32\" library.\n"
ImportWarning: log rotation requires the installation of the "pywin32" library.
Download and install from https://github.com/mhammond/pywin32/releases

C:\data>
</code>```

pywin32 module is already installed (tried reinstall with whl and pip anyway, that did not help)

```<code>C:\data>python -m pip show pywin32
Name: pywin32
Version: 305
Summary: Python for Window Extensions
Home-page: https://github.com/mhammond/pywin32
Author: Mark Hammond (et al)
Author-email: mhammond@skippinet.com.au
License: PSF
Location: C:\python-3.11.1-embed-amd64\Lib\site-packages
Requires:
Required-by: pypiwin32, supervisor-win

C:\data>
</code>```

What could be the issue here? I see less dll files (around 400 only) in C:\Windows\System32 compared to servercore/server image (This is working fine with windows servercore image.)

Body:
I am trying to bring two process up in a windows Nanoserver container using supervisord (pip install supervisor-win )

Everything is setup in supervisord.conf, while starting it I am facing below issue,

C:\data>supervisord -n
C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\options.py:480: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (inc
luding its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  self.warnings.warn(
Traceback (most recent call last):
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 220, in _disable_inheritance_filehandler
    import win32api
 oduleNotFoundError: No module named 'win32api'
D
 uring handling of the above exception, another exception occurred:
T
 raceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\python-3.11.1-embed-amd64\Scripts\supervisord.exe\__main__.py", line 7, in <module>
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 403, in main
    go(options)
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 415, in go
    d.main()
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\supervisord.py", line 77, in main
    self.options.make_logger()
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\options.py", line 1221, in make_logger
    loggers.handle_file(
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 444, in handle_file
    handler = RotatingFileHandler(filename, 'a', maxbytes, backups)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 211, in __init__
    self._disable_inheritance_filehandler()  # fix file used by others process
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\python-3.11.1-embed-amd64\Lib\site-packages\supervisor\loggers.py", line 223, in _disable_inheritance_filehandler
    raise ImportWarning("log rotation requires the installation of the \"pywin32\" library.\n"
ImportWarning: log rotation requires the installation of the "pywin32" library.
Download and install from https://github.com/mhammond/pywin32/releases

C:\data>

pywin32 module is already installed (tried reinstall with whl and pip anyway, that did not help)

C:\data>python -m pip show pywin32
Name: pywin32
Version: 305
Summary: Python for Window Extensions
Home-page: https://github.com/mhammond/pywin32
Author: Mark Hammond (et al)
Author-email: mhammond@skippinet.com.au
License: PSF
Location: C:\python-3.11.1-embed-amd64\Lib\site-packages
Requires:
Required-by: pypiwin32, supervisor-win

C:\data>

What could be the issue here? I see less dll files (around 400 only) in C:\Windows\System32 compared to servercore/server image (This is working fine with windows servercore image.)


问:
Getting error with Toaster form using cypress end 2 end
I am new in the use of cypress, which makes me face concern.

I would like to automate actions in order to test some Progressive Web App (PWA) and so I have recorded actions using the cypress extension of google chrome and when I create specs in cypress locally in order to reproduce the captures, I get errors especially when I am facing toasters.

```<code>cy.get('.h-full > #app > .layout--full > div > .hover\\3Aopacity-90').click()

cy.get('#app > .layout > .my-10 > .list-item:nth-child(3) > .text').click()

**cy.get('.h-full > #app > .pt-4 > .transform > .svg-inline--fa').click()**

cy.wait(15000)

cy.get('.form > .flex > div > .mt-6 > #mark').click()

cy.get('.form > .flex > div > .mt-6 > #mark').select('other')
</code>```

The toaster pops up and then I get this error.

I even added a wait but without success

Body:
I am new in the use of cypress, which makes me face concern.

I would like to automate actions in order to test some Progressive Web App (PWA) and so I have recorded actions using the cypress extension of google chrome and when I create specs in cypress locally in order to reproduce the captures, I get errors especially when I am facing toasters.

cy.get('.h-full > #app > .layout--full > div > .hover\\3Aopacity-90').click()

cy.get('#app > .layout > .my-10 > .list-item:nth-child(3) > .text').click()

**cy.get('.h-full > #app > .pt-4 > .transform > .svg-inline--fa').click()**

cy.wait(15000)

cy.get('.form > .flex > div > .mt-6 > #mark').click()

cy.get('.form > .flex > div > .mt-6 > #mark').select('other')

The toaster pops up and then I get this error.

I even added a wait but without success


问:
Javascript date comparison with AND not working but works separately
I have some dates to compare. I want to check if dateA is within range of dateB and dateC.

However, I can't get results when building logic. Separately they compare fine but when using AND I get nothing:

```<code>if(dateA >= dateB){
   // true
}

if(dateA < dateC){
   // true
}

if(dateA >= dateB && dateA < dateC){
   // doesn't reach
}
</code>```

also tried

```<code>console.log(dateA >= dateB); // true
console.log(dateA < dateC): // true
console.log(dateA >= dateB && dateA < dateC) // Nothing happens
</code>```

When I console log the dates when comparing they are identical. The typeof is object since they are Date.

Am I missing something here? Works in the browser console but when adding it to my reactjs code, nothing.

Body:
I have some dates to compare. I want to check if dateA is within range of dateB and dateC.

However, I can't get results when building logic. Separately they compare fine but when using AND I get nothing:

if(dateA >= dateB){
   // true
}

if(dateA < dateC){
   // true
}

if(dateA >= dateB && dateA < dateC){
   // doesn't reach
}

also tried

console.log(dateA >= dateB); // true
console.log(dateA < dateC): // true
console.log(dateA >= dateB && dateA < dateC) // Nothing happens

When I console log the dates when comparing they are identical. The typeof is object since they are Date.

Am I missing something here? Works in the browser console but when adding it to my reactjs code, nothing.


问:
some() method javascript - get access to parameter
```<code>if(highScores.some(s => s.name === score.name) {
        //I need access to s here
}
</code>```

how can I get access to 's' inside the brackets?

Body:
if(highScores.some(s => s.name === score.name) {
        //I need access to s here
}

how can I get access to 's' inside the brackets?


问:
Higher or Lower guessing game structuring problem, i had to look up the solution but it still makes no sense to me
im doing the 100 days of Python by Angela Yu and i just finished off day 14 today, the higher or lower follower count guessing game... I tried doing it all myself but i ended up getting lost when i needed to recycle the previous winning answer with the 1st option in the second round.. I Tried many things but none of them worked... so i looked at the answer and this makes absolutely no sense to me at all.

```<code>def game():
  print(logo)
  score = 0
  game_should_continue = True
  account_a = get_random_account()
  account_b = get_random_account()

  while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

    while account_a == account_b:
      account_b = get_random_account()

    print(f"Compare A: {format_data(account_a)}.")
    print(vs)
    print(f"Against B: {format_data(account_b)}.")

    guess = input("Who has more followers? Type 'A' or 'B': ").lower()
    a_follower_count = account_a["follower_count"]
    b_follower_count = account_b["follower_count"]
    is_correct = check_answer(guess, a_follower_count, b_follower_count)

    clear()
    print(logo)
    if is_correct:
      score += 1
      print(f"You're right! Current score: {score}.")
    else:
      game_should_continue = False
      print(f"Sorry, that's wrong. Final score: {score}")
</code>```

The get random account function fetches an dictionary from a list containing name follower count etc..
The function is ran twice to provide 2 variable entries A and B, these 2 are then printed in console and the input you enter gives back a result, i did all this myself quite successfully... Where i am really not understanding the logic is; once you get it right and the game reruns, how does

```<code>while game_should_continue:
    account_a = account_b
    account_b = get_random_account()
</code>```

account_a = account_b "Fetch" the value of the previous account_b ? surely it should just rerun the get_random_account() by doing that?

The reason i'm going through all this trouble to ask this after finishing is because i was convinced it could be done by inserting some return statements if game was won and simply reusing them as a parameter in the game() function.. but i didn't manage to get this to work.... Is it even possible?

Body:
im doing the 100 days of Python by Angela Yu and i just finished off day 14 today, the higher or lower follower count guessing game... I tried doing it all myself but i ended up getting lost when i needed to recycle the previous winning answer with the 1st option in the second round.. I Tried many things but none of them worked... so i looked at the answer and this makes absolutely no sense to me at all.

def game():
  print(logo)
  score = 0
  game_should_continue = True
  account_a = get_random_account()
  account_b = get_random_account()

  while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

    while account_a == account_b:
      account_b = get_random_account()

    print(f"Compare A: {format_data(account_a)}.")
    print(vs)
    print(f"Against B: {format_data(account_b)}.")

    guess = input("Who has more followers? Type 'A' or 'B': ").lower()
    a_follower_count = account_a["follower_count"]
    b_follower_count = account_b["follower_count"]
    is_correct = check_answer(guess, a_follower_count, b_follower_count)

    clear()
    print(logo)
    if is_correct:
      score += 1
      print(f"You're right! Current score: {score}.")
    else:
      game_should_continue = False
      print(f"Sorry, that's wrong. Final score: {score}")

The get random account function fetches an dictionary from a list containing name follower count etc..
The function is ran twice to provide 2 variable entries A and B, these 2 are then printed in console and the input you enter gives back a result, i did all this myself quite successfully... Where i am really not understanding the logic is; once you get it right and the game reruns, how does

while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

account_a = account_b "Fetch" the value of the previous account_b ? surely it should just rerun the get_random_account() by doing that?

The reason i'm going through all this trouble to ask this after finishing is because i was convinced it could be done by inserting some return statements if game was won and simply reusing them as a parameter in the game() function.. but i didn't manage to get this to work.... Is it even possible?


问:
Run script based on specific link clicked using Swup.js
I'm using video backgrounds throughout an app/kiosk we are building and trying to get specific scripts to run based on the target element that was clicked. Depending on the item clicked, videos are displayed and act as a transition between pages. Each page has a looping video as the background. Regardless of those details I'm having trouble understanding the above thread on how to have scripts fire using the swup.on(clickLink) event and using delegateTarget.

I currently have this working just to test out the basics:

```<code>function videoSwaps() {
   $('.video-02').addClass('visible-video');
   $('#video-player-02')[0].play();
   console.log("Video Replaced");
}

swup.on('clickLink', videoSwaps);
</code>```

Now though I'm looking to have different video swaps happen depending on which link/button a user clicks.

Approaching it this way breaks the swup transition:

```<code>$('.btn-video-02').click(function(){
    $('.video-02').addClass('visible-video');
    $('#video-player-02')[0].play();
    console.log("Video Replaced");
      }
 });
</code>```

Body:
I'm using video backgrounds throughout an app/kiosk we are building and trying to get specific scripts to run based on the target element that was clicked. Depending on the item clicked, videos are displayed and act as a transition between pages. Each page has a looping video as the background. Regardless of those details I'm having trouble understanding the above thread on how to have scripts fire using the swup.on(clickLink) event and using delegateTarget.

I currently have this working just to test out the basics:

function videoSwaps() {
   $('.video-02').addClass('visible-video');
   $('#video-player-02')[0].play();
   console.log("Video Replaced");
}

swup.on('clickLink', videoSwaps);

Now though I'm looking to have different video swaps happen depending on which link/button a user clicks.

Approaching it this way breaks the swup transition:

$('.btn-video-02').click(function(){
    $('.video-02').addClass('visible-video');
    $('#video-player-02')[0].play();
    console.log("Video Replaced");
      }
 });


问:
Figma: Can't draw a straight line using Pen and pencil tool what to do now
When I'm trying to draw a line it always shows me to BEND the line. How to draw a straight line in FIGMA using PEN Tool ?

I was expecting the correct answer


问:
Mapster map the derived class
I am Changing the AutoMapper to Mapster and i am new to mapster.

I have two classes like below

```<code>public class PayrollLineItems
{
   public int PayrollLineItemID{get;set;}
   public datetime PlannedStartDate {get;set;}
   public datetime PlannedEndDate {get;set;}
   public datetime ActualStartDate {get;set;}
   public datetime ActualEndDate {get;set;}
}

public class PayableLineItems
{
   public int PayrollLineItemID {get;set;}
   public TimePeriod PlannedTimePeriod {get;set;}
   public TimePeriod ActualTimePeriod {get;set;}
}

public class TimePeriod
{
    private DateTime _Start;
    private DateTime _End;
    private TimeSpan _ActualDuration;

   public TimePeriod(DateTime start, DateTime end)
   {
        this._Start = start;
        this._End = end;
        this._ActualDuration = (this._End-this._Start);
   }
}
</code>```

Below is the AutoMapper code to map the PlannedTimePeriod property of
PayrollLineItems and PayableLineItems.

```<code>CreateMap<PayrollLineitems, PayableLineItems>()
.ForMember(x => x.PlannedTimePeriod,
                            option => option.MapFrom<TimePeriod>(
                                      (src, dest) => new TimePeriod(src.PlannedStartTime.HasValue ? src.PlannedStartTime.Value : DateTime.MinValue,
                                                                    src.PlannedEndTime.HasValue ? src.PlannedEndTime.Value : DateTime.MinValue))
                                     )
</code>```

I am using the below code in Mapster to map the PlannedTimePeriod property

```<code>config
            .NewConfig<PayrollLineitems, PayableLineItems>()
      .Map(x => x.PlannedTimePeriod, dest => new TimePeriod(dest.PlannedStartTime.HasValue ? dest.PlannedStartTime.Value : DateTime.MinValue,
                            dest.PlannedEndTime.HasValue ? dest.PlannedEndTime.Value : DateTime.MinValue))
</code>```

I am getting the "No default constructor for type 'TimePeriod', please use 'ConstructUsing' or 'MapWith'" error with MapSter.

Can anyone please help me with the above issue.

Thanks in advance for helping.

Title: Mapster map the derived class

Body:
I am Changing the AutoMapper to Mapster and i am new to mapster.

I have two classes like below

public class PayrollLineItems
{
   public int PayrollLineItemID{get;set;}
   public datetime PlannedStartDate {get;set;}
   public datetime PlannedEndDate {get;set;}
   public datetime ActualStartDate {get;set;}
   public datetime ActualEndDate {get;set;}
}

public class PayableLineItems
{
   public int PayrollLineItemID {get;set;}
   public TimePeriod PlannedTimePeriod {get;set;}
   public TimePeriod ActualTimePeriod {get;set;}
}

public class TimePeriod
{
    private DateTime _Start;
    private DateTime _End;
    private TimeSpan _ActualDuration;

   public TimePeriod(DateTime start, DateTime end)
   {
        this._Start = start;
        this._End = end;
        this._ActualDuration = (this._End-this._Start);
   }
}

Below is the AutoMapper code to map the PlannedTimePeriod property of
PayrollLineItems and PayableLineItems.

CreateMap<PayrollLineitems, PayableLineItems>()
.ForMember(x => x.PlannedTimePeriod,
                            option => option.MapFrom<TimePeriod>(
                                      (src, dest) => new TimePeriod(src.PlannedStartTime.HasValue ? src.PlannedStartTime.Value : DateTime.MinValue,
                                                                    src.PlannedEndTime.HasValue ? src.PlannedEndTime.Value : DateTime.MinValue))
                                     )

I am using the below code in Mapster to map the PlannedTimePeriod property

config
            .NewConfig<PayrollLineitems, PayableLineItems>()
      .Map(x => x.PlannedTimePeriod, dest => new TimePeriod(dest.PlannedStartTime.HasValue ? dest.PlannedStartTime.Value : DateTime.MinValue,
                            dest.PlannedEndTime.HasValue ? dest.PlannedEndTime.Value : DateTime.MinValue))

I am getting the "No default constructor for type 'TimePeriod', please use 'ConstructUsing' or 'MapWith'" error with MapSter.

Can anyone please help me with the above issue.

Thanks in advance for helping.


问:
Can't refresh Live Preview on VS Code
I'm using preview my project using the "Go Live" button at the bottom right of VS Code. However, it doesn't refresh the page after I click refresh on the browser page of the preview. Does anyone have a better way to preview your work while working on VS Code?</p>

Title: Can't refresh Live Preview on VS Code


问:
Generator takes two values together instead of one by one
I have a function that takes a promise and returns a generator function,
and a function that initializes the generator, that function returns a function to use that takes argument and pass it to the generator.
then the generator resolve the promise and returns the resolved value.
So when I try to use it asynchronous (for example in the browser console) it works but when I execute 2 at the same time and the second value comes out as null. the generator takes them together instead of one by one.

const createWrapper = promise => {
  return async function*() {
    while (true) {
      const value = yield null // to get the parameter
      try {
        const results = await promise(value)
        yield results
      } catch (error) {
        yield error
      }
    }
  }
}

const generator = promise => {
  const wrapper = createWrapper(promise)() // initializing the generator
  wrapper.next() // because it starts with null

  const next = async(value) => {
    const results = await wrapper.next(value) // returns the resolved value
    await wrapper.next() // because it starts with null
    return results
  }

  return {
    next
  }
}

const testPromise = (value) => {
  return new Promise((resolve, reject) => {
    resolve(value)
  })
}

const test = generator(testPromise)

test.next('a').then(console.log) // outputs 'a'
test.next('b').then(console.log) // outputs null
test.next('c').then(console.log) // outputs 'c'```

So it does works when I execute the test.next asynchronies but when I execute them together (like in the code above) they come to the generator together instead of one by one acts weird with the yield null and the second test.next comes null

I tried to see if the results are null so I call next again, but it didn’t work
And I console logged in the generator and saw it comes together
I expected to see it prints from the generator then from below like that 3 times
but it printed from the generator 3 times then from below 3 times
I also tried to check if the resolved value is null then to call next() again but it didn't work too

Body:
I have a function that takes a promise and returns a generator function,
and a function that initializes the generator, that function returns a function to use that takes argument and pass it to the generator.
then the generator resolve the promise and returns the resolved value.
So when I try to use it asynchronous (for example in the browser console) it works but when I execute 2 at the same time and the second value comes out as null. the generator takes them together instead of one by one.

const createWrapper = promise => {
  return async function*() {
    while (true) {
      const value = yield null // to get the parameter
      try {
        const results = await promise(value)
        yield results
      } catch (error) {
        yield error
      }
    }
  }
}

const generator = promise => {
  const wrapper = createWrapper(promise)() // initializing the generator
  wrapper.next() // because it starts with null

  const next = async(value) => {
    const results = await wrapper.next(value) // returns the resolved value
    await wrapper.next() // because it starts with null
    return results
  }

  return {
    next
  }
}

const testPromise = (value) => {
  return new Promise((resolve, reject) => {
    resolve(value)
  })
}

const test = generator(testPromise)

test.next('a').then(console.log) // outputs 'a'
test.next('b').then(console.log) // outputs null
test.next('c').then(console.log) // outputs 'c'

So it does works when I execute the test.next asynchronies but when I execute them together (like in the code above) they come to the generator together instead of one by one acts weird with the yield null and the second test.next comes null

I tried to see if the results are null so I call next again, but it didn’t work
And I console logged in the generator and saw it comes together
I expected to see it prints from the generator then from below like that 3 times
but it printed from the generator 3 times then from below 3 times
I also tried to check if the resolved value is null then to call next() again but it didn't work too


问:
Some remote image is not showing in react native iOS but showing in android
Some remote image is not showing in react native iOS. But the same image is showing in android.

This is not happening for all images.

Not showing: https://d1ldvf68ux039x.cloudfront.net/thumbs/frames/audio/2211/71371/122x92_q95.jpg

Showing: https://d1ldvf68ux039x.cloudfront.net/thumbs/frames/audio/2211/71249/122x92_q95.jpg

<Image
  resizeMode={'contain'}
  style={{width: 140, height: 140, borderRadius: 5}}
  source={{uri: "https://d1ldvf68ux039x.cloudfront.net/thumbs/frames/audio/2211/71371/122x92_q95.jpg"}}
/>
```


问:
React.js upload file and manipulate the file without sending it to the server?
I have written a front end React.js and want to upload a csv file and then used another program to do the analysis of the csv file and the application needs to remember the path of the file. Is there a way to do so? I browsed on the internet, someone suggested use base64 which I have no idea what it is.

Thanks,
Jo


问:
Can we use SignalR in .NET Rest API project?
I have minimal API projects in .NET core 7. The frontend project is separate and created in Vue JS. I need to use SignalR for the notification module, but I can't figure out if this is really possible?
in.NET, all I have is REST APIs for my project, I created an API for SingleR, and it's being called from Vue JS, but the message is not being delivered to the client. Connect ID is being generated. Do I need to create some background services etc. in my understanding, once REST API is being called, it can't be connected forever for WebSocket purpose.</p>


问:
Microsoft Access || Join Query to return only one record
Im trying to join two tables together using Microsoft Access design view (still a beginner) where in the first table I have only unique date but in the second I have multiple records with the same reference.

So, when I try to join the two tables together I get all the records in table 2 (duplicates) however, I only need only to return one record (highest value for example)


问:
launching Error of Jupyter notebook and spyder notebook in Anaconda Navigator
After installing Anaconda Navigator I'm facing this kind of error. I completely two time uninstall and install it again but having same problem

what to do next or any other packages is required to install or not?

I'm expecting my jupyter notebook must be open from here. not from anaconda command prompt.


问:
Can i write a smart-contract in Java on hyperledger-grid splinter
Below is my understanding of the Hyperledger-Grid and a few of its related components.

The grid can use any one of the backends either Splinter or Sawtooth.

In the case of Grid on Splinter; Splinter, in turn, is built on a sawtooth-saber (implements an on-chain smart contract that is executed in a WebAssembly virtual machine.)
And sawtooth supports various programming language SDK like

sawtooth-sdk-java

sawtooth-sdk-go

sawtooth-sdk-python

sawtooth-sdk-rust

I have also seen examples of Grid-Product, Pike,  which is written in Rust.

Does this mean I can write an on-chain smart contract in like say java, and deploy that on a Splinter network/circuit?

can I write a similar Grid-Product (smart-contract) in Java and deploy that in place of Grid-Product (which is now in Rust)

Can I replace the Pike as the RBAC framework with another implementation written in Java on a splinter.?

Or does question 3 not even worth it doing on splinter ( or does NOT make sense), but instead I use sawtooth directly as the backend instead of Splinter?

if I can so write in Java, how do I compile into Wasm-compatible scar/jar/or-some-compatible-packaging ? Is there a reference implementation or working example that I can read?


问:
Calculate how long a process took, taking into account opening hours
I have two tables. An opening hours table that says for each seller and store, which are the opening and closing times for each day of the week. The second table is the operation one which has all information about the processes.

What I need is to calculate how many seconds each process took considering only the hours when the store was opened.

I tried to solve that with case when. I solved the problem when the process take less than 2 days. But I don't know how to handle it when it takes more days. The other problem I had with this code is that case when takes a lot of time to process. Can anybody help me with these issues?

Opening hours table:

sellerid
sellerstoreid
day
dayweek
opening
closing
next_day
opening_next_day
days_to_next

123
abc
1
monday
09:00:00
17:00:00
2
09:00:00
1

123
abc
2
tuesday
09:00:00
17:00:00
4
09:00:00
2

123
abc
4
thursday
09:00:00
17:00:00
5
09:30:00
1

123
abc
5
friday
09:30:00
17:00:00
1
09:00:00
3

Where:

sellerid + sellerstoreid + day works as a primary key;

dayweek translates day from number to name;

opening and closing are the opening and closing time for that day;

opening_next_day shows the opening time o the next available date for that store and seller;

days_to_next informes in how many days will the store reopen

Process table:

delivery_id
sellerid
sellerstoreid
process
end_time

a1
123
abc
p1
05/12/2022 16:00:00.000

a1
123
abc
p2
06/12/2022 16:00:00.000

a1
123
abc
p3
06/12/2022 16:00:00.000

a1
123
abc
p4
08/12/2022 16:00:00.000

a1
123
abc
p5
13/12/2022 16:00:00.000

Where:

The end_time of the previous process will be the the start time of the process.

```<code>with
table_1 as (
    select
        delivery_id
        , sellerid
                , sellerstoreid
        , process
        , lag(end_time, 1) over (partition by delivery_id order by end_time) as start_time
        , extract(dow from lag(end_time, 1) over (partition by delivery_id order by end_time)) as dow_start_time
        , end_time
        , extract(dow from end_time) as dow_end_time
    from process_table
),

table_2 as (
    select
        table_1.*
        , oh_start.opening as start_opening
        , oh_start.closing as start_closing
        , oh_end .opening as end_opening
        , oh_end .closing as end_closing
    from table_1 tb1

        left join opening_hours oh_start
        on oh_start.sellerid = tb1.sellerid
        and oh_start.sellerstoreid = tb1.sellerstoreid
        and oh_start.day = dow_start_time

        left join opening_hours oh_end
        on oh_end .sellerid = tb1.sellerid
        and oh_end.sellerstoreid = tb1.sellerstoreid
        and oh_end.day = dow_end_time
)

select
    *
    , case
        when dow_start_time = dow_end_time then
            extract(epoch from
                (case
                    when end_time::time > start_opening then
                        (case
                            when end_time::time > start_closing then start_closing
                            else end_time::time
                        end)
                    else start_opening
                end
            -
                case
                    when start_time::time > start_opening then
                        (case
                            when start_time::time < start_closing then start_time::time
                            else start_closing
                        end
                        )
                    else start_opening
                end))
        when dow_start_time <> dow_end_time then
            extract(epoch from
                (start_closing
            -
                case
                    when start_time::time > start_opening then
                        (case
                            when start_time::time < start_closing then start_time::time
                            else start_closing
                        end)
                    else start_opening
                end)
            +
                (case
                    when end_time::time > end_opening then
                        (case
                            when end_time::time > end_closing then end_closing
                            else end_time::time
                        end)
                    else end_opening
                end
            -
                end_opening)

    end status_duration
from table_2
</code>```

Body:
I have two tables. An opening hours table that says for each seller and store, which are the opening and closing times for each day of the week. The second table is the operation one which has all information about the processes.

What I need is to calculate how many seconds each process took considering only the hours when the store was opened.

I tried to solve that with case when. I solved the problem when the process take less than 2 days. But I don't know how to handle it when it takes more days. The other problem I had with this code is that case when takes a lot of time to process. Can anybody help me with these issues?

Opening hours table:

sellerid
sellerstoreid
day
dayweek
opening
closing
next_day
opening_next_day
days_to_next

123
abc
1
monday
09:00:00
17:00:00
2
09:00:00
1

123
abc
2
tuesday
09:00:00
17:00:00
4
09:00:00
2

123
abc
4
thursday
09:00:00
17:00:00
5
09:30:00
1

123
abc
5
friday
09:30:00
17:00:00
1
09:00:00
3

Where:

sellerid + sellerstoreid + day works as a primary key;

dayweek translates day from number to name;

opening and closing are the opening and closing time for that day;

opening_next_day shows the opening time o the next available date for that store and seller;

days_to_next informes in how many days will the store reopen

Process table:

delivery_id
sellerid
sellerstoreid
process
end_time

a1
123
abc
p1
05/12/2022 16:00:00.000

a1
123
abc
p2
06/12/2022 16:00:00.000

a1
123
abc
p3
06/12/2022 16:00:00.000

a1
123
abc
p4
08/12/2022 16:00:00.000

a1
123
abc
p5
13/12/2022 16:00:00.000

Where:

The end_time of the previous process will be the the start time of the process.

with
table_1 as (
    select
        delivery_id
        , sellerid
                , sellerstoreid
        , process
        , lag(end_time, 1) over (partition by delivery_id order by end_time) as start_time
        , extract(dow from lag(end_time, 1) over (partition by delivery_id order by end_time)) as dow_start_time
        , end_time
        , extract(dow from end_time) as dow_end_time
    from process_table
),

table_2 as (
    select
        table_1.*
        , oh_start.opening as start_opening
        , oh_start.closing as start_closing
        , oh_end .opening as end_opening
        , oh_end .closing as end_closing
    from table_1 tb1

        left join opening_hours oh_start
        on oh_start.sellerid = tb1.sellerid
        and oh_start.sellerstoreid = tb1.sellerstoreid
        and oh_start.day = dow_start_time

        left join opening_hours oh_end
        on oh_end .sellerid = tb1.sellerid
        and oh_end.sellerstoreid = tb1.sellerstoreid
        and oh_end.day = dow_end_time
)

select
    *
    , case
        when dow_start_time = dow_end_time then
            extract(epoch from
                (case
                    when end_time::time > start_opening then
                        (case
                            when end_time::time > start_closing then start_closing
                            else end_time::time
                        end)
                    else start_opening
                end
            -
                case
                    when start_time::time > start_opening then
                        (case
                            when start_time::time < start_closing then start_time::time
                            else start_closing
                        end
                        )
                    else start_opening
                end))
        when dow_start_time <> dow_end_time then
            extract(epoch from
                (start_closing
            -
                case
                    when start_time::time > start_opening then
                        (case
                            when start_time::time < start_closing then start_time::time
                            else start_closing
                        end)
                    else start_opening
                end)
            +
                (case
                    when end_time::time > end_opening then
                        (case
                            when end_time::time > end_closing then end_closing
                            else end_time::time
                        end)
                    else end_opening
                end
            -
                end_opening)

    end status_duration
from table_2


问:
Need assistance in migrating a SOAP service to Wildlfy 26 from Wildfly 10
```<code>We have a Java SOAP service running on Wildlfy & Java 8 currently. We are migrating from Wildfly 10 to 26, java-11-openjdk-11.0.12.0.7-0.el8_4.x86_64
Running into all kinds of issues.

Below is my web.xml

<display-name>SearchWS</display-name>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
<!--    <listener><listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class></listener> -->
  <servlet>
    <servlet-name>SolrSearchWS</servlet-name>
    <servlet-class>com.solr.service.SolrSearchWS</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SolrSearchWS</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

when i try to deploy my web service, i get the following in my log file

2022-12-07 11:30:06,133 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService: org.jboss.msc.service.StartException in service jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService: Failed to start serviceorg.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1731)org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1363)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.IllegalArgumentException: UT010009: Servlet SolrSearchWS of type class com.solr.service.SolrSearchWS does not implement javax.servlet.Servletio.undertow.servlet@2.2.19.Final//io.undertow.servlet.api.ServletInfo.(ServletInfo.java:98)
org.wildfly.extension.undertow@26.1.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:749)
org.wildfly.extension.undertow@26.1.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.start(UndertowDeploymentInfoService.java:312)
org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1739)
org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1701)
... 6 more

2022-12-07 11:30:06,141 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService" => "Failed to start service
Caused by: java.lang.IllegalArgumentException: UT010009: Servlet SolrSearchWS of type class com.solr.service.SolrSearchWS does not implement javax.servlet.Servlet"}}

Any help will be greatly appreciated.
regards
preet

We have tried many different combinations of files in POM. Nothing seems to help

Body:
We have a Java SOAP service running on Wildlfy & Java 8 currently. We are migrating from Wildfly 10 to 26, java-11-openjdk-11.0.12.0.7-0.el8_4.x86_64
Running into all kinds of issues.

Below is my web.xml

<display-name>SearchWS</display-name>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>SolrSearchWS</servlet-name>
    <servlet-class>com.solr.service.SolrSearchWS</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SolrSearchWS</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

when i try to deploy my web service, i get the following in my log file

2022-12-07 11:30:06,133 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService: org.jboss.msc.service.StartException in service jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService: Failed to start serviceorg.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1731)org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1363)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.IllegalArgumentException: UT010009: Servlet SolrSearchWS of type class com.solr.service.SolrSearchWS does not implement javax.servlet.Servletio.undertow.servlet@2.2.19.Final//io.undertow.servlet.api.ServletInfo.(ServletInfo.java:98)
org.wildfly.extension.undertow@26.1.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.createServletConfig(UndertowDeploymentInfoService.java:749)
org.wildfly.extension.undertow@26.1.2.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService.start(UndertowDeploymentInfoService.java:312)
org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1739)
org.jboss.msc@1.4.13.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1701)
... 6 more

2022-12-07 11:30:06,141 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit."SearchWS-0.0.1-SNAPSHOT.war".undertow-deployment.UndertowDeploymentInfoService" => "Failed to start service
Caused by: java.lang.IllegalArgumentException: UT010009: Servlet SolrSearchWS of type class com.solr.service.SolrSearchWS does not implement javax.servlet.Servlet"}}

Any help will be greatly appreciated.
regards
preet

We have tried many different combinations of files in POM. Nothing seems to help


问:
Displaying opencv image using python flask after taking input from user and use mouse events after displaying of that image
I am able to print my code on using imshow in opencv but unable to print it on ui using flask
Is there any way to do it someone please help me out..
I wanted to use mouse events after displaying it in flask api
file1.py

```<code>
from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
import numpy as np
import pandas as pd
import imutils
import cv2
import csv
from csv import writer

lval = \[\]

def rescaleFrame(frame, scale=0.48):
width = int(frame.shape\[1\] \* scale)
height = int(frame.shape\[0\] \* scale)
dimensions = (width, height)
return cv2.resize(frame, dimensions, interpolation=cv2.INTER_AREA)

def midpoint(ptA, ptB):
return ((ptA\[0\] + ptB\[0\]) \* 0.5, (ptA\[1\] + ptB\[1\]) \* 0.5)

image = cv2.imread("leg1.jpeg")
image = rescaleFrame(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

# find contours in the edge map

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# sort the contours from left-to-right and initialize the

# 'pixels per metric' calibration variable

(cnts, \_) = contours.sort_contours(cnts)
pixelsPerMetric = None

def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
box1 = \[\]
cv2.circle(orig, (x, y), 3, (0, 0, 255), -1)
points.append((x, y))
if len(points) % 2 !=0:
qx = x
qy = y
cv2.line(orig, (qx, qy), (qx + 500, qy), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx, qy + 500), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx, qy - 500), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx - 500, qy), (224, 224, 224), 1)
if len(points) % 2 == 0:
cv2.line(orig, points\[-1\], points\[-2\], (255, 0, 0), 1)
box1.append(points\[-1\])
box1.append(points\[-2\])
first, last = box1\[0\], box1\[1\]
first1, last1 = midpoint(first, last)
\# cv2.circle(orig, (int(first), int(last)), 5, (255, 0, 0), -1)
dA = dist.euclidean((first\[0\], first\[1\]), (last\[0\], last\[1\]))
dimA = round((dA / pixelsPerMetric),3)
\# copying the values from image to csv file
lval.append(dimA)
file = open('value.csv', 'a')
file.truncate(0)
writer = csv.writer(file)
writer.writerow(lval)
cv2.putText(orig, "{:.1f}in".format(dimA), (int(first\[0\] - 15), int(first\[1\] - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)
cv2.imshow('image1', orig)

# loop over the contours individually

for c in cnts:
\# if the contour is not sufficiently large, ignore it
if cv2.contourArea(c) \< 100:
continue
\# compute the rotated bounding box of the contour
orig = image.copy()
box = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
\# order the points in the contour such that they appear
\# in top-left, top-right, bottom-right, and bottom-left
\# order, then draw the outline of the rotated bounding box
box = perspective.order_points(box)
cv2.drawContours(orig, \[box.astype("int")\], -1, (0, 255, 0), 2)
\# loop over the original points and draw them
for (x, y) in box:
cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)
\# unpack the ordered bounding box, then compute the midpoint
\# between the top-left and top-right coordinates, followed by
\# the midpoint between bottom-left and bottom-right coordinates
(tl, tr, br, bl) = box
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)

    # compute the midpoint between the top-left and top-right points,
    # followed by the midpoint between the top-right and bottom-right
    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    # draw the midpoints on the image
    cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)
    # draw lines between the midpoints
    cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),
             (255, 0, 255), 2)
    cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),
             (255, 0, 255), 2)
    # compute the Euclidean distance between the midpoints
    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
    # if the pixels per metric has not been initialized, then
    # compute it as the ratio of pixels to supplied metric
    # (in this case, inches)
    if pixelsPerMetric is None:
        pixelsPerMetric = dA / 0.866 #args["width"]
        cv2.imshow('image1', orig)
        # compute the size of the object
        dimA = dA / pixelsPerMetric
        dimB = dB / pixelsPerMetric

        # draw the object sizes on the image
        cv2.putText(orig, "{:.1f}in".format(dimA),
                    (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
                    0.65, (255, 255, 255), 2)
        cv2.putText(orig, "{:.1f}in".format(dimB),
                    (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
                    0.65, (255, 255, 255), 2)
        cv2.imshow('image1',orig)
    else:
        cv2.setMouseCallback('image1', click_event)
        break

orig = image.copy()

cv2.imshow('image1', orig)
points = \[\]
cv2.waitKey(0)

</code>```

This is the python file that I want it to be displayed on the website using flask but unable to do it.
I even tried mouse events using javascript but also unable to do that dynamically as I did in python file someone please help me out with this`

Body:
I am able to print my code on using imshow in opencv but unable to print it on ui using flask
Is there any way to do it someone please help me out..
I wanted to use mouse events after displaying it in flask api
file1.py

from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
import numpy as np
import pandas as pd
import imutils
import cv2
import csv
from csv import writer

lval = \[\]

def rescaleFrame(frame, scale=0.48):
width = int(frame.shape\[1\] \* scale)
height = int(frame.shape\[0\] \* scale)
dimensions = (width, height)
return cv2.resize(frame, dimensions, interpolation=cv2.INTER_AREA)

def midpoint(ptA, ptB):
return ((ptA\[0\] + ptB\[0\]) \* 0.5, (ptA\[1\] + ptB\[1\]) \* 0.5)

image = cv2.imread("leg1.jpeg")
image = rescaleFrame(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)

edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

# find contours in the edge map

cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

# sort the contours from left-to-right and initialize the

# 'pixels per metric' calibration variable

(cnts, \_) = contours.sort_contours(cnts)
pixelsPerMetric = None

def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
box1 = \[\]
cv2.circle(orig, (x, y), 3, (0, 0, 255), -1)
points.append((x, y))
if len(points) % 2 !=0:
qx = x
qy = y
cv2.line(orig, (qx, qy), (qx + 500, qy), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx, qy + 500), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx, qy - 500), (224, 224, 224), 1)
cv2.line(orig, (qx, qy), (qx - 500, qy), (224, 224, 224), 1)
if len(points) % 2 == 0:
cv2.line(orig, points\[-1\], points\[-2\], (255, 0, 0), 1)
box1.append(points\[-1\])
box1.append(points\[-2\])
first, last = box1\[0\], box1\[1\]
first1, last1 = midpoint(first, last)
\# cv2.circle(orig, (int(first), int(last)), 5, (255, 0, 0), -1)
dA = dist.euclidean((first\[0\], first\[1\]), (last\[0\], last\[1\]))
dimA = round((dA / pixelsPerMetric),3)
\# copying the values from image to csv file
lval.append(dimA)
file = open('value.csv', 'a')
file.truncate(0)
writer = csv.writer(file)
writer.writerow(lval)
cv2.putText(orig, "{:.1f}in".format(dimA), (int(first\[0\] - 15), int(first\[1\] - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)
cv2.imshow('image1', orig)

# loop over the contours individually

for c in cnts:
\# if the contour is not sufficiently large, ignore it
if cv2.contourArea(c) \< 100:
continue
\# compute the rotated bounding box of the contour
orig = image.copy()
box = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else cv2.boxPoints(box)
box = np.array(box, dtype="int")
\# order the points in the contour such that they appear
\# in top-left, top-right, bottom-right, and bottom-left
\# order, then draw the outline of the rotated bounding box
box = perspective.order_points(box)
cv2.drawContours(orig, \[box.astype("int")\], -1, (0, 255, 0), 2)
\# loop over the original points and draw them
for (x, y) in box:
cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)
\# unpack the ordered bounding box, then compute the midpoint
\# between the top-left and top-right coordinates, followed by
\# the midpoint between bottom-left and bottom-right coordinates
(tl, tr, br, bl) = box
(tltrX, tltrY) = midpoint(tl, tr)
(blbrX, blbrY) = midpoint(bl, br)

    # compute the midpoint between the top-left and top-right points,
    # followed by the midpoint between the top-right and bottom-right
    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    # draw the midpoints on the image
    cv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)
    cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)
    # draw lines between the midpoints
    cv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),
             (255, 0, 255), 2)
    cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),
             (255, 0, 255), 2)
    # compute the Euclidean distance between the midpoints
    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
    # if the pixels per metric has not been initialized, then
    # compute it as the ratio of pixels to supplied metric
    # (in this case, inches)
    if pixelsPerMetric is None:
        pixelsPerMetric = dA / 0.866 #args["width"]
        cv2.imshow('image1', orig)
        # compute the size of the object
        dimA = dA / pixelsPerMetric
        dimB = dB / pixelsPerMetric

        # draw the object sizes on the image
        cv2.putText(orig, "{:.1f}in".format(dimA),
                    (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
                    0.65, (255, 255, 255), 2)
        cv2.putText(orig, "{:.1f}in".format(dimB),
                    (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
                    0.65, (255, 255, 255), 2)
        cv2.imshow('image1',orig)
    else:
        cv2.setMouseCallback('image1', click_event)
        break

orig = image.copy()

cv2.imshow('image1', orig)
points = \[\]
cv2.waitKey(0)

This is the python file that I want it to be displayed on the website using flask but unable to do it.
I even tried mouse events using javascript but also unable to do that dynamically as I did in python file someone please help me out with this`


问:
PHP Warning: mysqli_connect(): (HY000/1040): Too many connections
I have simple-ish PHP website. On each page of the site I start by including a link to my database connection script:

This script just contains the connection to the database:

```<code><?php
ob_start();
session_start();

// =====MYSQL SETTINGS ===== //
$db['db_host'] = "127.0.0.1";
$db['db_user'] = "mysqlusername";
$db['db_pass'] = "mysqlpassword";
$db['db_name'] = "databasename";
// =====END OF MYSQL SETTINGS ===== //

foreach($db as $key => $value){
    define(strtoupper($key), $value);
}
$dbconn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(!$dbconn){
    die("Database connection failed");
}
?>
</code>```

Back on the main web page I then include links to other files/scripts that contain elements of the page - i.e. a link to a script that shows the menu/navigation,  a link to a banner slideshow, etc. - on a busy page there might be 15 or so of these include files. A typical include looks like this (this one gets and displays some reviews from the database):

```<code><?php
//show reviews
$mainreviewstate = "Y"; //testEnabled Y or N
$query = "SELECT Id, Name, Company, Desc FROM tblreviews WHERE Enabled = ? ORDER BY RAND() LIMIT 2";
$stmt = mysqli_stmt_init($dbconn);
if(mysqli_stmt_prepare($stmt, $query)){
    mysqli_stmt_bind_param($stmt, 's', $mainreviewstate);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $Id, $Name, $Company, $Desc);
    confirmQuery($stmt);

while(mysqli_stmt_fetch($stmt)){
*'the reviews would show here'*
} //end if stmt while loop

    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);
} //end if stmt query is not empty
?>
</code>```

..so each of the includes uses the $dbconn connection made in the first include file to connect to the database and then runs the prepared statement and closes the statement at the end - "mysqli_stmt_close($stmt);"

My site is hosted on shared hosting and I was looking through the server log and there were quite a few entries for "PHP Warning: mysqli_connect(): (HY000/1040): Too many connections" and referencing the $dbconn mysqli_connect in the connection include file.

So my question is, should I be closing the connection and when should I close it? - As mentioned one page may include 10 to 15 include files each of which runs a statement and fetches data from the database. Do I need to close the connection after each "include" (after each prepared statement) or do I need to add another include to the bottom of the web page to close the connection to the database once the page has finished loading - i.e.

include to connect to the database

includes to prepared statements to fetch and display data from the database

more includes....

include to close the connection to the database

As mentioned I'm on shared hosting so I can't increase or amend the number of connections possible in MySQL.

Should I be closing my connection and if so, when and where?

Many thanks for reading.

I thought the lines:

```<code>mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);
</code>```

would affectively close the the connection but I realise now they just close the statement.

Body:
I have simple-ish PHP website. On each page of the site I start by including a link to my database connection script:

This script just contains the connection to the database:

<?php
ob_start();
session_start();

// =====MYSQL SETTINGS ===== //
$db['db_host'] = "127.0.0.1";
$db['db_user'] = "mysqlusername";
$db['db_pass'] = "mysqlpassword";
$db['db_name'] = "databasename";
// =====END OF MYSQL SETTINGS ===== //

foreach($db as $key => $value){
    define(strtoupper($key), $value);
}
$dbconn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(!$dbconn){
    die("Database connection failed");
}
?>

Back on the main web page I then include links to other files/scripts that contain elements of the page - i.e. a link to a script that shows the menu/navigation,  a link to a banner slideshow, etc. - on a busy page there might be 15 or so of these include files. A typical include looks like this (this one gets and displays some reviews from the database):

<?php
//show reviews
$mainreviewstate = "Y"; //testEnabled Y or N
$query = "SELECT Id, Name, Company, Desc FROM tblreviews WHERE Enabled = ? ORDER BY RAND() LIMIT 2";
$stmt = mysqli_stmt_init($dbconn);
if(mysqli_stmt_prepare($stmt, $query)){
    mysqli_stmt_bind_param($stmt, 's', $mainreviewstate);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $Id, $Name, $Company, $Desc);
    confirmQuery($stmt);

while(mysqli_stmt_fetch($stmt)){
*'the reviews would show here'*
} //end if stmt while loop

    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);
} //end if stmt query is not empty
?>

..so each of the includes uses the $dbconn connection made in the first include file to connect to the database and then runs the prepared statement and closes the statement at the end - "mysqli_stmt_close($stmt);"

My site is hosted on shared hosting and I was looking through the server log and there were quite a few entries for "PHP Warning: mysqli_connect(): (HY000/1040): Too many connections" and referencing the $dbconn mysqli_connect in the connection include file.

So my question is, should I be closing the connection and when should I close it? - As mentioned one page may include 10 to 15 include files each of which runs a statement and fetches data from the database. Do I need to close the connection after each "include" (after each prepared statement) or do I need to add another include to the bottom of the web page to close the connection to the database once the page has finished loading - i.e.

include to connect to the database

includes to prepared statements to fetch and display data from the database

more includes....

include to close the connection to the database

As mentioned I'm on shared hosting so I can't increase or amend the number of connections possible in MySQL.

Should I be closing my connection and if so, when and where?

Many thanks for reading.

I thought the lines:

mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);

would affectively close the the connection but I realise now they just close the statement.