问:
How to bypass HttpWebRequest detection?
Actually I'm playing around with the HtmlAgilityPack.

I've noticed that it can parse the HTML from the HtmlWebRequest.

I would like to know is there a way to bypass the "HttpWebRequest" detection?
It's because when I tried to use the HttpWebRequestto get the HTML content, it seems that the server knows me I am using "HttpWebRequest" and does not allow me to retrieve the HTML inside.

Here is my source code:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    var targetUrl = new Uri("http://www.aastocks.com/tc/ltp/rtquote.aspx?symbol=03800");
    var webReq = (HttpWebRequest)WebRequest.Create(targetUrl);
    WebResponse webRes = webReq.GetResponse();
    System.IO.Stream stream = webRes.GetResponseStream();
    System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    System.IO.StreamReader reader = new System.IO.StreamReader(stream, encode);
    HtmlDocument doc = new HtmlDocument();
    doc.Load(reader);
    foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//html"))
    {
        Label1.Text += link.InnerHtml;
    }
}
</code>```

I'm not trying to do something to violate the copyright, but just curious about this.

答:
There is no such thing as HttpWebRequest detection.

However, the page you are accessing may be not as simple: it may be loaded by several HTTP requests (iframes), or via AJAX, or require certain HTTP headers in the request.

The best thing I can advise: track the HTTP traffic between your browser and the website (for example, with Fiddler). Then track the traffic between your application (which sends the request programmatically) and the same website.

Spot the difference, and make your application behave exactly like the browser does.

Title: How to bypass HttpWebRequest detection?

Body:
Actually I'm playing around with the HtmlAgilityPack.

I've noticed that it can parse the HTML from the HtmlWebRequest.

I would like to know is there a way to bypass the "HttpWebRequest" detection?
It's because when I tried to use the HttpWebRequestto get the HTML content, it seems that the server knows me I am using "HttpWebRequest" and does not allow me to retrieve the HTML inside.

Here is my source code:

protected void Page_Load(object sender, EventArgs e)
{
    var targetUrl = new Uri("http://www.aastocks.com/tc/ltp/rtquote.aspx?symbol=03800");
    var webReq = (HttpWebRequest)WebRequest.Create(targetUrl);
    WebResponse webRes = webReq.GetResponse();
    System.IO.Stream stream = webRes.GetResponseStream();
    System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    System.IO.StreamReader reader = new System.IO.StreamReader(stream, encode);
    HtmlDocument doc = new HtmlDocument();
    doc.Load(reader);
    foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//html"))
    {
        Label1.Text += link.InnerHtml;
    }
}

I'm not trying to do something to violate the copyright, but just curious about this.


来源: stackexchange

问:
MultiIndex DataFrame: Delete non-consecutive indices and re-index
I have a MultiIndex DataFrame, that looks like this:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                3          6         6         6
                5          7         7         7
                6          8         8         8

</code>```

Now I want to drop all rows that have no direct preceding index and no direct subsequent index, e.g. row with index (1,3). The resulting DataFrame would look like this:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                5          7         7         7
                6          8         8         8
</code>```

Afterwards I want to reindex the DataFrame so that each SecondIdx with no predecessor increments the FirstIdx and the SecondIdx starts to count from 0:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
       2        0          7         7         7
                1          8         8         8
</code>```

Does pandas implement any convenient and fast way to do these 2 operations (maybe combined in one step)?

Thanks!

答:
One option, using a frame version of the index:

```<code># get index as frame for convenience
idx = df.index.to_frame()

# set groups of consecutive values
groups = idx.groupby(level='FirstIdx')['SecondIdx'].diff().gt(1).cumsum()

# determines rows to drop (i.e. groups with single values)
mask = idx.groupby([idx['FirstIdx'], groups])['FirstIdx'].transform('size').gt(1)

# compute increment of MultiIndex
increment = (~mask).groupby(level='FirstIdx').cumsum()

# update MultiIndex
idx['FirstIdx'] += increment
df.index = pd.MultiIndex.from_frame(idx)

# and drop unwanted rows
df = df.loc[mask.values]
</code>```

output:

```<code>                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
0        0                 0         0         0
         1                 1         1         1
         2                 2         2         2
         3                 3         3         3
1        0                 4         4         4
         1                 5         5         5
2        5                 7         7         7
         6                 8         8         8
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a MultiIndex DataFrame, that looks like this:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                3          6         6         6
                5          7         7         7
                6          8         8         8

Now I want to drop all rows that have no direct preceding index and no direct subsequent index, e.g. row with index (1,3). The resulting DataFrame would look like this:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
                5          7         7         7
                6          8         8         8

Afterwards I want to reindex the DataFrame so that each SecondIdx with no predecessor increments the FirstIdx and the SecondIdx starts to count from 0:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
       0        0          0         0         0
                1          1         1         1
                2          2         2         2
                3          3         3         3
       1        0          4         4         4
                1          5         5         5
       2        0          7         7         7
                1          8         8         8

Does pandas implement any convenient and fast way to do these 2 operations (maybe combined in one step)?

Thanks!

Body:
One option, using a frame version of the index:

# get index as frame for convenience
idx = df.index.to_frame()

# set groups of consecutive values
groups = idx.groupby(level='FirstIdx')['SecondIdx'].diff().gt(1).cumsum()

# determines rows to drop (i.e. groups with single values)
mask = idx.groupby([idx['FirstIdx'], groups])['FirstIdx'].transform('size').gt(1)

# compute increment of MultiIndex
increment = (~mask).groupby(level='FirstIdx').cumsum()

# update MultiIndex
idx['FirstIdx'] += increment
df.index = pd.MultiIndex.from_frame(idx)

# and drop unwanted rows
df = df.loc[mask.values]

output:

                    Column_1  Column_2  Column_3
FirstIdx SecondIdx
0        0                 0         0         0
         1                 1         1         1
         2                 2         2         2
         3                 3         3         3
1        0                 4         4         4
         1                 5         5         5
2        5                 7         7         7
         6                 8         8         8


问:
Helm Chart will install manually, will not install via Terraform
I'm having issues getting the ingress-nginx Helm Chart to install via Terraform with Minikube, yet I'm able to install it successfully via the command line. Here is my vanilla Terraform code -

```<code>provider "kubernetes" {
  host                   = "https://127.0.0.1:63191"
  client_certificate     = base64decode(var.client_certificate)
  client_key             = base64decode(var.client_key)
  cluster_ca_certificate = base64decode(var.cluster_ca_certificate)
}

provider "helm" {
  kubernetes {

  }
}

resource "helm_release" "nginx" {
  name        = "beta-nginx"
  repository  = "https://kubernetes.github.io/ingress-nginx"
  chart       = "ingress-nginx"
  namespace   = "default"
}
</code>```

I get the following logs when I apply the Terraform code above -

```<code>helm_release.nginx: Still creating... [4m31s elapsed]
2022-01-26T14:32:49.623-0600 [TRACE] dag/walk: vertex "root" is waiting for "provider[\"registry.terraform.io/hashicorp/helm\"] (close)"
2022-01-26T14:32:49.624-0600 [TRACE] dag/walk: vertex "meta.count-boundary (EachMode fixup)" is waiting for "helm_release.nginx"
2022-01-26T14:32:49.624-0600 [TRACE] dag/walk: vertex "provider[\"registry.terraform.io/hashicorp/helm\"] (close)" is waiting for "helm_release.nginx"
2022-01-26T14:32:51.299-0600 [INFO]  provider.terraform-provider-helm_v2.4.1_x5: 2022/01/26 14:32:51 [DEBUG] Service does not have load balancer ingress IP address: default/beta-nginx-ingress-nginx-controller: timestamp=2022-01-26T14:32:51.299-0600
2022-01-26T14:32:53.302-0600 [INFO]  provider.terraform-provider-helm_v2.4.1_x5: 2022/01/26 14:32:53 [DEBUG] Service does not have load balancer ingress IP address: default/beta-nginx-ingress-nginx-controller: timestamp=2022-01-26T14:32:53.302-0600
2022-01-26T14:32:54.626-0600 [TRACE] dag/walk: vertex "provider[\"registry.terraform.io/hashicorp/helm\"] (close)" is waiting for "helm_release.nginx"

Warning: Helm release "beta-nginx" was created but has a failed status. Use the `helm` command to investigate the error, correct it, then run Terraform again.

  with helm_release.nginx,
  on main.tf line 21, in resource "helm_release" "nginx":
  21: resource "helm_release" "nginx" {

Error: timed out waiting for the condition

  with helm_release.nginx,
  on main.tf line 21, in resource "helm_release" "nginx":
  21: resource "helm_release" "nginx" {
</code>```

When I try installing the Helm Chart via the command line helm install beta-nginx ingress-nginx/ingress-nginx it installs the chart no problem.

Here are a few version numbers:

Terraform
1.0.5

Minikube
1.25.1

Kubernetes
1.21.7

Helm
3.7.2

答:
This is because Terraform waits for LoadBalancer to get a public IP address, but this never happens, so the Error: timed out waiting for the condition error occurs:

```<code>$ kubectl get svc
NAME                                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
beta-nginx-ingress-nginx-controller             LoadBalancer   <PRIVATE_IP>    <pending>     80:30579/TCP,443:30909/TCP   7m32s
</code>```

You can install MetalLB to get a load-balancer implementation or create a NodePort instead of LoadBalancer. I'll briefly demonstrate the second option.

All you have to do is modify the controller.service.type value from the values.yaml file:

```<code>$ cat beta-nginx.tf
provider "helm" {
  kubernetes {
    config_path = "~/.kube/config"
  }
}

resource "helm_release" "nginx" {
  name        = "beta-nginx"
  repository  = "https://kubernetes.github.io/ingress-nginx"
  chart       = "ingress-nginx"
  namespace   = "default"
  set {
    name  = "controller.service.type"
    value = "NodePort"
  }
}

$ terraform apply
...
      + set {
          + name  = "controller.service.type"
          + value = "NodePort"
        }
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

$ kubectl get svc
NAME                                            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
beta-nginx-ingress-nginx-controller             NodePort    <PRIVATE_IP>     <none>        80:32410/TCP,443:31630/TCP   74s
</code>```

As you can see above, the NodePort service has been created instead of the LoadBalancer.

Body:
I'm having issues getting the ingress-nginx Helm Chart to install via Terraform with Minikube, yet I'm able to install it successfully via the command line. Here is my vanilla Terraform code -

provider "kubernetes" {
  host                   = "https://127.0.0.1:63191"
  client_certificate     = base64decode(var.client_certificate)
  client_key             = base64decode(var.client_key)
  cluster_ca_certificate = base64decode(var.cluster_ca_certificate)
}

provider "helm" {
  kubernetes {

  }
}

resource "helm_release" "nginx" {
  name        = "beta-nginx"
  repository  = "https://kubernetes.github.io/ingress-nginx"
  chart       = "ingress-nginx"
  namespace   = "default"
}

I get the following logs when I apply the Terraform code above -

helm_release.nginx: Still creating... [4m31s elapsed]
2022-01-26T14:32:49.623-0600 [TRACE] dag/walk: vertex "root" is waiting for "provider[\"registry.terraform.io/hashicorp/helm\"] (close)"
2022-01-26T14:32:49.624-0600 [TRACE] dag/walk: vertex "meta.count-boundary (EachMode fixup)" is waiting for "helm_release.nginx"
2022-01-26T14:32:49.624-0600 [TRACE] dag/walk: vertex "provider[\"registry.terraform.io/hashicorp/helm\"] (close)" is waiting for "helm_release.nginx"
2022-01-26T14:32:51.299-0600 [INFO]  provider.terraform-provider-helm_v2.4.1_x5: 2022/01/26 14:32:51 [DEBUG] Service does not have load balancer ingress IP address: default/beta-nginx-ingress-nginx-controller: timestamp=2022-01-26T14:32:51.299-0600
2022-01-26T14:32:53.302-0600 [INFO]  provider.terraform-provider-helm_v2.4.1_x5: 2022/01/26 14:32:53 [DEBUG] Service does not have load balancer ingress IP address: default/beta-nginx-ingress-nginx-controller: timestamp=2022-01-26T14:32:53.302-0600
2022-01-26T14:32:54.626-0600 [TRACE] dag/walk: vertex "provider[\"registry.terraform.io/hashicorp/helm\"] (close)" is waiting for "helm_release.nginx"

Warning: Helm release "beta-nginx" was created but has a failed status. Use the `helm` command to investigate the error, correct it, then run Terraform again.

  with helm_release.nginx,
  on main.tf line 21, in resource "helm_release" "nginx":
  21: resource "helm_release" "nginx" {

Error: timed out waiting for the condition

  with helm_release.nginx,
  on main.tf line 21, in resource "helm_release" "nginx":
  21: resource "helm_release" "nginx" {

When I try installing the Helm Chart via the command line helm install beta-nginx ingress-nginx/ingress-nginx it installs the chart no problem.

Here are a few version numbers:

Terraform
1.0.5

Minikube
1.25.1

Kubernetes
1.21.7

Helm
3.7.2

Body:
This is because Terraform waits for LoadBalancer to get a public IP address, but this never happens, so the Error: timed out waiting for the condition error occurs:

$ kubectl get svc
NAME                                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
beta-nginx-ingress-nginx-controller             LoadBalancer   <PRIVATE_IP>    <pending>     80:30579/TCP,443:30909/TCP   7m32s

You can install MetalLB to get a load-balancer implementation or create a NodePort instead of LoadBalancer. I'll briefly demonstrate the second option.

All you have to do is modify the controller.service.type value from the values.yaml file:

$ cat beta-nginx.tf
provider "helm" {
  kubernetes {
    config_path = "~/.kube/config"
  }
}

resource "helm_release" "nginx" {
  name        = "beta-nginx"
  repository  = "https://kubernetes.github.io/ingress-nginx"
  chart       = "ingress-nginx"
  namespace   = "default"
  set {
    name  = "controller.service.type"
    value = "NodePort"
  }
}

$ terraform apply
...
      + set {
          + name  = "controller.service.type"
          + value = "NodePort"
        }
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

$ kubectl get svc
NAME                                            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
beta-nginx-ingress-nginx-controller             NodePort    <PRIVATE_IP>     <none>        80:32410/TCP,443:31630/TCP   74s

As you can see above, the NodePort service has been created instead of the LoadBalancer.


问:
Azure key vault integration from visual studio 2022 connected services
I am trying to store stripe credentials in the Azure Key Vault.
I used the connected services tab in my Visual studio application, That seemed to work.
However when I run the application locally I get errors in the program file. I am using dotnet 6 core razor pages.

These are the errors hope you can help.

DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot

EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot

ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.

Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\Extensions\lybeojxv.4oe\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token.  'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: b90f1908-e45e-4679-aadc-64dbc7452600
Correlation ID: 62078fe0-4072-4e16-8ed7-6b5060844d88
Timestamp: 2022-02-09 07:51:08Z'.

Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot

Please run 'az login' to set up account

PowerShell is not installed.

This is the Program class
...

```<code>public class Program
 {
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var keyVaultEndpoint = new
  Uri(Environment.GetEnvironmentVariable("VaultUri"));
                config.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());

            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var loggerFactory = services.GetRequiredService<ILoggerFactory>();
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
                var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
            }
            catch (Exception ex)
            {
                var logger = loggerFactory.CreateLogger<Program>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }
        host.Run();
    }

}
</code>```

...

答:
Try these

Authenticate you Azure credential in Visual Studio

Tools - Options - Azure Service authentication - Choose an Account or Authenticate with Azure credentials

Ensure you have right access in AZ Keyvault (Get and List)

Az portal - Keyvault - Access policy - Add - Select principal and save it

Validate these settings in launchSettings.json file

Body:
I am trying to store stripe credentials in the Azure Key Vault.
I used the connected services tab in my Visual studio application, That seemed to work.
However when I run the application locally I get errors in the program file. I am using dotnet 6 core razor pages.

These are the errors hope you can help.

DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot

EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot

ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.

Process "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\Extensions\lybeojxv.4oe\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token.  'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '872cd9fa-d31f-45e0-9eab-6e460a02d1f1'(Visual Studio) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
Trace ID: b90f1908-e45e-4679-aadc-64dbc7452600
Correlation ID: 62078fe0-4072-4e16-8ed7-6b5060844d88
Timestamp: 2022-02-09 07:51:08Z'.

Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot

Please run 'az login' to set up account

PowerShell is not installed.

This is the Program class
...

public class Program
 {
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var keyVaultEndpoint = new
  Uri(Environment.GetEnvironmentVariable("VaultUri"));
                config.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());

            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var loggerFactory = services.GetRequiredService<ILoggerFactory>();
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
                var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
            }
            catch (Exception ex)
            {
                var logger = loggerFactory.CreateLogger<Program>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }
        host.Run();
    }

}

...


问:
JS push arrays to main array with key name
I have solidIcons which contains:

```<code>['book', 'apple', 'smile', 'pencil']
</code>```

and regularIcons:

```<code>['flower', 'clock', 'house', 'bird']
</code>```

I want to create the following array from the two:

```<code>{
  'solid-icons': ['book', 'apple', 'smile', 'pencil'],
  'regular-icons': ['flower', 'clock', 'house', 'bird'],
}
</code>```

The goal is to be able to use map to loop through either solid-icons or regular-icons.

I'm trying:

```<code>let allIcons = [];

allIcons["solid-icons"] = solidIcons;
allIcons["regular-icons"] = regularIcons;
</code>```

This is creating

```<code>0: [solid-icons: Array()]
1: [regular-icons: Array()]
</code>```

The issue is that O cannot simply access an array group with allIcons["solid-icons"] I have to use the index allIcons[0]. How can i create the array in such a way that i can use the solid-icons or regular-icons to access without the index.

答:
let allIcons = [] - this is array, you need let allIcons = {}  instead

let allIcons = {};

allIcons["solid-icons"] = solidIcons;
allIcons["regular-icons"] = regularIcons;
```

Body:
I have solidIcons which contains:

['book', 'apple', 'smile', 'pencil']

and regularIcons:

['flower', 'clock', 'house', 'bird']

I want to create the following array from the two:

{
  'solid-icons': ['book', 'apple', 'smile', 'pencil'],
  'regular-icons': ['flower', 'clock', 'house', 'bird'],
}

The goal is to be able to use map to loop through either solid-icons or regular-icons.

I'm trying:

let allIcons = [];

allIcons["solid-icons"] = solidIcons;
allIcons["regular-icons"] = regularIcons;

This is creating

0: [solid-icons: Array()]
1: [regular-icons: Array()]

The issue is that O cannot simply access an array group with allIcons["solid-icons"] I have to use the index allIcons[0]. How can i create the array in such a way that i can use the solid-icons or regular-icons to access without the index.


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
>>> d = {'a':0, 'b':0, 'c':0, 'd':0}
>>> s = 'cbad'
>>> for x in d:
        d[x]=s.find(x)
>>> d
    {'a': 2, 'c': 0, 'b': 1, 'd': 3}

ContentLicense: CC BY-SA 3.0


问:
Implement Infinite scroll in ag-grid Angular
I am trying to implement infinite scroll in ag-grid . I could see many examples which makes request to api and gets the next set of data . But my scenario is different.  On first api call itself I will get entire data , just that I have to show first 20 records on load , then when user scrolls and reaches the bottom of table I have to load the grid with next 20 records . Can someone tell me is it something achievable and guide me in possible .</p>

答:
If you have your entire set of data then you should be able to follow this example as that too loads all the data but only gives the data a set amount of rows at a time.

So you will need to implement the IDataSource interface a bit like this.

```<code>fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
  .then((response) => response.json())
  .then(function (data) {
    const dataSource: IDatasource = {
      rowCount: undefined, // behave as infinite scroll

      getRows: function (params: IGetRowsParams) {
        console.log('asking for ' + params.startRow + ' to ' + params.endRow);

          // take a slice of the total rows
          const rowsThisPage = data.slice(params.startRow, params.endRow);
          // if on or after the last page, work out the last row.
          let lastRow = -1;
          if (data.length <= params.endRow) {
            lastRow = data.length;
          }
          // call the success callback
          params.successCallback(rowsThisPage, lastRow);
      },
    };

    gridOptions.api!.setDatasource(dataSource);
  });
</code>```

Body:
If you have your entire set of data then you should be able to follow this example as that too loads all the data but only gives the data a set amount of rows at a time.

So you will need to implement the IDataSource interface a bit like this.

fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
  .then((response) => response.json())
  .then(function (data) {
    const dataSource: IDatasource = {
      rowCount: undefined, // behave as infinite scroll

      getRows: function (params: IGetRowsParams) {
        console.log('asking for ' + params.startRow + ' to ' + params.endRow);

          // take a slice of the total rows
          const rowsThisPage = data.slice(params.startRow, params.endRow);
          // if on or after the last page, work out the last row.
          let lastRow = -1;
          if (data.length <= params.endRow) {
            lastRow = data.length;
          }
          // call the success callback
          params.successCallback(rowsThisPage, lastRow);
      },
    };

    gridOptions.api!.setDatasource(dataSource);
  });


问:
fixed or sticky the header background image up to the specific section only
how could I fixed or sticky the header background image up to the first section only?
let's say this is the code:

```<code><header id="header-bg"> <!-- inside this id has a background cover img -->
     <!-- header content here -->
</header>

<section id="first-section">
     <!-- content here -->
</section>
</code>```

my goal is to stay/fixed or sticky the header background up to the first section when scrolling. once the first section is end, the header background is not fixed/sticky anymore.

答:
Hi I have created a sandbox for your reference.

https://codesandbox.io/s/cold-lake-hklc5?file=/index.html

.header {
  position: sticky;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <header class="header" id="header-bg">
    <!-- inside this id has a background cover img -->
    <!-- header content here -->
    Header Content Dummy
  </header>

  <section id="first-section">
    <!-- content here -->
    Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
    here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
    goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first
    content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
  </section>
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section></code>```

Body:
how could I fixed or sticky the header background image up to the first section only?
let's say this is the code:

my goal is to stay/fixed or sticky the header background up to the first section when scrolling. once the first section is end, the header background is not fixed/sticky anymore.

Body:
Hi I have created a sandbox for your reference.

https://codesandbox.io/s/cold-lake-hklc5?file=/index.html

.header {
  position: sticky;
  top: 0;
}

<section>
  <header class="header" id="header-bg">
    <!-- inside this id has a background cover img -->
    <!-- header content here -->
    Header Content Dummy
  </header>

  <section id="first-section">
    <!-- content here -->
    Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
    here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
    goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first
    content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
  </section>
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>
<section id="first-section">
  <!-- content here -->
  Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes
  here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content
  goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here Section first content goes here
</section>


问:
Return MAX(Null) as Null in postgresql
I have a scenario where the max function should work as follows in PostgreSQL:

```<code>select max(3,null) from table
</code>```

should return 3

whereas,

```<code>select max(null) from table
</code>```

should return null.

Suggestions are welcomed!

答:
max() is an aggregate that works across rows, not columns.

You are looking for greatest()

```<code>select greatest(3,null) from table
</code>```

Title: Return MAX(Null) as Null in postgresql

Body:
I have a scenario where the max function should work as follows in PostgreSQL:

select max(3,null) from table

should return 3

whereas,

select max(null) from table

should return null.

Suggestions are welcomed!

Body:
max() is an aggregate that works across rows, not columns.

You are looking for greatest()

select greatest(3,null) from table


问:
Is it possible to have points which shade out in scatter plot?
We can plot heart shape and other shape in scatter plot. But is it possible to have a plot where points in plot shades out [in circle] as shown in below image with text beside it.

Thanks for your response in advance.

答:
Yes it is possible. You'll need to add the value to the plotly.graph_objects.Scatter.text attribute. I suspect that you have a heart symbol/emoji for the text attribute, so have a list of the values you want to put in the text ordered by your preference to match the points, and append the heart symbol to it. Here's an generic example of how it can be done:

import dash
from dash import html, dcc
import pandas as pd
import numpy as np
import plotly.graph_objects as go

app = dash.Dash()

df = pd.DataFrame([
    np.random.randint(1, 5, 5),
    np.random.randint(1, 5, 5),
    ["text_1", "text_2", "text_3", "text_4", "text_5"]]
).transpose()

df.columns = ["x", "y", "text"]

def add_text_to_heart(st):
    return f"♥ {st}"

df["text"] = df["text"].apply(add_text_to_heart)

app.layout = html.Div([
    dcc.Graph(figure=(go.Figure(
    go.Scatter(
        x=df["x"],
        y=df["y"],
        mode="text",
        text=df["text"],
        textfont_size=20,
        textfont_color=np.random.choice(["red","yellow","blue"], 10)
    )
)))
])

if __name__ == "__main__":
    app.run_server()
```


问:
How can I Post-redir-get without losing form data
Let's say a user gets a page /form/

GET /form/

He then fills in the form and sends a post request

POST /form/

The server attempts to validate user input and determines input to be invalid.

Currently the history chain for the users is

GET /form/

POST /form/

Now the server redirects the user to the GET /form/ page so it can fill in the form again (with error messages).

His history looks like

GET /form/ with filled in form fields

GET /form/ without filed in form fields

How do I send the user back without the user losing the details he entered in his first form?

What techniques are there for redirecting users back to their GET /form/ page and not forcing them to re-enter their information.

Below is my express (node.js) specific server side code for this example.

The validation middleware:

```<code>validate().on("error", function _error(msg) {
    // store error message on request object
    req.flash(msg, validateUserMessage[msg]);
}).on("valid", function _valid() {
    // handle the rest of /POST/
    next();
}).on("invalid", function _invalid() {
    // redirect user back to last page, the /GET/ form
    res.redirect("back");
}).run(function _validateUsers(check, sanitize) {
    // validation logic.
});
</code>```

The routing:

```<code>// GET /form/
app.get("/form", function _signUpView(req, res) {
    // render /form/
    res.render("auth/signup", req.flash());
});

// POST /form/
// validation middleware used here.
app.post("/form", secure.validateUser, function _signUpCreate(req, res) {
    model.create(req.body, function _create() {
         // create thing in database
    });
});
</code>```

答:
DO NOT redirect on invalid input. Do it on valid input only.

On invalid input, respond to the POST request with the same form, but this time populated with the POST data that you just received.

Body:
Let's say a user gets a page /form/

GET /form/

He then fills in the form and sends a post request

POST /form/

The server attempts to validate user input and determines input to be invalid.

Currently the history chain for the users is

GET /form/

POST /form/

Now the server redirects the user to the GET /form/ page so it can fill in the form again (with error messages).

His history looks like

GET /form/ with filled in form fields

GET /form/ without filed in form fields

How do I send the user back without the user losing the details he entered in his first form?

What techniques are there for redirecting users back to their GET /form/ page and not forcing them to re-enter their information.

Below is my express (node.js) specific server side code for this example.

The validation middleware:

validate().on("error", function _error(msg) {
    // store error message on request object
    req.flash(msg, validateUserMessage[msg]);
}).on("valid", function _valid() {
    // handle the rest of /POST/
    next();
}).on("invalid", function _invalid() {
    // redirect user back to last page, the /GET/ form
    res.redirect("back");
}).run(function _validateUsers(check, sanitize) {
    // validation logic.
});

The routing:

// GET /form/
app.get("/form", function _signUpView(req, res) {
    // render /form/
    res.render("auth/signup", req.flash());
});

// POST /form/
// validation middleware used here.
app.post("/form", secure.validateUser, function _signUpCreate(req, res) {
    model.create(req.body, function _create() {
         // create thing in database
    });
});


问:
Rank for distincted rows
I have this.

ID
ITEM_ID
ORDER

10
1
1

11
1
2

12
1
3

13
4
4

15
2
5

16
2
6

17
3
7

18
3
8

And I need to select to this. Make order for distincted item_id

答:
If you just want to order by the minimum ORDER for each item_id then:

SELECT item_id,
       ROW_NUMBER() OVER (ORDER BY MIN("ORDER")) AS "ORDER"
FROM   table_name
GROUP BY item_id
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (ID, ITEM_ID, "ORDER") AS
SELECT 10, 1, 1 FROM DUAL UNION ALL
SELECT 11, 1, 2 FROM DUAL UNION ALL
SELECT 12, 1, 3 FROM DUAL UNION ALL
SELECT 13, 4, 4 FROM DUAL UNION ALL
SELECT 15, 2, 5 FROM DUAL UNION ALL
SELECT 16, 2, 6 FROM DUAL UNION ALL
SELECT 17, 3, 7 FROM DUAL UNION ALL
SELECT 18, 3, 8 FROM DUAL;
</code>```

Note: ORDER is a reserved word and cannot be used as an unquoted identifier; it would be better to use a different identifier rather than ORDER.

Outputs:

ITEM_ID
ORDER

1
1

4
2

2
3

3
4

If you want item_id to appear multiple times if there are different item_ids between occurrences then, from Oracle 12, you can use MATCH_RECOGNIZE:

SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  ORDER BY "ORDER"
  MEASURES
    FIRST(item_id) AS item_id,
    MATCH_NUMBER() AS "ORDER"
  PATTERN (same_item+)
  DEFINE same_item AS FIRST(item_id) = item_id
)
```
<p>Which for the sample data above gives the same output; however, if you add some extra rows:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO table_name (id, item_id, "ORDER")
SELECT 19, 1,  9 FROM DUAL UNION ALL
SELECT 20, 2, 10 FROM DUAL UNION ALL
SELECT 21, 2, 11 FROM DUAL UNION ALL
SELECT 22, 4, 12 FROM DUAL;
</code>```

Then the output from the MATCH_RECOGNIZE query is:

ITEM_ID
ORDER

1
1

4
2

2
3

3
4

1
5

2
6

4
7

db<>fiddle here

Title: Rank for distincted rows

Body:
If you just want to order by the minimum ORDER for each item_id then:

SELECT item_id,
       ROW_NUMBER() OVER (ORDER BY MIN("ORDER")) AS "ORDER"
FROM   table_name
GROUP BY item_id

Which, for the sample data:

CREATE TABLE table_name (ID, ITEM_ID, "ORDER") AS
SELECT 10, 1, 1 FROM DUAL UNION ALL
SELECT 11, 1, 2 FROM DUAL UNION ALL
SELECT 12, 1, 3 FROM DUAL UNION ALL
SELECT 13, 4, 4 FROM DUAL UNION ALL
SELECT 15, 2, 5 FROM DUAL UNION ALL
SELECT 16, 2, 6 FROM DUAL UNION ALL
SELECT 17, 3, 7 FROM DUAL UNION ALL
SELECT 18, 3, 8 FROM DUAL;

Note: ORDER is a reserved word and cannot be used as an unquoted identifier; it would be better to use a different identifier rather than ORDER.

Outputs:

ITEM_ID
ORDER

1
1

4
2

2
3

3
4

If you want item_id to appear multiple times if there are different item_ids between occurrences then, from Oracle 12, you can use MATCH_RECOGNIZE:

SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  ORDER BY "ORDER"
  MEASURES
    FIRST(item_id) AS item_id,
    MATCH_NUMBER() AS "ORDER"
  PATTERN (same_item+)
  DEFINE same_item AS FIRST(item_id) = item_id
)

Which for the sample data above gives the same output; however, if you add some extra rows:

INSERT INTO table_name (id, item_id, "ORDER")
SELECT 19, 1,  9 FROM DUAL UNION ALL
SELECT 20, 2, 10 FROM DUAL UNION ALL
SELECT 21, 2, 11 FROM DUAL UNION ALL
SELECT 22, 4, 12 FROM DUAL;

Then the output from the MATCH_RECOGNIZE query is:

ITEM_ID
ORDER

1
1

4
2

2
3

3
4

1
5

2
6

4
7

db<>fiddle here


答:
I think you can just use object literal:

```<code>let allIcons = {
  'solid-icons': ['book', 'apple', 'smile', 'pencil'],
  'regular-icons': ['flower', 'clock', 'house', 'bird'],
}
</code>```

You are not creating an array but object.

Title: JS push arrays to main array with key name

Body:
I think you can just use object literal:

let allIcons = {
  'solid-icons': ['book', 'apple', 'smile', 'pencil'],
  'regular-icons': ['flower', 'clock', 'house', 'bird'],
}

You are not creating an array but object.


问:
Spring data - RepositoryRestResource PUT returns 200 but does not update object
I'm using Spring's HATEOAS repo:

```<code>@RepositoryRestResource(collectionResourceRel = "equipment", path = "equipment")
interface EquipmentRepository : PagingAndSortingRepository<Equipment, Int>
</code>```

Here's my domain object:

```<code>@Entity
data class Equipment(
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    val id: Int?,
    val serialNumber: String?,
    val modelNumber: String,
    val make: String,
    val model: String,
    val year: Int,
    val purchaseDate: Date,
    val warrantyEnds: Date,
    val cost: Double
)
</code>```

I'm using cURL and Postman to create equipment and it's all good. If I use PATCH for a partial update the query updates the object - if I use the same URL and same data for PUT nothing is updated but I get a 200 response (and the old object) in postman.

How come I can PATCH http://localhost:8080/equipment/1 works but a PUT with the same data and same endpoint returns 200 but does not update the data?

No errors on the server-side on the console/logs, or any indication as to why I'm getting a 200 and no update...

I am using Kotlin, if it matters...

答: Try change val to var, i had the same problem and this should help.

Body:
I'm using Spring's HATEOAS repo:

@RepositoryRestResource(collectionResourceRel = "equipment", path = "equipment")
interface EquipmentRepository : PagingAndSortingRepository<Equipment, Int>

Here's my domain object:

@Entity
data class Equipment(
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    val id: Int?,
    val serialNumber: String?,
    val modelNumber: String,
    val make: String,
    val model: String,
    val year: Int,
    val purchaseDate: Date,
    val warrantyEnds: Date,
    val cost: Double
)

I'm using cURL and Postman to create equipment and it's all good. If I use PATCH for a partial update the query updates the object - if I use the same URL and same data for PUT nothing is updated but I get a 200 response (and the old object) in postman.

How come I can PATCH http://localhost:8080/equipment/1 works but a PUT with the same data and same endpoint returns 200 but does not update the data?

No errors on the server-side on the console/logs, or any indication as to why I'm getting a 200 and no update...

I am using Kotlin, if it matters...


问:
Error on deserializing data from an restApi response to an class object in java?
i am trying to deserialize this data from the api

```<code>          [{
             "id":1,
              "title":"Book of arts",
              "Author":"Helena"
         }]
     Response response =
   RestApiHandler.sendParametricRequest("GET",url,paramsMap,dataMap);
</code>```

How can i deserialise this to a class object in java?.

```<code>      public class PostData{
               public int id;
               public String title;
               public String author;
               public int getId() {
               return id;
              }

         public void setId(int id) {
               this.id = id;
         }
           public String getTitle() {
              return title;
            }

         public void setTitle(String title) {
               this.title = title;
         }
         public String getAuthor() {
              return author;
            }

         public void setAuthor(String author) {
               this.author = author;
         }
         }
</code>```

i have tried this ,
PostData postData = response.as(PostData.class);
System.out.println(postData.getAuthor());
Its giving me errors. Please help, Tia

答:
Can you get the json str from response object?  i feel this is a str convert to object problem

the following code use jackson

```<code>    String jsonStr = "other object json";
    ObjectMapper objectMapper = new ObjectMapper();
    TargetObject targetObject = objectMapper.readValue(jsonStr, TargetObject.class);
</code>```

Body:
i am trying to deserialize this data from the api

          [{
             "id":1,
              "title":"Book of arts",
              "Author":"Helena"
         }]
     Response response =
   RestApiHandler.sendParametricRequest("GET",url,paramsMap,dataMap);

How can i deserialise this to a class object in java?.

      public class PostData{
               public int id;
               public String title;
               public String author;
               public int getId() {
               return id;
              }

         public void setId(int id) {
               this.id = id;
         }
           public String getTitle() {
              return title;
            }

         public void setTitle(String title) {
               this.title = title;
         }
         public String getAuthor() {
              return author;
            }

         public void setAuthor(String author) {
               this.author = author;
         }
         }

i have tried this ,
PostData postData = response.as(PostData.class);
System.out.println(postData.getAuthor());
Its giving me errors. Please help, Tia

Body:
Can you get the json str from response object?  i feel this is a str convert to object problem

the following code use jackson

    String jsonStr = "other object json";
    ObjectMapper objectMapper = new ObjectMapper();
    TargetObject targetObject = objectMapper.readValue(jsonStr, TargetObject.class);


问:
Query in command must target single shard key
I have an array of document ids using which I wish to delete the documents with the given id. The document id is also the shard key of the document. So I provided the following query for model.deleteMany(query)

query:
{ doc_id: { '$in': [ 'docid1', 'docid2' ] } }

I still get the error Query in command must target single shard key.
Is it possible to overcome this without looping through the array and deleting the docs one by one?

答:
By matching any document in the collection with the _id field, you can make a query or delete command:

```<code>db.collection.deleteMany({ _id: { $exists: true }})
</code>```

During the specification of the schema model in the code, a Shard Key (Partition Key) must be specified. We may execute operations such as save, update, and delete once it is provided

```<code>const mySchema = new Schema({
    requestId: { type: String, required: true },
    data: String,
    documents: [{ docId: String, name: String, attachedBy: String }],
    updatedBy: {
        type: {
            name: { type: String, required: true },
            email: { type: String, required: true },
        }, required: true
    },
    createdDate: { type: Date, required: true },
    updatedDate: { type: Date },
}, { shardKey: { requestId: 1 } }
);
</code>```

Body:
By matching any document in the collection with the _id field, you can make a query or delete command:

db.collection.deleteMany({ _id: { $exists: true }})

During the specification of the schema model in the code, a Shard Key (Partition Key) must be specified. We may execute operations such as save, update, and delete once it is provided

const mySchema = new Schema({
    requestId: { type: String, required: true },
    data: String,
    documents: [{ docId: String, name: String, attachedBy: String }],
    updatedBy: {
        type: {
            name: { type: String, required: true },
            email: { type: String, required: true },
        }, required: true
    },
    createdDate: { type: Date, required: true },
    updatedDate: { type: Date },
}, { shardKey: { requestId: 1 } }
);


问:
Cause: buildOutput.apkData must not be null
My android application using Kotlin is throwing this exception when I try to Run 'app' in the emulator o in my cellphone. When I build my project it runs well, with no errors.

I am using:

SDK 28 (Android 9.0 (Pie))

Gradle 5.1.1

Gradle Plugin 3.5.0-alpha03

Kotlin 1.3.10

Java 1.8.0_151

OSX 10.13.2

```<code>    org.gradle.internal.exceptions.LocationAwareException: buildOutput.apkData must not be null
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:99)
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.collectFailures(DefaultExceptionAnalyser.java:65)
        at org.gradle.initialization.exception.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:39)
        at org.gradle.initialization.exception.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:29)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:194)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:141)
        ...
    Caused by: java.lang.IllegalStateException: buildOutput.apkData must not be null
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:103)
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:67)
        at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:174)
        at kotlin.sequences.SequencesKt___SequencesKt.toCollection(_Sequences.kt:691)
        at kotlin.sequences.SequencesKt___SequencesKt.toMutableList(_Sequences.kt:721)
        at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:712)
        ...
</code>```

答: enter code hereIf your using different build variants, Select the specific folder to generate signin apk file. When you are trying to generate signin apk flow, you can change the path. For me, this worked.

Body:
My android application using Kotlin is throwing this exception when I try to Run 'app' in the emulator o in my cellphone. When I build my project it runs well, with no errors.

I am using:

SDK 28 (Android 9.0 (Pie))

Gradle 5.1.1

Gradle Plugin 3.5.0-alpha03

Kotlin 1.3.10

Java 1.8.0_151

OSX 10.13.2

    org.gradle.internal.exceptions.LocationAwareException: buildOutput.apkData must not be null
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.transform(DefaultExceptionAnalyser.java:99)
        at org.gradle.initialization.exception.DefaultExceptionAnalyser.collectFailures(DefaultExceptionAnalyser.java:65)
        at org.gradle.initialization.exception.MultipleBuildFailuresExceptionAnalyser.transform(MultipleBuildFailuresExceptionAnalyser.java:39)
        at org.gradle.initialization.exception.StackTraceSanitizingExceptionAnalyser.transform(StackTraceSanitizingExceptionAnalyser.java:29)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:194)
        at org.gradle.initialization.DefaultGradleLauncher.finishBuild(DefaultGradleLauncher.java:141)
        ...
    Caused by: java.lang.IllegalStateException: buildOutput.apkData must not be null
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:103)
        at com.android.build.gradle.internal.ide.EarlySyncBuildOutput$Companion$load$2.invoke(EarlySyncBuildOutput.kt:67)
        at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:174)
        at kotlin.sequences.SequencesKt___SequencesKt.toCollection(_Sequences.kt:691)
        at kotlin.sequences.SequencesKt___SequencesKt.toMutableList(_Sequences.kt:721)
        at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:712)
        ...


问:
finding file_id of a group media message in telegram by telebot library
In my bot, I received a forwarded media group message which contains 3 different photos. Now I want to catch all these 3 photos and send them again to another chat_id. However, all values in message.photo.file_id are representing the same photo in various resolutions and when I store this file_id in a list to use it in media section of bot.send_media_group, it makes a group of the same photo.

My question is, how can I find those three picture unique file_id to store in my list and use it in media section of bot.send_media_group

my code is below:

```<code>    for i in message.photo:
                    print(i.file_id)
                    list_file_id.append(i.file_id)
                print(message)
                print(list_file_id)

    bot.send_media_group(channelData.chat_ID, media = [InputMediaPhoto(media = i) for i in list_file_id], caption= "hellow")
</code>```

答:
You're iterating over the wrong parameter, but it's what I define a false friend.

The attribute photo into the Message Telegram object represents all of the available sizes related to the picture into the message itself (documentation here).

It's a false friend because as you tried so far, you're getting the different picture sizes instead of the file_id which could be found into the other message's object attributes.

Body:
In my bot, I received a forwarded media group message which contains 3 different photos. Now I want to catch all these 3 photos and send them again to another chat_id. However, all values in message.photo.file_id are representing the same photo in various resolutions and when I store this file_id in a list to use it in media section of bot.send_media_group, it makes a group of the same photo.

My question is, how can I find those three picture unique file_id to store in my list and use it in media section of bot.send_media_group

my code is below:

    for i in message.photo:
                    print(i.file_id)
                    list_file_id.append(i.file_id)
                print(message)
                print(list_file_id)

    bot.send_media_group(channelData.chat_ID, media = [InputMediaPhoto(media = i) for i in list_file_id], caption= "hellow")


问:
How do I install camel-cxf feature for camel 3.8.0 in Apache Karaf 4.2.15?
This works:

```<code>karaf@root> feature:repo-add camel 3.7.7
karaf@root> feature:install camel camel-cxf
</code>```

This doesn't work:

```<code>karaf@root> feature:repo-add camel 3.8.0
karaf@root> feature:install camel camel-cxf
</code>```

Error message:

```<code>Error executing command: Unable to resolve root: missing requirement [root] osgi.identity;
osgi.identity=camel-cxf; type=karaf.feature; version="[3.8.0,3.8.0]";
filter:="(&(osgi.identity=camel-cxf)(type=karaf.feature)(version>=3.8.0)(version<=3.8.0))"
[caused by: Unable to resolve camel-cxf/3.8.0: missing requirement [camel-cxf/3.8.0]
osgi.identity; osgi.identity=cxf-core; type=karaf.feature; version="[3.3.0,4.0.0)"]
</code>```

Why did this stop working between these two versions, or rather how do I resolve this issue?

答:
Have you tried adding apache cxf feature-repository and installing cxf feature first?

Example:

feature:repo-add cxf <version>
feature:install cxf

feature:repo-add camel 3.8.0
feature:install camel
feature:install camel-cxf
```

Camel feature-repository has entry for apache-cxf feature-repository with version range set to 3.0.0 - 4.0.0 which might cause it to use incompatible version of apache-cxf or its feature-repository.

The missing cxf-core feature should be available in cxf-feature repository and if you install cxf feature first camel-cxf should just use the pre-installed version instead of trying to install latest version which could very well be something like 4.0.0-alpha since it's technically lower than 4.0.0.

Body:
This works:

karaf@root> feature:repo-add camel 3.7.7
karaf@root> feature:install camel camel-cxf

This doesn't work:

karaf@root> feature:repo-add camel 3.8.0
karaf@root> feature:install camel camel-cxf

Error message:

Error executing command: Unable to resolve root: missing requirement [root] osgi.identity;
osgi.identity=camel-cxf; type=karaf.feature; version="[3.8.0,3.8.0]";
filter:="(&(osgi.identity=camel-cxf)(type=karaf.feature)(version>=3.8.0)(version<=3.8.0))"
[caused by: Unable to resolve camel-cxf/3.8.0: missing requirement [camel-cxf/3.8.0]
osgi.identity; osgi.identity=cxf-core; type=karaf.feature; version="[3.3.0,4.0.0)"]

Why did this stop working between these two versions, or rather how do I resolve this issue?

Body:
Have you tried adding apache cxf feature-repository and installing cxf feature first?

Example:

feature:repo-add cxf <version>
feature:install cxf

feature:repo-add camel 3.8.0
feature:install camel
feature:install camel-cxf

Camel feature-repository has entry for apache-cxf feature-repository with version range set to 3.0.0 - 4.0.0 which might cause it to use incompatible version of apache-cxf or its feature-repository.

The missing cxf-core feature should be available in cxf-feature repository and if you install cxf feature first camel-cxf should just use the pre-installed version instead of trying to install latest version which could very well be something like 4.0.0-alpha since it's technically lower than 4.0.0.


问:
Problem decoding h264 over RTP TCP stream
I'm trying to receive RTP stream encoding h264 over TCP from my intercom Hikvision DS-KH8350-WTE1. By reverse engineering I was able to replicate how Hikvision original software Hik-Connect on iPhone and iVMS-4200 on MacOS connects and negotaties streaming. Now I'm getting the very same stream as original apps - verified through Wireshark. Now I need to "make sense" of the stream. I know it's RTP because I inspected how iVMS-4200 uses it using /usr/bin/sample on MacOS. Which yields:

```<code>  ! :               2 CStreamConvert::InputData(void*, int)  (in libOpenNetStream.dylib) + 52  [0x11ff7c7a6]
+     ! :                 2 SYSTRANS_InputData  (in libSystemTransform.dylib) + 153  [0x114f917f2]
+     ! :                   1 CRTPDemux::ProcessH264(unsigned char*, unsigned int, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 302  [0x114fa2c04]
+     ! :                   | 1 CRTPDemux::AddAVCStartCode()  (in libSystemTransform.dylib) + 47  [0x114fa40f1]
+     ! :                   1 CRTPDemux::ProcessH264(unsigned char*, unsigned int, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 476  [0x114fa2cb2]
+     ! :                     1 CRTPDemux::ProcessVideoFrame(unsigned char*, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 1339  [0x114fa29b3]
+     ! :                       1 CMPEG2PSPack::InputData(unsigned char*, unsigned int, FRAME_INFO*)  (in libSystemTransform.dylib) + 228  [0x114f961d6]
+     ! :                         1 CMPEG2PSPack::PackH264Frame(unsigned char*, unsigned int, FRAME_INFO*)  (in libSystemTransform.dylib) + 238  [0x114f972fe]
+     ! :                           1 CMPEG2PSPack::FindAVCStartCode(unsigned char*, unsigned int)  (in libSystemTransform.dylib) + 23  [0x114f97561]`
</code>```

I can catch that with lldb and see the arriving packet data making sense as the format I'm describing.

The packet signatures look following:

0x24 0x02 0x05 0x85 0x80 0x60 0x01 0x57 0x00 0x00 0x00 0x02 0x00 0x00 0x27 0xde
0x0d 0x80 0x60 0x37 0x94 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c
0x85 0xb8 0x00 00 00 00 01 65 0xb8 0x0 0x0 0xa 0x35 ...

0x24 0x02 0x05 0x85 0x80 0x60 0x01 0x58 0x00 0x00 0x00 0x02 0x00 0x00 0x27 0xde
0xd 0x80 0x60 0x37 0x95 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c 0x05 0x15 0xac ...

0x24 0x02 0x5 0x85 0x80 0x60 0x01 0x59 0x00 0x0 0x00 0x02 0x00 00x0 0x27 0xde
0xd 0x80 0x60 0x37 0x96 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c 0x05 0x5d 0x00 ...

By the means of reverse engineering the original software I was able to figure out that 0x7c85 indicates a key frame. 0x7c85 bytes in the genuine software processing do get replaced by h264 00 00 00 01 65 Key frame NALU . That's h264 appendix-B format.
The 0x7c05 packets always follow and are the remaining payload of the key frame. No NALU are added during their handling (the 0x7c05 is stripped away and rest of the bytes is copied). None of the bytes preceding 0x7cXX make it to a mp4 recording (that makes sense as it's the RTP protocol , albeit I'm not sure if it's entirely RTP standard or there's something custom from Hikvision).

If you pay close attention in the Header there are 2 separate bytes indicating order which always match, so I'm sure no packet loss is occurring.

I also observed nonkey frames arriving as 0x7c81 and converted to 00 00 00 01 61 NALU but I want to focus solely on the single key frame for now. Mostly because if I record a movie with the original software it will always begin with 00 00 00 01 65 Key frame (that obviously makes sense).

To get a working mp4 I decided to copy paste a mp4 header of a genuine iVMS-4200 recording (in this sense that's every byte preceding 1st frame NALU 00 00 00 01 65 in the mp4 file). I know that the resolution will match the actual camera footage. With the strategy of waiting for a keyframe , replacing 0x7c85 with 00 00 00 01 65 NALU and appending the remaining bytes, or only appending bytes in the 0x7c05 case I do seem to get something that eventually could work.
When I attempt to ffplay the custom crafted mp4 result I do get something (with a little stretch of imagination that's actually the camera fisheye image forming), but clearly there is a problem.

It seems around 3-4th 0x7c05 packet (as the failing packet differs on every run), when I copy bytes eventually the h264 stream is incorrect. Just by eye-inspecting the bytes I don't see anything unusual.

This is the failing packet around offset 750 decimal, (I know it's around this place because I keep stripping bytes away to see if there's still same amount frame arriving before it breaks).

More over I did dump those bytes from original software using lldb taking out my own python implementation out of equation. And I run into very same problem with the original packets.

The mp4 header I use should work (since it does for original recordings even if I manipulate number of frames and leave just the first keyframe).
Correct me if I'm wrong but the phase of converting this to MPEG2-PS (which iVMS-4200 does and I don't) should be entirely optional and should not be related to my problem.

Update:
I went the path of setting up recording and only then dumping the original iVMS-4200 packets. I edited the recorded movie to only contain keyframe of interest and it works. I found differences but I cannot explain where they are there yet:

Somehow 00 00 01 E0  13 FA 88 00 02 FF FF is inserted in the genuine recording (that's 4th packet), but I have no idea how this byte string was generated and what is its purpose.
When I fixed the first difference the next one is:

The pattern is striking. But what00 00 01 E0  13 FA 88 00 02 FF FF actually is? And why is it inserted after 18 03 25 10 & 2F F4 80 FC

The 00 00 01 E0 signature would suggest those are Packetized Elementary Stream (PES) headers

答:
Going for mp4 container wasn't a good choice after all. It turns out the RTP essentially yields raw h264 stream. To inspect its structure I converted the genuine mp4 recording to .264 like this:

```<code>ffmpeg -i recording.mp4 -codec copy recording.264
</code>```

It's essentially a PPS (00 00 00 01 67) and SPS 00 00 00 01 68 followed by frame data NALUs that I got in the stream.

Raw h264 turned out a way simpler structure to aim at, and I don't have to deal with those Packetized Elementary Stream (PES) headers anymore. That yields correct image. In my case I just took the PPS & SPS settings that original recordings use from recording.264. That could definitely be resolved dynamically somehow but I didn't bother.

Body:
I'm trying to receive RTP stream encoding h264 over TCP from my intercom Hikvision DS-KH8350-WTE1. By reverse engineering I was able to replicate how Hikvision original software Hik-Connect on iPhone and iVMS-4200 on MacOS connects and negotaties streaming. Now I'm getting the very same stream as original apps - verified through Wireshark. Now I need to "make sense" of the stream. I know it's RTP because I inspected how iVMS-4200 uses it using /usr/bin/sample on MacOS. Which yields:

  ! :               2 CStreamConvert::InputData(void*, int)  (in libOpenNetStream.dylib) + 52  [0x11ff7c7a6]
+     ! :                 2 SYSTRANS_InputData  (in libSystemTransform.dylib) + 153  [0x114f917f2]
+     ! :                   1 CRTPDemux::ProcessH264(unsigned char*, unsigned int, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 302  [0x114fa2c04]
+     ! :                   | 1 CRTPDemux::AddAVCStartCode()  (in libSystemTransform.dylib) + 47  [0x114fa40f1]
+     ! :                   1 CRTPDemux::ProcessH264(unsigned char*, unsigned int, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 476  [0x114fa2cb2]
+     ! :                     1 CRTPDemux::ProcessVideoFrame(unsigned char*, unsigned int, unsigned int)  (in libSystemTransform.dylib) + 1339  [0x114fa29b3]
+     ! :                       1 CMPEG2PSPack::InputData(unsigned char*, unsigned int, FRAME_INFO*)  (in libSystemTransform.dylib) + 228  [0x114f961d6]
+     ! :                         1 CMPEG2PSPack::PackH264Frame(unsigned char*, unsigned int, FRAME_INFO*)  (in libSystemTransform.dylib) + 238  [0x114f972fe]
+     ! :                           1 CMPEG2PSPack::FindAVCStartCode(unsigned char*, unsigned int)  (in libSystemTransform.dylib) + 23  [0x114f97561]`

I can catch that with lldb and see the arriving packet data making sense as the format I'm describing.

The packet signatures look following:

0x24 0x02 0x05 0x85 0x80 0x60 0x01 0x57 0x00 0x00 0x00 0x02 0x00 0x00 0x27 0xde
0x0d 0x80 0x60 0x37 0x94 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c
0x85 0xb8 0x00 00 00 00 01 65 0xb8 0x0 0x0 0xa 0x35 ...

0x24 0x02 0x05 0x85 0x80 0x60 0x01 0x58 0x00 0x00 0x00 0x02 0x00 0x00 0x27 0xde
0xd 0x80 0x60 0x37 0x95 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c 0x05 0x15 0xac ...

0x24 0x02 0x5 0x85 0x80 0x60 0x01 0x59 0x00 0x0 0x00 0x02 0x00 00x0 0x27 0xde
0xd 0x80 0x60 0x37 0x96 0x71 0xe3 0x97 0x10 0x77 0x20 0x2c 0x51 | 0x7c 0x05 0x5d 0x00 ...

By the means of reverse engineering the original software I was able to figure out that 0x7c85 indicates a key frame. 0x7c85 bytes in the genuine software processing do get replaced by h264 00 00 00 01 65 Key frame NALU . That's h264 appendix-B format.
The 0x7c05 packets always follow and are the remaining payload of the key frame. No NALU are added during their handling (the 0x7c05 is stripped away and rest of the bytes is copied). None of the bytes preceding 0x7cXX make it to a mp4 recording (that makes sense as it's the RTP protocol , albeit I'm not sure if it's entirely RTP standard or there's something custom from Hikvision).

If you pay close attention in the Header there are 2 separate bytes indicating order which always match, so I'm sure no packet loss is occurring.

I also observed nonkey frames arriving as 0x7c81 and converted to 00 00 00 01 61 NALU but I want to focus solely on the single key frame for now. Mostly because if I record a movie with the original software it will always begin with 00 00 00 01 65 Key frame (that obviously makes sense).

To get a working mp4 I decided to copy paste a mp4 header of a genuine iVMS-4200 recording (in this sense that's every byte preceding 1st frame NALU 00 00 00 01 65 in the mp4 file). I know that the resolution will match the actual camera footage. With the strategy of waiting for a keyframe , replacing 0x7c85 with 00 00 00 01 65 NALU and appending the remaining bytes, or only appending bytes in the 0x7c05 case I do seem to get something that eventually could work.
When I attempt to ffplay the custom crafted mp4 result I do get something (with a little stretch of imagination that's actually the camera fisheye image forming), but clearly there is a problem.

It seems around 3-4th 0x7c05 packet (as the failing packet differs on every run), when I copy bytes eventually the h264 stream is incorrect. Just by eye-inspecting the bytes I don't see anything unusual.

This is the failing packet around offset 750 decimal, (I know it's around this place because I keep stripping bytes away to see if there's still same amount frame arriving before it breaks).

More over I did dump those bytes from original software using lldb taking out my own python implementation out of equation. And I run into very same problem with the original packets.

The mp4 header I use should work (since it does for original recordings even if I manipulate number of frames and leave just the first keyframe).
Correct me if I'm wrong but the phase of converting this to MPEG2-PS (which iVMS-4200 does and I don't) should be entirely optional and should not be related to my problem.

Update:
I went the path of setting up recording and only then dumping the original iVMS-4200 packets. I edited the recorded movie to only contain keyframe of interest and it works. I found differences but I cannot explain where they are there yet:

Somehow 00 00 01 E0  13 FA 88 00 02 FF FF is inserted in the genuine recording (that's 4th packet), but I have no idea how this byte string was generated and what is its purpose.
When I fixed the first difference the next one is:

The pattern is striking. But what00 00 01 E0  13 FA 88 00 02 FF FF actually is? And why is it inserted after 18 03 25 10 & 2F F4 80 FC

The 00 00 01 E0 signature would suggest those are Packetized Elementary Stream (PES) headers

Body:
Going for mp4 container wasn't a good choice after all. It turns out the RTP essentially yields raw h264 stream. To inspect its structure I converted the genuine mp4 recording to .264 like this:

ffmpeg -i recording.mp4 -codec copy recording.264

It's essentially a PPS (00 00 00 01 67) and SPS 00 00 00 01 68 followed by frame data NALUs that I got in the stream.

Raw h264 turned out a way simpler structure to aim at, and I don't have to deal with those Packetized Elementary Stream (PES) headers anymore. That yields correct image. In my case I just took the PPS & SPS settings that original recordings use from recording.264. That could definitely be resolved dynamically somehow but I didn't bother.


问:
How to create a button with border and transparent background android
How can I create this type of a button in android which has only borders and is transparent, like the "ADD" button in the picture below?

P.S. This is a picture from Ludmila Shevchenko's travel app. Although the screenshot is of ios, I would want to achieve this in android. How can I do it?

答:
you don't need to add extra resource xml, just copy this and paste it. its so simple .Thanks

```<code>           <com.google.android.material.button.MaterialButton
                        android:id="@+id/JoinButton_id"
                      style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_margin="20dp"
                        android:text="JOIN"
                        android:textColor="@color/white"
                        app:strokeColor="@color/white" />
</code>```

enter image description here

Body:
you don't need to add extra resource xml, just copy this and paste it. its so simple .Thanks

           <com.google.android.material.button.MaterialButton
                        android:id="@+id/JoinButton_id"
                      style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_margin="20dp"
                        android:text="JOIN"
                        android:textColor="@color/white"
                        app:strokeColor="@color/white" />

enter image description here


问:
In jmeter websocket request shown run as sucessfully but request ping is not shown in aws logs as it fail. How can we run webscoket using jmeter
In jmeter websocket request shown run as sucessfully but request ping is not shown in aws logs as it fail. How can we run webscoket using jmeter.

Request response

Request header

Request

AWS Logs

答:
It seems you have successfully executed the request (from JMeter perspective)

If you want to try troubleshooting the issue from JMeter side you could increase JMeter logging verbosity for the WebSocket Samplers plugin by adding the next line to log4j2.xml file:

```<code><Logger name="eu.luminis" level="debug" />
</code>```

JMeter restart will be required to pick up the change, once done you should be able to see all request and response details in the jmeter.log file.

Both log4j2.xml and jmeter.log files should live in "bin" folder of your JMeter installation

Body:
It seems you have successfully executed the request (from JMeter perspective)

If you want to try troubleshooting the issue from JMeter side you could increase JMeter logging verbosity for the WebSocket Samplers plugin by adding the next line to log4j2.xml file:

<Logger name="eu.luminis" level="debug" />

JMeter restart will be required to pick up the change, once done you should be able to see all request and response details in the jmeter.log file.

Both log4j2.xml and jmeter.log files should live in "bin" folder of your JMeter installation


问:
Print words within the string from last to first
for example I entered follwoing string ;
" hello I am Mohsen" ;
now I want to Print on output :
"Mohsen am I hello "

please help me !

答:
Split by space, reverse the list, and stitch it back together.

s = " hello I am Mohsen"
words = s.split(' ')
words_reversed = words[::-1]
s_reversed = ' '.join(words_reversed)

print(s_reversed)
```


问:
createStackNavigator is not a function
I am building my first practice app and was trying to put together navigation between screens using the createAppNavigator.

However, as soon as I try to use createAppNavigator I get the following error .

.

Relevant code:

App.js

import React from 'react';
import { Home } from './app/views/Home.js';
import { Contact } from './app/views/Contact.js';
import { createStackNavigator } from 'react-navigation';

const MyRoutes = createStackNavigator({
    HomeRT: { screen: Home },
    ContactRT: { screen: Contact },
  },
  {
    initialRouteName: 'HomeRT'
  }
);

export default class App extends React.Component {
  render() {
    return (
      <MyRoutes />
    );
  }
}```

I am really puzzled as to what I am doing wrong. One idea is that perhaps react-navigation is not installed correctly, but beyond using npm install --save react-navigation, I don't know what else I could need to do.

答:
This can also happen when switching from @react-navigation/stack to @react-navigation/native-stack, the imported function names differs:

With /stack:

```<code>import { createStackNavigator } from '@react-navigation/stack';
</code>```

With /native-stack

```<code>import { createNativeStackNavigator } from '@react-navigation/native-stack';
</code>```

If you forget to modify the imported function you will have the same error message.

Title: createStackNavigator is not a function

Body:
I am building my first practice app and was trying to put together navigation between screens using the createAppNavigator.

However, as soon as I try to use createAppNavigator I get the following error .

.

Relevant code:

App.js

import React from 'react';
import { Home } from './app/views/Home.js';
import { Contact } from './app/views/Contact.js';
import { createStackNavigator } from 'react-navigation';

const MyRoutes = createStackNavigator({
    HomeRT: { screen: Home },
    ContactRT: { screen: Contact },
  },
  {
    initialRouteName: 'HomeRT'
  }
);

export default class App extends React.Component {
  render() {
    return (
      <MyRoutes />
    );
  }
}

I am really puzzled as to what I am doing wrong. One idea is that perhaps react-navigation is not installed correctly, but beyond using npm install --save react-navigation, I don't know what else I could need to do.

Body:
This can also happen when switching from @react-navigation/stack to @react-navigation/native-stack, the imported function names differs:

With /stack:

import { createStackNavigator } from '@react-navigation/stack';

With /native-stack

import { createNativeStackNavigator } from '@react-navigation/native-stack';

If you forget to modify the imported function you will have the same error message.


问:
How to check if an element exists and only then run a test with Cypress?
I want to execute some function only when certain element is present using its data-test id.

Below is what I am trying to do:

```<code>cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}
</code>```

Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".

How can I fix this? Could someone please help me with this?

答:
You can use the jquery method .attr to check the presence of the attribute data-testid.

cy.get('checkbox-id').then(($ele) => {
  if ($ele.attr('data-testid')) {
    cy.tableSelectAll()
  } else {
    //Do something else
  }
})
```

Body:
I want to execute some function only when certain element is present using its data-test id.

Below is what I am trying to do:

cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}

Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".

How can I fix this? Could someone please help me with this?


问:
Example from cppreference.com does not compile with MSVC
Tried to compile the following example from cppreference.com:

```<code>#include <coroutine>

struct promise;
struct coroutine : std::coroutine_handle<promise>
{
    using promise_type = struct promise;
};

struct promise {
    coroutine get_return_object()
    {
        return { coroutine::from_promise(*this) };
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
};

struct S {
    int i;
    coroutine f() {
        std::cout << i;
        co_return;
    }
};
</code>```

but got compiler error:

```<code>error C3789: this function cannot be a coroutine: 'coroutine::promise' does not declare the member 'get_return_object()'
</code>```

Compiler: MSVC2019, /std:c++latest

Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30137 for x86

But GCC12 compiles it, what is wrong with MSVC?

EDIT1

The same error with MSVC2022

Optimizing Compiler Version 19.30.30709 for x86

/std:c++latest

答:
As the Site says:

Work in progress: This page is in progress of being updated to reflect the parts of Coroutines Technical Specification that were included in the working draft of C++20.

This example is not runnable with a MSVC2019 Compiler.
You can install and try it with this version:

https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes

Body:
Tried to compile the following example from cppreference.com:

#include <coroutine>

struct promise;
struct coroutine : std::coroutine_handle<promise>
{
    using promise_type = struct promise;
};

struct promise {
    coroutine get_return_object()
    {
        return { coroutine::from_promise(*this) };
    }
    std::suspend_always initial_suspend() noexcept { return {}; }
    std::suspend_never final_suspend() noexcept { return {}; }
    void return_void() {}
    void unhandled_exception() {}
};

struct S {
    int i;
    coroutine f() {
        std::cout << i;
        co_return;
    }
};

but got compiler error:

error C3789: this function cannot be a coroutine: 'coroutine::promise' does not declare the member 'get_return_object()'

Compiler: MSVC2019, /std:c++latest

Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30137 for x86

But GCC12 compiles it, what is wrong with MSVC?

EDIT1

The same error with MSVC2022

Optimizing Compiler Version 19.30.30709 for x86

/std:c++latest


问:
LEFT JOIN query with COUNT takes so long to execute
I have 4 tables, album, artist, song_cover and song.
Am trying to join the 3 tables to the album table and include the total number of songs within each album.

The query I have so far returns results as expected but takes almost over a minute to execute.

```<code>SELECT frco_album.*,
COUNT(frco_song.song_id) AS TotalSongs,
artist_aka, artist_address,
cover_filename
FROM frco_album
LEFT JOIN frco_song ON frco_album.album_id =
frco_song.song_album_id
LEFT JOIN frco_artist ON frco_album.album_artist =
frco_artist.artist_id
LEFT JOIN frco_song_cover ON frco_album.album_cover_id =
frco_song_cover.cover_id
GROUP BY frco_album.album_id
ORDER BY album_month DESC LIMIT 0, 20;
</code>```

When I get rid of the song table LEFT JOIN song ON album.album_id = song.song_album_id and COUNT(song.song_id) AS TotalSongs, the query executes fast, as expected.

What am I doing wrong here?

EDIT: I've edited the question to include the tables and changed the query to reflect the actual rows in the tables.

答:
The left join will multiply rows and then you condense them back using group by. Assuming that there is one artist and cover per album I would try counting the songs inside the select clause:

```<code>SELECT album.*, artist_aka, artist_address, cover_filename, (
    SELECT COUNT(*)
    FROM songs
    WHERE song.song_album_id = album.album_id
) AS TotalSongs
FROM album
LEFT JOIN artist ON album.album_artist_id = artist.artist_id
LEFT JOIN song_cover ON album.album_cover_id = song_cover.cover_id
ORDER BY album_plays DESC
LIMIT 0, 20
</code>```

Body:
I have 4 tables, album, artist, song_cover and song.
Am trying to join the 3 tables to the album table and include the total number of songs within each album.

The query I have so far returns results as expected but takes almost over a minute to execute.

SELECT frco_album.*,
COUNT(frco_song.song_id) AS TotalSongs,
artist_aka, artist_address,
cover_filename
FROM frco_album
LEFT JOIN frco_song ON frco_album.album_id =
frco_song.song_album_id
LEFT JOIN frco_artist ON frco_album.album_artist =
frco_artist.artist_id
LEFT JOIN frco_song_cover ON frco_album.album_cover_id =
frco_song_cover.cover_id
GROUP BY frco_album.album_id
ORDER BY album_month DESC LIMIT 0, 20;

When I get rid of the song table LEFT JOIN song ON album.album_id = song.song_album_id and COUNT(song.song_id) AS TotalSongs, the query executes fast, as expected.

What am I doing wrong here?

EDIT: I've edited the question to include the tables and changed the query to reflect the actual rows in the tables.

Body:
The left join will multiply rows and then you condense them back using group by. Assuming that there is one artist and cover per album I would try counting the songs inside the select clause:

SELECT album.*, artist_aka, artist_address, cover_filename, (
    SELECT COUNT(*)
    FROM songs
    WHERE song.song_album_id = album.album_id
) AS TotalSongs
FROM album
LEFT JOIN artist ON album.album_artist_id = artist.artist_id
LEFT JOIN song_cover ON album.album_cover_id = song_cover.cover_id
ORDER BY album_plays DESC
LIMIT 0, 20


问:
Parsing a Datetime String into a Django DateTimeField
I have a Django app with a model that contains a field of type DateTimeField.

I am pulling data from the web in the format of 2008-04-10 11:47:58-05.

I believe that the last 3 characters in this example are the timezone.

How can I preserve that data in the DateTimeField, and is there an easy conversion between the two? Setting the DateTimeField to simply contain a string of the above format throws a ValidationError.

Thank you!

答:
To make standard format:

```<code>from django.utils.dateparse import parse_datetime
formatted_datetime = parse_datetime(YOUR_STRING_DATETIME).strftime('%Y-%m-%d %H:%M:%S')
print(f"formatted_datetime: {formatted_datetime}")
</code>```

You will see something like this:

```<code>2022-02-09 12:58:52
</code>```

Be successful

Body:
To make standard format:

from django.utils.dateparse import parse_datetime
formatted_datetime = parse_datetime(YOUR_STRING_DATETIME).strftime('%Y-%m-%d %H:%M:%S')
print(f"formatted_datetime: {formatted_datetime}")

You will see something like this:

2022-02-09 12:58:52

Be successful


问:
How to pass type parameter dynamically while creating an instance of an object
Assuming I've got a class looking like the following one:

```<code>public class MyClass<MyType> : MyBaseClass<MyType> where MyType : class, IMyInterface
{
}
</code>```

In a first step, I'm getting a List with all types of the classes that implement IMyInterface
var typeIMyInterface = typeof(IMyInterface);

```<code>var typesThatImplementIMyInterface = AppDomain.CurrentDomain.GetAssemblies()
                                                 .SelectMany(s => s.GetTypes())
                                                 .Where(p => typeIMyInterface .IsAssignableFrom(p) && p.IsClass);
</code>```

Then in a second step, I want to loop through these types and create an instance of MyClass for the type in the loop fof further usage.

```<code>foreach (Type typeThatImplementsIMyInterface in typesThatImplementIMyInterface)
{
    var myInstance = Activator.CreateInstance<MyClass<typeThatImplementsIMyInterface>>();
}
</code>```

Unfortunately, the last block of code doesn't work because of a compile-time error "Cannot resolve type typeThatImplementsIMyInterface".

How can I pass this type correctly, so that I can successfully create an instance of the object?

答:
You have to construct the type using Type.MakeGenericType and afterwards call the un-generic version of Activator.CreateInstance:

```<code>var d1 = typeof(MyClass<>);
var constructedType = d1.MakeGenericType(new[] { typeThatImplementsIMyInterface });
var instance = activator.CreateInstance(constructedType);
</code>```

Body:
Assuming I've got a class looking like the following one:

public class MyClass<MyType> : MyBaseClass<MyType> where MyType : class, IMyInterface
{
}

In a first step, I'm getting a List with all types of the classes that implement IMyInterface
var typeIMyInterface = typeof(IMyInterface);

var typesThatImplementIMyInterface = AppDomain.CurrentDomain.GetAssemblies()
                                                 .SelectMany(s => s.GetTypes())
                                                 .Where(p => typeIMyInterface .IsAssignableFrom(p) && p.IsClass);

Then in a second step, I want to loop through these types and create an instance of MyClass for the type in the loop fof further usage.

foreach (Type typeThatImplementsIMyInterface in typesThatImplementIMyInterface)
{
    var myInstance = Activator.CreateInstance<MyClass<typeThatImplementsIMyInterface>>();
}

Unfortunately, the last block of code doesn't work because of a compile-time error "Cannot resolve type typeThatImplementsIMyInterface".

How can I pass this type correctly, so that I can successfully create an instance of the object?

Body:
You have to construct the type using Type.MakeGenericType and afterwards call the un-generic version of Activator.CreateInstance:

var d1 = typeof(MyClass<>);
var constructedType = d1.MakeGenericType(new[] { typeThatImplementsIMyInterface });
var instance = activator.CreateInstance(constructedType);