问:
DropDownList On telerik grid with inline Edit Option mvc
I am using Telerik grid for mvc project , I want drop down list to be in the grid for four values , but I want first to choose the the dropdownlist to be present at inline edit mode and to be disabled at non edit mode
 here is my bound statement</p>

```<code> column.Bound(objUser => objUser.UserState)
            .ClientTemplate(
                                    Html.Telerik().DropDownList()
                                    .Name("UserState<#= UserState #>")
                                    .BindTo(new SelectList(ProjectTest.Controllers.UserController.UserStateList().ToList()))
                                    .Encode(false)
                                    .ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false)

        .Title("User State");
</code>```

答:
I've been wrestling with this too. take a look at the link below, in which I asked the same type of question. In my case, I managed to get this working, but still have some questions about HOW I got it working. Anyway, I hope this helps ...

Telerik MVC Grid: How to use DropDownList in a column?

Body:
I am using Telerik grid for mvc project , I want drop down list to be in the grid for four values , but I want first to choose the the dropdownlist to be present at inline edit mode and to be disabled at non edit mode
 here is my bound statement

 column.Bound(objUser => objUser.UserState)
            .ClientTemplate(
                                    Html.Telerik().DropDownList()
                                    .Name("UserState<#= UserState #>")
                                    .BindTo(new SelectList(ProjectTest.Controllers.UserController.UserStateList().ToList()))
                                    .Encode(false)
                                    .ToHtmlString().Replace("{", "{{").Replace("}", "}}")).Encoded(false)

        .Title("User State");


来源: stackexchange

问:
Quarkus How to get all url query param?
I would like to get all query params from an URL but I can't use @QueryParam without specifying a name, since names of paramters are dynamic, I can have some params that start with same name : param_toto, param_tata, param_titi, etc.

```<code>@QueryParam("") Map<String, String> queryParams
</code>```

I get this error : RESTEASY003875: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.QueryParam("")

Please not that I don't want to use : HttpServletRequest since is not support by Quarkus, and I need to add a dependecy, of corse vertx has it implementation.

答: You can use @Context UriInfo uriInfo and call uriInfo.getQueryParameters()

ContentLicense: CC BY-SA 4.0

Title: Quarkus How to get all url query param?

Body:
I would like to get all query params from an URL but I can't use @QueryParam without specifying a name, since names of paramters are dynamic, I can have some params that start with same name : param_toto, param_tata, param_titi, etc.

@QueryParam("") Map<String, String> queryParams

I get this error : RESTEASY003875: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.QueryParam("")

Please not that I don't want to use : HttpServletRequest since is not support by Quarkus, and I need to add a dependecy, of corse vertx has it implementation.


问:
Is GPS activated - Flutter
Is there a way to find out in Flutter if the GPS is activated or deactivated?
I use the plugin location however there I get only the location and not the state of the GPS.</p>

答:
```<code>checkLocationPermission() async {
final status = await Permission.location.request();
if (status == PermissionStatus.granted) {
  debugPrint('Permission granted');
  bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
  if (isLocationEnabled) {
  // location service is enabled,
  } else {
  // open Location settings
    await Geolocator.openLocationSettings();
  }
} else if (status == PermissionStatus.denied) {
  debugPrint(
      'Permission denied. Show a dialog and again ask for the permission');
} else if (status == PermissionStatus.permanentlyDenied) {
  debugPrint('Take the user to the settings page.');
  await openAppSettings();
}
}
</code>```

Title: Is GPS activated - Flutter


问:
Powershell script running terminals indefinitely
what I'm trying to do is setting up aliases to run Windows Terminal from file browser in the current directory, as admin or regular user.
I'm not very familiar with powershell scripts and I'm trying to understand why my functions are called when the script is loaded instead of when the alias is called, which in turn runs terminals indefinitely..

Here is the script I wrote in $Profile :

```<code>$wtHere = "wt -d ."
function Run-Command{
    param($Command)
    Invoke-Expression $Command
}
function Run-As-Administrator{
        param($Command)
        Run-Command -Command "runas /user:administrator $Command"
}
set-alias -Name wtha -Value $(Run-As-Administrator -Command $wtHere)
set-alias -Name wth -Value $(Run-Command -Command $wtHere)
</code>```

答:
Quoting this excellent answer which explains really well what you're doing wrong:

PowerShell aliases do not allow for arguments.

They can only refer to a command name, which can be the name of a cmdlet or a function, or the name / path of a script or executable

And from the official Docs:

The Set-Alias cmdlet creates or changes an alias for a cmdlet or a command, such as a function, script, file, or other executable. An alias is an alternate name that refers to a cmdlet or command.

This should help you understand what is going:

```<code>$wtHere = "Hello world"

function Run-Command {
    param($Command)
    "$Command - Received on {0}" -f $MyInvocation.MyCommand.Name
}

function Run-As-Admin {
    param($Command)
    Run-Command ("From {0} - Command: $Command" -f $MyInvocation.MyCommand.Name)
}

Set-Alias -Name wtha -Value $(Run-As-Admin -Command $wtHere)
Set-Alias -Name wth -Value $(Run-Command -Command $wtHere)
Get-Alias wth, wtha | Select-Object Name, Definition
</code>```

You're storing the "result" of your functions and not the functions definitions into your aliases. You can't store an expression such as Run-As-Admin -Command $wtHere as the Value of your Alias, it will be stored as literal, even if you run the alias you would see that PowerShell will run the result of your expression and fail:

wth: The term 'Hello world - Received on Run-Command' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What you should do is as simple as:

```<code>Set-Alias -Name wtha -Value Run-As-Admin
Set-Alias -Name wth -Value Run-Command
</code>```

Then you can interactively run:

```<code>PS /> wtha $wtHere
</code>```

Body:
what I'm trying to do is setting up aliases to run Windows Terminal from file browser in the current directory, as admin or regular user.
I'm not very familiar with powershell scripts and I'm trying to understand why my functions are called when the script is loaded instead of when the alias is called, which in turn runs terminals indefinitely..

Here is the script I wrote in $Profile :

$wtHere = "wt -d ."
function Run-Command{
    param($Command)
    Invoke-Expression $Command
}
function Run-As-Administrator{
        param($Command)
        Run-Command -Command "runas /user:administrator $Command"
}
set-alias -Name wtha -Value $(Run-As-Administrator -Command $wtHere)
set-alias -Name wth -Value $(Run-Command -Command $wtHere)

Body:
Quoting this excellent answer which explains really well what you're doing wrong:

PowerShell aliases do not allow for arguments.

They can only refer to a command name, which can be the name of a cmdlet or a function, or the name / path of a script or executable

And from the official Docs:

The Set-Alias cmdlet creates or changes an alias for a cmdlet or a command, such as a function, script, file, or other executable. An alias is an alternate name that refers to a cmdlet or command.

This should help you understand what is going:

$wtHere = "Hello world"

function Run-Command {
    param($Command)
    "$Command - Received on {0}" -f $MyInvocation.MyCommand.Name
}

function Run-As-Admin {
    param($Command)
    Run-Command ("From {0} - Command: $Command" -f $MyInvocation.MyCommand.Name)
}

Set-Alias -Name wtha -Value $(Run-As-Admin -Command $wtHere)
Set-Alias -Name wth -Value $(Run-Command -Command $wtHere)
Get-Alias wth, wtha | Select-Object Name, Definition

You're storing the "result" of your functions and not the functions definitions into your aliases. You can't store an expression such as Run-As-Admin -Command $wtHere as the Value of your Alias, it will be stored as literal, even if you run the alias you would see that PowerShell will run the result of your expression and fail:

wth: The term 'Hello world - Received on Run-Command' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What you should do is as simple as:

Set-Alias -Name wtha -Value Run-As-Admin
Set-Alias -Name wth -Value Run-Command

Then you can interactively run:

PS /> wtha $wtHere


问:
SwiftUI UIHostingController navigation title animation broken
When I use a UIHostingController to push a new SwiftUI.View to the navigation stack of an existing UIKit UIViewController the animation of the title in the navigation bar is broken. I tested in Xcode 12.0 on a pure new project.

Watch carefully the title "UIHostingController". You can see how the animation looks different from normal push animation, it just "appears" out of nothing and looks broken. The second animation happens already from SwiftUI.NavigationLink which looks fine.

Here is a link to the sample project if you want to try it out:
https://www.dropbox.com/s/mjkuzhpsb6yvlir/HostingControllerTest.zip?dl=0

See this GIF image: (open in another browser tab if you don't the see GIF animation)

This is the code behind:

```<code>class ViewController: UIViewController {
    private let button = UIButton(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "UIHostingController Title Test"
        self.view.backgroundColor = UIColor.white

        self.view.addSubview(self.button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("Push UIHostingController", for: .normal)
        button.addTarget(self, action: #selector(Self.pushVC), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            button.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    @objc private func pushVC() {
        let vc = UIHostingController(rootView: Content())
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

struct Content: View {
    var body: some View {
        NavigationLink(destination: Content2()) {
            Text("Push NavigationLink")
        }
        .navigationTitle("UIHostingController")
    }
}

struct Content2: View {
    var body: some View {
        Text("Coming from NavigationLink")
            .navigationTitle("Native SwiftUI View")
    }
}
</code>```

答:
To force UIHostingController to set up its navigation item we can pre-render it in a separate window:

let window = UIWindow(frame: .zero)
window.rootViewController = UINavigationController(rootViewController: hostingController)
window.isHidden = false
window.layoutIfNeeded()
```

The window could even be cached for pre-rendering other views.

Update: the workaround seems to stop working on iOS 16.4.

Body:
When I use a UIHostingController to push a new SwiftUI.View to the navigation stack of an existing UIKit UIViewController the animation of the title in the navigation bar is broken. I tested in Xcode 12.0 on a pure new project.

Watch carefully the title "UIHostingController". You can see how the animation looks different from normal push animation, it just "appears" out of nothing and looks broken. The second animation happens already from SwiftUI.NavigationLink which looks fine.

Here is a link to the sample project if you want to try it out:
https://www.dropbox.com/s/mjkuzhpsb6yvlir/HostingControllerTest.zip?dl=0

See this GIF image: (open in another browser tab if you don't the see GIF animation)

This is the code behind:

class ViewController: UIViewController {
    private let button = UIButton(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "UIHostingController Title Test"
        self.view.backgroundColor = UIColor.white

        self.view.addSubview(self.button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("Push UIHostingController", for: .normal)
        button.addTarget(self, action: #selector(Self.pushVC), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            button.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    @objc private func pushVC() {
        let vc = UIHostingController(rootView: Content())
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

struct Content: View {
    var body: some View {
        NavigationLink(destination: Content2()) {
            Text("Push NavigationLink")
        }
        .navigationTitle("UIHostingController")
    }
}

struct Content2: View {
    var body: some View {
        Text("Coming from NavigationLink")
            .navigationTitle("Native SwiftUI View")
    }
}

Body:
To force UIHostingController to set up its navigation item we can pre-render it in a separate window:

let window = UIWindow(frame: .zero)
window.rootViewController = UINavigationController(rootViewController: hostingController)
window.isHidden = false
window.layoutIfNeeded()

The window could even be cached for pre-rendering other views.

Update: the workaround seems to stop working on iOS 16.4.


问:
Reversing a hash, getting its keys, and sorting
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

```<code>foreach my $key (sort keys reverse %hash){

...}
</code>```

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

答:
The argument to keys must be a hash, array or expression, not a list. If you did

```<code>keys { reverse %hash }
</code>```

you would get the result you expect, because the brackets create an anonymous hash. Parens, on the other hand, only change the precedence. Or, in this case they are probably considered related to the function keys(), as most perl functions have optional parens.

Also, if you just want the values of the hash, you can use:

```<code>values %hash
</code>```

See the documentation for reverse, values and keys for more info.

ContentLicense: CC BY-SA 3.0

Body:
I'm still learning Perl, so there's probably a more efficient way of doing this. I'm trying to take a hash, reverse it so $values => $keys, grab the new key (the old value) and then sort those keys.

Here's the code in question:

foreach my $key (sort keys reverse %hash){

...}

What I'm expecting to happen is that reverse %hash will return a hash type, which is what keys is looking for. However, I get the following error:

Type of arg 1 to keys must be hash (not reverse)

I've tried putting parentheses around reverse %hash, but still get the same thing.

Any ideas why this wouldn't work?

Body:
The argument to keys must be a hash, array or expression, not a list. If you did

keys { reverse %hash }

you would get the result you expect, because the brackets create an anonymous hash. Parens, on the other hand, only change the precedence. Or, in this case they are probably considered related to the function keys(), as most perl functions have optional parens.

Also, if you just want the values of the hash, you can use:

values %hash

See the documentation for reverse, values and keys for more info.


问:
Tilde ~ in SCSS @use statement no longer resolving to node_modules as of Angular 13
After upgrading an Angular 12 project to Angular 13 I encountered an issue where SCSS was no longer to locate a shared style sheet in a library. It appears that that Tilde (~) no longer resolves to node_modules.

Broken:
@use '~my-angular-lib' as lib;

Works:
@use '../node_modules/my-angular-lib' as lib;

I noticed that angular material just directly refences '@angular/material' as of Angular 13 but I can't figure out how to get that to work with my library. It seems kind of hacky to use a relative path to node_modules every time.

What is the current best method of refencing a style sheet in node_modules, or what am I missing to where ~ no longer points to node_modules?

答:
To use @use 'my-angular-lib' as lib; you need to make sure to export the relevant files in your angular libraries package.json and ng-package.json files (see https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).

Here my configuration for example:

// package.json
  ...,
  "exports": {
    ".": {
      "sass": "./src/lib/_index.scss"
    }
  },
  ...
// ng-package.json
  ...,
  "assets": [
    "./src/lib/_index.scss",
    "./**/*-theme.scss"
  ],
  ...
```
<p>All my theme related component files have the suffix <code>-theme</code> and I have one scss file (<code>_index.scss</code>) that contains only one <code>@mixin</code> to <code>@include</code> theme specific component styles. For example:</p>
<pre class="lang-scss prettyprint-override"><code>// src/lib/_index.scss
@use './some/some-component-theme' as *;
@mixin lib-theme($theme) {
  @include some-component-theme($theme);
}
</code>```

Hint: Sometimes I had to manually remove the .angular/cache folder when working with local libraries. So try this if something odd happens during the build process.

Body:
To use @use 'my-angular-lib' as lib; you need to make sure to export the relevant files in your angular libraries package.json and ng-package.json files (see https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).

Here my configuration for example:

// package.json
  ...,
  "exports": {
    ".": {
      "sass": "./src/lib/_index.scss"
    }
  },
  ...
// ng-package.json
  ...,
  "assets": [
    "./src/lib/_index.scss",
    "./**/*-theme.scss"
  ],
  ...

All my theme related component files have the suffix -theme and I have one scss file (_index.scss) that contains only one @mixin to @include theme specific component styles. For example:

// src/lib/_index.scss
@use './some/some-component-theme' as *;
@mixin lib-theme($theme) {
  @include some-component-theme($theme);
}

Hint: Sometimes I had to manually remove the .angular/cache folder when working with local libraries. So try this if something odd happens during the build process.


问:
Round to nearest number between two numbers
How do I round a fraction to the nearest 0.5 between 0.0 and 5.0?

Let's say I've got 11/150, it should convert to 0.0. In addition, 75/150 should convert to 2.5

As for the code I've got this but I'm lost as to where to go from here

```<code># number is 11, and max is 150

number = float(percent / max)
number = round(p/0.5)*0.5
</code>```

However, it needs to round between 0.0 and 5.0 rather than 0 and 1.

EDIT 1:

It's best to treat it as a percentage. For example, let's say the percent given is 5o% (50/100, for ease). This means the result should be 2.5

In the same respect, 51% would still be 2.5.

However, 60% (60/100) would be 3.0

答:
Multiply by 2, round, then divide by 2

if you want nearest quarter, multiply by 4, divide by 4, etc

Body:
How do I round a fraction to the nearest 0.5 between 0.0 and 5.0?

Let's say I've got 11/150, it should convert to 0.0. In addition, 75/150 should convert to 2.5

As for the code I've got this but I'm lost as to where to go from here

# number is 11, and max is 150

number = float(percent / max)
number = round(p/0.5)*0.5

However, it needs to round between 0.0 and 5.0 rather than 0 and 1.

EDIT 1:

It's best to treat it as a percentage. For example, let's say the percent given is 5o% (50/100, for ease). This means the result should be 2.5

In the same respect, 51% would still be 2.5.

However, 60% (60/100) would be 3.0


问:
How to read text from an image and save it to a text file
I used

```<code>image_path= "image.jpg"
reader = easyocr.Reader(['en'], gpu=False)
result= reader.readtext(image_path)
print(result)
print("text printed")
</code>```

output:

Using CPU. Note: This module is much faster with a GPU.
[([[707, 587], [999, 587], [999, 719], [707, 719]], 'Dream', 0.930219167433956), ([[998, 546], [1246, 546], [1246, 770], [998, 770]], 'big!', 0.8384830355644226)]
text printed
```

But the run time is very large I don't know why

If I want to write an API for the same is it possible to show the file path as output?
Any suggestions would be very helpful.
Thanks

答:
```<code>#Depends on what you need. Here I am appending cords and text.

#If your running to whole folder run this.

reader = easyocr.Reader(["en"], gpu = False)

text = []
cords= []
for files in glob.glob("*.jpg"):
  #print(files)
  images = cv2.imread(files)
  bounds = reader.readtext(images)
  for bound in bounds:
    text.append(bound[1])
    cords.append(bound[0])

#Creating the dataframe and transfer to text file
df_ocr = pd.DataFrame({"cords": cords,"text": text})
df_ocr.to_csv('result.txt', sep='\t', index=False)

#If your runnning to single file
bound = reader.readtext(image)
df_ocr = pd.DataFrame({"cords": bound[0],"text": bound[1})
df_ocr.to_csv('result.txt', sep='\t', index=False)
</code>```

Body:
I used

image_path= "image.jpg"
reader = easyocr.Reader(['en'], gpu=False)
result= reader.readtext(image_path)
print(result)
print("text printed")

output:

Using CPU. Note: This module is much faster with a GPU.
[([[707, 587], [999, 587], [999, 719], [707, 719]], 'Dream', 0.930219167433956), ([[998, 546], [1246, 546], [1246, 770], [998, 770]], 'big!', 0.8384830355644226)]
text printed

But the run time is very large I don't know why

If I want to write an API for the same is it possible to show the file path as output?
Any suggestions would be very helpful.
Thanks


问:
find pairs of numbers where cube is equal to square
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

```<code>def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)
</code>```

what will be an optimal way to solve this problem with a better time complexity?

答:
You can use itertool's combinations_with_replacement function.

from itertools import combinations_with_replacement as combinations

def get_pair(N):
    for i, j in combinations(range(1,N), 2):
        if i*i*i==j*j:
            print(i,j)
N=50
get_pair(N)
```

Body:
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)

what will be an optimal way to solve this problem with a better time complexity?


问:
Gmail SMTP error - Temporary block?
I am using Gmail servers to send email from my system, with a program.
Recently I started getting errors like this:

Data command failed: 421 4.7.0 Temporary System Problem.  Try again later (WS). 6sm3756432pab.11 - gsmtp

The reasons are given in the support.

Can anybody tell me what is the number of emails that can trigger this issue?

Or is it because of some other reasons?

答: have a rest for 20 minutes , and try again, the error gone</p>

Title: Gmail SMTP error - Temporary block?


问:
Using matplotlib to draw a path given cartesian coordinates
I'm new to matplotlib and numpy and am trying to plot some array data to something like this:

but it currently looks like this:

My code is extremely basic but basically the image above is what I'd like to be able to do. I'm not too concerned yet with drawing gridlines but  the plot should be proportional. I've looked at some examples on the mathplotlib website but can't find something similar enough.
I wonder if pyplot is not the correct procedure or if my array is not formatted correctly?

```<code>import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)
plt.ylim(0, 4)
plt.xlim(0, 4)
plt.axis([0, 4, 0, 4])
plt.plot(data)
plt.show()
</code>```

Body:
I'm new to matplotlib and numpy and am trying to plot some array data to something like this:

but it currently looks like this:

My code is extremely basic but basically the image above is what I'd like to be able to do. I'm not too concerned yet with drawing gridlines but  the plot should be proportional. I've looked at some examples on the mathplotlib website but can't find something similar enough.
I wonder if pyplot is not the correct procedure or if my array is not formatted correctly?

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

data = np.asarray(data)
print(data)
plt.ylim(0, 4)
plt.xlim(0, 4)
plt.axis([0, 4, 0, 4])
plt.plot(data)
plt.show()

Body:
You could try something like this:

import numpy as np
from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

for i in range(len(data) -1):
  x1 = data[i][0]
  y1 = data[i][1]
  x2 = data[i+1][0]
  y2 = data[i+1][1]
  plt.plot([x1, x2], [y1, y2], c='blue')
  plt.scatter(x1, y1, c='blue')
plt.show()


问:
Techniques for implementing -hash on mutable Cocoa objects
The documentation for -hash says it must not change while a mutable object is stored in a collection, and similarly the documentation for -isEqual: says the -hash value must be the same for equal objects.

Given this, does anybody have any suggestions for the best way to implement -hash such that it meets both these conditions and yet is actually calculated intelligently (i.e. doesn't just return 0)? Does anybody know how the mutable versions of framework-provided classes do this?

The simplest thing to do is of course just forget the first condition (about it not changing) and just make sure I never accidentally mutate an object while it's in a collection, but I'm wondering if there's any solution that's more flexible.

EDIT: I'm wondering here whether it's possible to maintain the 2 contracts (where equal objects have equal hashes, and hashes don't change while the object is in a collection) when I'm mutating the internal state of the object. My inclination is to say "no", unless I do something stupid like always return 0 for the hash, but that's why I'm asking this question.

答:
The question here isn't how to meet both of these requirements, but rather which one you should meet.  In Apple's documentation, it is clearly stated that:

a mutable dictionary can be put in a hash table but you must not change it while it is in there.

This being said, it seems more important that you meet the equality requirement of hashes.  The hash of an object should always be a way to check if an object is equal to another.  If this is ever not the case, it is not a true hash function.

Just to finish up my answer, I'll give an example of a good hash implementation.  Let's say you are writing the implementation of -hash on a collection that you have created.  This collection stores an array of NSObjects as pointers.  Since all NSObjects implement the hash function, you can use their hashes in calculating the collection's hash:

```<code>- (NSUInteger)hash {
    NSUInteger theHash = 0;
    for (NSObject * aPtr in self) { // fast enumeration
        theHash ^= [aPtr hash];
    }
    return theHash;
}
</code>```

This way, two collection objects containing the same pointers (in the same order) will have the same hash.

OwnerDisplayName: Kevin Ballard

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kevin Ballard

Body:
The question here isn't how to meet both of these requirements, but rather which one you should meet.  In Apple's documentation, it is clearly stated that:

a mutable dictionary can be put in a hash table but you must not change it while it is in there.

This being said, it seems more important that you meet the equality requirement of hashes.  The hash of an object should always be a way to check if an object is equal to another.  If this is ever not the case, it is not a true hash function.

Just to finish up my answer, I'll give an example of a good hash implementation.  Let's say you are writing the implementation of -hash on a collection that you have created.  This collection stores an array of NSObjects as pointers.  Since all NSObjects implement the hash function, you can use their hashes in calculating the collection's hash:

- (NSUInteger)hash {
    NSUInteger theHash = 0;
    for (NSObject * aPtr in self) { // fast enumeration
        theHash ^= [aPtr hash];
    }
    return theHash;
}

This way, two collection objects containing the same pointers (in the same order) will have the same hash.


问:
How to change default font size for ag-grid row cells in react js?
I am using ag-grid table for first time. I am not able to change the default font size of row cells(Not header portion). I want to change the font size of row cells(row data). I am using ag-theme-alpine.

Here is the code which I am using.

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            columnDefs: [
                {headerName: 'Make', field: 'make'},
                {headerName: 'Model', field: 'model'},
                {headerName: 'Price', field: 'price'}

            ],
            rowData: [
                {make: 'Toyota', model: 'Celica', price: 35000},
                {make: 'Ford', model: 'Mondeo', price: 32000},
                {make: 'Porsche', model: 'Boxter', price: 72000}
            ]
        }
    }

    render() {
        return (
            <div
                className="ag-theme-alpine"
          style={{ height: '500px', width: '100%',fontSize:'20px' }}
            >
                <AgGridReact
                    columnDefs={this.state.columnDefs}
                    rowData={this.state.rowData}>
                </AgGridReact>
            </div>
        );
    }
}

render(<App />, document.getElementById('root'));
</code>```

Please suggest a good solution.

答:
You can set font-size and other parameters globally by customizing a theme: React Data Grid: Customising Themes

Define the style parameters in the styles.scss file like this:

```<code>.ag-theme-alpine {
  @include ag-theme-alpine((
      font-size: 10px,
  ));
}
</code>```

Body:
I am using ag-grid table for first time. I am not able to change the default font size of row cells(Not header portion). I want to change the font size of row cells(row data). I am using ag-theme-alpine.

Here is the code which I am using.

import React, { Component } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            columnDefs: [
                {headerName: 'Make', field: 'make'},
                {headerName: 'Model', field: 'model'},
                {headerName: 'Price', field: 'price'}

            ],
            rowData: [
                {make: 'Toyota', model: 'Celica', price: 35000},
                {make: 'Ford', model: 'Mondeo', price: 32000},
                {make: 'Porsche', model: 'Boxter', price: 72000}
            ]
        }
    }

    render() {
        return (

                <AgGridReact
                    columnDefs={this.state.columnDefs}
                    rowData={this.state.rowData}>
                </AgGridReact>

        );
    }
}

render(<App />, document.getElementById('root'));

Please suggest a good solution.

Body:
You can set font-size and other parameters globally by customizing a theme: React Data Grid: Customising Themes

Define the style parameters in the styles.scss file like this:

.ag-theme-alpine {
  @include ag-theme-alpine((
      font-size: 10px,
  ));
}


问:
VirtualBox drag & drop from host to guest not working
I am using Windows 10 as my host and Ubuntu 14.04.3 Linux as the guest OS for my VirtualBox VMs.

Even after installing 'Guest Additions' on my VM and setting the 'Drag and Drop' to 'Bidirectional',  I am not able to drag files/folders from the host machine (Windows) to the guest (Linux).

The opposite i.e. dragging and dropping from guest to host is working fine as expected.

What could be the issue? Is it a bug in VirtualBox?

答:
I've solved the issue by just adding the user to the vboxsf group, using the next command in the Guest OS (Ubuntu). After restarting the Guest OS this feature started to work normally.</p>
```<code>sudo adduser $USER vboxsf
</code>```

Body:
I've solved the issue by just adding the user to the vboxsf group, using the next command in the Guest OS (Ubuntu). After restarting the Guest OS this feature started to work normally.

sudo adduser $USER vboxsf


问:
Preventing duplicate requests to java servlet
I have a java serlvet, which accesses a hadoop cluster and sends a downloadable csv of some data from the hadoop cluster as a response.

My issue is that there appears to be multiple GET requests to this servlet (which I understand to be intentional for chrome + other browsers), which is causing multiple connections to open to my Hadoop cluster. I don't want multiple requests at once. Is there a way to deny multiple requests from the same source and only respond to the first request?

答:
Solution: Nginx Proxy Cache

You can put Nginx in-front of the java servlet. Nginx has a caching module and required mechanism to prevent thundering herd.

Although your problem does not involve high concurrency but still you can use nginx cache locking mechanism which will lock the cache for a defined period of time allowing only one request to fill the cache.

Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache

```<code>proxy_cache_lock on;
proxy_cache_lock_age 5s; # depending on the use case
proxy_cache_lock_timeout 5s;
</code>```

Body:
Solution: Nginx Proxy Cache

You can put Nginx in-front of the java servlet. Nginx has a caching module and required mechanism to prevent thundering herd.

Although your problem does not involve high concurrency but still you can use nginx cache locking mechanism which will lock the cache for a defined period of time allowing only one request to fill the cache.

Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache

proxy_cache_lock on;
proxy_cache_lock_age 5s; # depending on the use case
proxy_cache_lock_timeout 5s;


问:
cannot send mail using mailgun
I am using mailgun driver in laravel app and tried to send mail. But it gives me this error

```<code>Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required
</code>```

config/mail.php

```<code>'driver' => env('mailgun', 'smtp'),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'arshaikh_17@hotmail.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],
</code>```

.env

```<code>MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

services.php

```<code>'mailgun' => [
        'domain' => env('mydomain.com.pk'),
        'secret' => env('key-********************'),
    ],
</code>```

What is wrong with my settings and is there anything else you need to check? Please help I have been trying to study laracast for past 2 days but it doesn't send mail.

答: To me it was that I was using an incorrect value for MAILGUN_SECRET env variable, at first I was using a key that I received through email but the required value was the api secret key that is way longer. Api secret key can be found in: Settings -> API Keys -> Private API key at mailgun.org</p>

Title: cannot send mail using mailgun

Body:
I am using mailgun driver in laravel app and tried to send mail. But it gives me this error

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

config/mail.php

'driver' => env('mailgun', 'smtp'),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'arshaikh_17@hotmail.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

.env

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

services.php

'mailgun' => [
        'domain' => env('mydomain.com.pk'),
        'secret' => env('key-********************'),
    ],

What is wrong with my settings and is there anything else you need to check? Please help I have been trying to study laracast for past 2 days but it doesn't send mail.


问:
Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: ["name"]
```<code> import 'package:flutter/material.dart';
 import 'package:http/http.dart' as http;
 import 'dart:convert';

 class homePage extends StatefulWidget {
      const homePage({Key? key}) : super(key: key);

      @override
     _homePageState createState() => _homePageState();
       }

     class _homePageState extends State<homePage> {
     var data;
     @override
     void initState() {
     // TODO: implement initState
     super.initState();
     getData();
     }

     getData() async {
      var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

      data = jsonDecode(res.body);

      print("i am waleed" + data[2]["name"]);
      setState(() {});
       }

      @override
       Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My app"),
      ),
      body: Container(
        child: data != null
            ? ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                      //   title: data[index]["id"],
                      );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    );
  }
}
</code>```

the data is coming from the API but not showing in the ListView giving the following error:

```<code>Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: ["name"]
</code>```

Please anyone who can solve it.

答:
You're using incorrect property name and structure when accessing the data. Here is your json structure from the api:

```<code>{
  "success": true,
  "data": {
    "memes": [
      {
        "id": "181913649",
        "name": "Drake Hotline Bling",
        "url": "https://i.imgflip.com/30b1gx.jpg",
        "width": 1200,
        "height": 1200,
        "box_count": 2
      }
    ]
  }
}
</code>```

So, you need to access data object, then memes array. Then you can access each memes element.

You need to use something like this:

```<code>getData() async {
  var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

  Map<String, dynamic> maps = jsonDecode(res.body);

  var name = maps['data']['memes'][2]['name'];

  debugPrint("i am waleed $name");
}
</code>```

For complex json, see JSON and serialization

UPDATE

For reading your json api result, you need to create the object for it. You can use something like this (generated from online tools):

```<code>class MemeResult {
  late final bool success;
  late final Data data;
  MemeResult({
    required this.success,
    required this.data,
  });

  MemeResult.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    data = Data.fromJson(json['data']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['success'] = success;
    _data['data'] = data.toJson();
    return _data;
  }
}

class Data {
  late final List<Memes> memes;

  Data({required this.memes});

  Data.fromJson(Map<String, dynamic> json) {
    memes = List.from(json['memes']).map((e) => Memes.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['memes'] = memes.map((e) => e.toJson()).toList();
    return _data;
  }
}

class Memes {
  late final String id;
  late final String name;
  late final String url;
  late final int width;
  late final int height;
  late final int boxCount;

  Memes({
    required this.id,
    required this.name,
    required this.url,
    required this.width,
    required this.height,
    required this.boxCount,
  });

  Memes.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    url = json['url'];
    width = json['width'];
    height = json['height'];
    boxCount = json['box_count'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['name'] = name;
    _data['url'] = url;
    _data['width'] = width;
    _data['height'] = height;
    _data['box_count'] = boxCount;
    return _data;
  }
}
</code>```

Then, you can use it like the following:

```<code>  getData() async {
    var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

    var maps = jsonDecode(res.body);
    MemeResult result = MemeResult.fromJson(maps);
    debugPrint(result.data.memes[2].name);
    setState(() {});
  }
</code>```

You need to use Serializing JSON using code generation libraries for your json instead of creating the code manually.

Body:
 import 'package:flutter/material.dart';
 import 'package:http/http.dart' as http;
 import 'dart:convert';

 class homePage extends StatefulWidget {
      const homePage({Key? key}) : super(key: key);

      @override
     _homePageState createState() => _homePageState();
       }

     class _homePageState extends State<homePage> {
     var data;
     @override
     void initState() {
     // TODO: implement initState
     super.initState();
     getData();
     }

     getData() async {
      var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

      data = jsonDecode(res.body);

      print("i am waleed" + data[2]["name"]);
      setState(() {});
       }

      @override
       Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My app"),
      ),
      body: Container(
        child: data != null
            ? ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                      //   title: data[index]["id"],
                      );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    );
  }
}

the data is coming from the API but not showing in the ListView giving the following error:

Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: ["name"]

Please anyone who can solve it.

Body:
You're using incorrect property name and structure when accessing the data. Here is your json structure from the api:

{
  "success": true,
  "data": {
    "memes": [
      {
        "id": "181913649",
        "name": "Drake Hotline Bling",
        "url": "https://i.imgflip.com/30b1gx.jpg",
        "width": 1200,
        "height": 1200,
        "box_count": 2
      }
    ]
  }
}

So, you need to access data object, then memes array. Then you can access each memes element.

You need to use something like this:

getData() async {
  var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

  Map<String, dynamic> maps = jsonDecode(res.body);

  var name = maps['data']['memes'][2]['name'];

  debugPrint("i am waleed $name");
}

For complex json, see JSON and serialization

UPDATE

For reading your json api result, you need to create the object for it. You can use something like this (generated from online tools):

class MemeResult {
  late final bool success;
  late final Data data;
  MemeResult({
    required this.success,
    required this.data,
  });

  MemeResult.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    data = Data.fromJson(json['data']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['success'] = success;
    _data['data'] = data.toJson();
    return _data;
  }
}

class Data {
  late final List<Memes> memes;

  Data({required this.memes});

  Data.fromJson(Map<String, dynamic> json) {
    memes = List.from(json['memes']).map((e) => Memes.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['memes'] = memes.map((e) => e.toJson()).toList();
    return _data;
  }
}

class Memes {
  late final String id;
  late final String name;
  late final String url;
  late final int width;
  late final int height;
  late final int boxCount;

  Memes({
    required this.id,
    required this.name,
    required this.url,
    required this.width,
    required this.height,
    required this.boxCount,
  });

  Memes.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    url = json['url'];
    width = json['width'];
    height = json['height'];
    boxCount = json['box_count'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['name'] = name;
    _data['url'] = url;
    _data['width'] = width;
    _data['height'] = height;
    _data['box_count'] = boxCount;
    return _data;
  }
}

Then, you can use it like the following:

  getData() async {
    var res = await http.get(Uri.parse("https://api.imgflip.com/get_memes"));

    var maps = jsonDecode(res.body);
    MemeResult result = MemeResult.fromJson(maps);
    debugPrint(result.data.memes[2].name);
    setState(() {});
  }

You need to use Serializing JSON using code generation libraries for your json instead of creating the code manually.


问:
Xamarin Dependency Services does not work with higher Android version
I have programmed a Xamarin app that uses a native Android function through Dependency Service. Specifically it is about WifiManager and the method SetWifiEnabled() which is for turning off Wifi. Using Android 7.1 emulator with API 25 everything works and I can turn off the wifi. With emulator with Android version 11 and API 30 the wifi is not turned off which I assume that the method SetWifiEnabled() does not work. The wifi is not turned off. Does anyone know the reason for this ?
Thanks a lot

Here is the Code from Dependency Service:

```<code>[assembly: Dependency(typeof(GetWifimanager))]
namespace WifiSwitch.Droid
{
    public class GetWifimanager : IWifiManager
    {
        [Obsolete]
        public bool CheckWifi()
        {
            var wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

            return wifiManager != null && wifiManager.SetWifiEnabled(false);

        }
    }
}
</code>```

答:
according to the docs

This method was deprecated in API level 29. Starting with
Build.VERSION_CODES#Q, applications are not allowed to enable/disable
Wi-Fi. Compatibility Note: For applications targeting
Build.VERSION_CODES.Q or above, this API will always fail and return
false. If apps are targeting an older SDK (Build.VERSION_CODES.P or
below), they can continue to use this API.

Body:
I have programmed a Xamarin app that uses a native Android function through Dependency Service. Specifically it is about WifiManager and the method SetWifiEnabled() which is for turning off Wifi. Using Android 7.1 emulator with API 25 everything works and I can turn off the wifi. With emulator with Android version 11 and API 30 the wifi is not turned off which I assume that the method SetWifiEnabled() does not work. The wifi is not turned off. Does anyone know the reason for this ?
Thanks a lot

Here is the Code from Dependency Service:

[assembly: Dependency(typeof(GetWifimanager))]
namespace WifiSwitch.Droid
{
    public class GetWifimanager : IWifiManager
    {
        [Obsolete]
        public bool CheckWifi()
        {
            var wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

            return wifiManager != null && wifiManager.SetWifiEnabled(false);

        }
    }
}


问:
When I paste text to a NSTextView, how to paste plain text only?
When I paste text to a NSTextView, I wish I can paste plain text only. All the rich text formats should be removed, include: font, color, link, and paragraph style. All the text pasted should be displayed with the default font and style of the text view. NSTextView accepts rich text by default, how to disable it?</p>

答: Use isRichText = false to disable rich text.


问:
share env variable beween turborepo monorepo project
I ve setup a basic turborepo project and I want to share .env variables across the all the apps and some of packages. If I set one .env file in the root of project and how can all apps and packages access them. Or for my requirement do I need to set multiple .env files in all apps and packages?

答:
To load the env variables from .env into the process env you can use https://www.npmjs.com/package/dotenv.

Then to share the env variables in your monorepo :

In each workspace/app add require('dotenv').config({path: /custom/path/to/.env}) (assuming common js module resolution here) as early as possible as per docs (meaning e.g. for a next js app in next.config.js), where /custom/path/to/.env would be the relative path to your root .env (e.g. two folders up:../../.env)


问:
Send Email outlook using Excel VBA
I am trying to send an email using Excel with this code :

```<code>Sub SEND_EMAIL()

Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

' ADRESSE
olMail.To = "selojo7915@rippb.com"
' Subject
olMail.subject = "Line"
' BODY
olMail.body = "this"

olMail.Send
</code>```

When starting this macro i have the following error

The error is in the last line (olMail.Send)

And every time i am trying to send an email outlook is starting to update and after a moment it's showing error

Exception de HRESULT : 0x80004004 (E_ABORT)

答:
You see a security issue (earlier prompts) because Outlook is configured on the client computer in one of the following ways:

Uses the default Outlook security settings (that is, no Group Policy set up)

Uses security settings defined by Group Policy but does not have programmatic access policy applied

Uses security settings defined by Group Policy which is set to warn when the antivirus software is inactive or out of date

You can create a group policy to prevent security prompts from displaying if any up-to-date antivirus software is installed on the system or just turn these warning off (which is not really recommended).

Read more about that in the Security Behavior of the Outlook Object Model article.

You may consider using the following workarounds:

Install any antivirus software with latest updates.

Use a low-level API - Extended MAPI which doesn't trigger security issues. You may also consider Redemption which is a convenient wrapper around Extended MAPI.

Create a COM add-in which has access to the safe Application instance.

Use group policy settings to turn such security prompts/issues when dealing with Outlook.

Also you may consider using third-party components that allow turning off and on dynamically security prompts and issues in Outlook. See Outlook Security Manager for more information.

Title: Send Email outlook using Excel VBA

Body:
I am trying to send an email using Excel with this code :

Sub SEND_EMAIL()

Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

' ADRESSE
olMail.To = "selojo7915@rippb.com"
' Subject
olMail.subject = "Line"
' BODY
olMail.body = "this"

olMail.Send

When starting this macro i have the following error

The error is in the last line (olMail.Send)

And every time i am trying to send an email outlook is starting to update and after a moment it's showing error

Exception de HRESULT : 0x80004004 (E_ABORT)


问:
Don't repeat keyof Type expression in generics
I don't want to repeat keyof T expression in here:

```<code>// This type is meant to achieve something like ReturnType<typeof Object.entries>
type ObjectEntries<T extends object> = [keyof T, T[keyof T]][];
</code>```

So I do this but it doesn't work:

```<code>type ObjectEntries<T extends object, U = keyof T> = [U, T[U]][];
// Type 'U' cannot be used to index type 'T'
</code>```

However if U extends to keyof T, it works but why?

```<code>type ObjectEntries<T extends object, U extends keyof T = keyof T> = [U, T[U]][];
</code>```

答:
U extends X means that U needs to be a type that extends X, it is also called a type constraint. If you leave it like this, U must be specified and you will get a compiler error if you don't specify it when instantiating ObjectEntries.

U = X means that if U is unspecified when instantiating ObjectEntries it will by default be X, but since U does not have any constraint, U could be any type whatsoever (for example string).

Constraints and defaults serve different purposes and so if you want U to default to keyof T so you don't have to specify it you need the  = keyof T, and if you also want to constrain U so only types that are subtypes of keyof T can be specified, you will need the extends keyof T. The constraint is what gives TyepScript enough information to know that it is safe to index T with U, since any specified type for U must be a subtype of keyof T

Body:
I don't want to repeat keyof T expression in here:

// This type is meant to achieve something like ReturnType<typeof Object.entries>
type ObjectEntries<T extends object> = [keyof T, T[keyof T]][];

So I do this but it doesn't work:

type ObjectEntries<T extends object, U = keyof T> = [U, T[U]][];
// Type 'U' cannot be used to index type 'T'

However if U extends to keyof T, it works but why?

type ObjectEntries<T extends object, U extends keyof T = keyof T> = [U, T[U]][];


问:
How do i change a pivot table from grand total to average?
Good afternoon, it is necessary that in the end there is not a sum, but the average of all values. Is it possible to implement this functionality?</p>

答:
In WDR, there is no clear way to make an average grand total if subtotal values contain the sum aggregations.
But you can change the text in grand total cells with the customizeCell  function to make it contain an average value.
Example:

<!DOCTYPE html>

    <title>WDR</title>

    <link href="https://cdn.webdatarocks.com/latest/webdatarocks.min.css" rel="stylesheet" />

```

Body:
In WDR, there is no clear way to make an average grand total if subtotal values contain the sum aggregations.
But you can change the text in grand total cells with the customizeCell  function to make it contain an average value.
Example:

<!DOCTYPE html>
<html>
<head>
    <title>WDR</title>
</head>
<body>
    <link href="https://cdn.webdatarocks.com/latest/webdatarocks.min.css" rel="stylesheet" />
    <script src="https://cdn.webdatarocks.com/latest/webdatarocks.toolbar.min.js"></script>
    <script src="https://cdn.webdatarocks.com/latest/webdatarocks.js"></script>
    <div id="wdr"></div>
    <script>
        var pivot = new WebDataRocks({
            container: "#wdr",
            toolbar: true,
            customizeCell: customize,
            report: {
                dataSource: {
                    filename: "https://cdn.webdatarocks.com/data/data.csv"
                }
            }
        });

        function customize(cell,data) {
            if(data.isGrandTotalRow) {
                cell.text = data.value / (data.rowIndex - 1);
            }
        }
    </script>
</body>
</html>


问:
refactor cferror tag to application.cfc's onError()
How to translate

```<code><cferror type="EXCEPTION" template="ErrorTemplate.cfm">
</code>```

to an onError() function for Application.cfc?  Notice that cferror create a var error struct for the template.  Is there a quick and easy way to create the same error struct?  How to pass that into ErrorTemplate.cfm using <cfinclude>?

I know onRequest() shares the variable scope with the target page, but does onError share variables scope too?  If not, what shall I do? Stick it to the Form scope?

Thank you

答: Why would you not just use onError in App.cfc to display a "Sorry and error occurred, we are working on it" type page?</p>

Body:
How to translate

<cferror type="EXCEPTION" template="ErrorTemplate.cfm">

to an onError() function for Application.cfc?  Notice that cferror create a var error struct for the template.  Is there a quick and easy way to create the same error struct?  How to pass that into ErrorTemplate.cfm using <cfinclude>?

I know onRequest() shares the variable scope with the target page, but does onError share variables scope too?  If not, what shall I do? Stick it to the Form scope?

Thank you


答:
You need to unpack the x and y components into arrays like this:

```<code>plt.plot([p[0] for p in data], [p[1] for p in data], 'o-')
</code>```

Use format style "o-": "o" for a symbol marker and "-" for a solid line.

To also format the x/y ticks here is the full code:

from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

x = [p[0] for p in data]
y = [p[1] for p in data]
_, ax = plt.subplots()
ax.set_xticks(range(5))
ax.set_yticks(range(5))
ax.plot(x, y, 'o-', color='blue')
plt.grid() # add grid lines
plt.show()
```

Output:

Title: Using matplotlib to draw a path given cartesian coordinates

Body:
You need to unpack the x and y components into arrays like this:

plt.plot([p[0] for p in data], [p[1] for p in data], 'o-')

Use format style "o-": "o" for a symbol marker and "-" for a solid line.

To also format the x/y ticks here is the full code:

from matplotlib import pyplot as plt

data = [(2, 2), (3, 2), (4, 1), (4, 0), (3, 0), (3, 1), (4, 2),
        (4, 3), (4, 4), (3, 3), (3, 4), (2, 4), (2, 3), (1, 4),
        (0, 4), (0, 3), (1, 3), (0, 2), (1, 2), (0, 1), (0, 0),
        (1, 0), (1, 1), (2, 0), (2, 1)]

x = [p[0] for p in data]
y = [p[1] for p in data]
_, ax = plt.subplots()
ax.set_xticks(range(5))
ax.set_yticks(range(5))
ax.plot(x, y, 'o-', color='blue')
plt.grid() # add grid lines
plt.show()

Output:


问:
Why list of stories does not get initialized in this file once I run the code?
In this code, I cache data from Firebase realtime data base and then save it locally in Hive database. All this code used to work in another project that was null safe, but implementing this in an old project does not work. Where is the problem?
Here is the code:

```<code>class NewHomeScreen extends StatefulWidget {
  const NewHomeScreen({Key key}) : super(key: key);

  @override
  _NewHomeScreenState createState() => _NewHomeScreenState();
}

class _NewHomeScreenState extends State<NewHomeScreen> {
  List stories = [];
  Box<Story> storyBox;
  List<String> keys;
  @override
  void initState() {
    super.initState();
  }

  Future openBox() async {
    final document = await getApplicationDocumentsDirectory();
    Hive.init(document.path);
    Hive.registerAdapter<Story>(StoryAdapter());
    storyBox = await Hive.openBox<Story>('storyBoxName');
    print('Box Opened!');
  }

  Future<bool> getAllData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    await openBox();
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
    } catch (SocketException) {
      print('No Internet');
    }
    var mymap = storyBox.toMap().values.toList();
    if (mymap.isEmpty) {
      stories.add('empty');
    } else {
      stories = mymap;
    }
    return Future.value(true);
  }

  Future putData(Map<String, dynamic> data) async {
    await storyBox.clear();
    Story newStory;
    data.forEach((key, value) {
      newStory = Story(
        author: value['author'],
        category: value['category'],
        content: value['content'],
        id: key.toString(),
        title: value['title'],
      );
      storyBox.put(key, newStory);
    });
  }

  Future<void> updateData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
      setState(() {});
    } catch (SocketException) {
      Fluttertoast.showToast(
          msg: "This is Center Short Toast",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
      print('No Internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFDEBF7),
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text("Shaparak"),
      ),
      body: Center(
        child: FutureBuilder(
          future: getAllData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (stories.isEmpty) {
                return const Text(
                  'No Data',
                  style: TextStyle(
                    fontSize: 24.0,
                  ),
                );
              } else {
                return RefreshIndicator(
                  onRefresh: updateData,
                  child: ItemsGrid(storyBox.toMap().values.toList()),
                );
              }
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}
</code>```

This used to work in a null safety migrated project, but implementing this in an old project which is not null safe, does not work. Can you please guide me how to solve it?

答: It looks like you need to add the getAllData() to the initState function.

Body:
In this code, I cache data from Firebase realtime data base and then save it locally in Hive database. All this code used to work in another project that was null safe, but implementing this in an old project does not work. Where is the problem?
Here is the code:

class NewHomeScreen extends StatefulWidget {
  const NewHomeScreen({Key key}) : super(key: key);

  @override
  _NewHomeScreenState createState() => _NewHomeScreenState();
}

class _NewHomeScreenState extends State<NewHomeScreen> {
  List stories = [];
  Box<Story> storyBox;
  List<String> keys;
  @override
  void initState() {
    super.initState();
  }

  Future openBox() async {
    final document = await getApplicationDocumentsDirectory();
    Hive.init(document.path);
    Hive.registerAdapter<Story>(StoryAdapter());
    storyBox = await Hive.openBox<Story>('storyBoxName');
    print('Box Opened!');
  }

  Future<bool> getAllData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    await openBox();
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
    } catch (SocketException) {
      print('No Internet');
    }
    var mymap = storyBox.toMap().values.toList();
    if (mymap.isEmpty) {
      stories.add('empty');
    } else {
      stories = mymap;
    }
    return Future.value(true);
  }

  Future putData(Map<String, dynamic> data) async {
    await storyBox.clear();
    Story newStory;
    data.forEach((key, value) {
      newStory = Story(
        author: value['author'],
        category: value['category'],
        content: value['content'],
        id: key.toString(),
        title: value['title'],
      );
      storyBox.put(key, newStory);
    });
  }

  Future<void> updateData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
      setState(() {});
    } catch (SocketException) {
      Fluttertoast.showToast(
          msg: "This is Center Short Toast",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
      print('No Internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFDEBF7),
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text("Shaparak"),
      ),
      body: Center(
        child: FutureBuilder(
          future: getAllData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (stories.isEmpty) {
                return const Text(
                  'No Data',
                  style: TextStyle(
                    fontSize: 24.0,
                  ),
                );
              } else {
                return RefreshIndicator(
                  onRefresh: updateData,
                  child: ItemsGrid(storyBox.toMap().values.toList()),
                );
              }
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

This used to work in a null safety migrated project, but implementing this in an old project which is not null safe, does not work. Can you please guide me how to solve it?


问:
How to customize yii2 gridview filter row?
```<code>                <?=
                    GridView::widget([
                        'dataProvider' => $dataProvider,
                        'filterModel' => $searchModel,
                        'tableOptions' => ['class' => 'table custom-table-view table-striped table-bordered'],
                        'columns' => [
                            ['class' => 'yii\grid\SerialColumn'],
                            [
                                'label' => 'User name',
                                'attribute' => 'name',
                                'filterInputOptions' => [
                                    'class' => 'form-control custom-form-control pr-5',
                                    'placeholder' => 'Search...',

                                ],

                            ],
                        ],
                    ])
                    ?>
</code>```

This is the code which I am using, using this code I am able to add class into and this is the out put.

```<code><table class="table custom-table-view table-striped table-bordered">
    <thead>
      <tr id="w0-filters" class="filters">
        <td> </td>
        <td><input type="text" id="search-name" class="form-control custom-form-control pr-5" name="Search[name]" placeholder="Search..."></td>
     </tr>
</code>```

But what I want is

```<code><tr id="w0-filters" class="filters">
  <td> </td>
   <td>
    <div class"my_class">
    <input type="text" id="search-name" class="form-control custom-form-control pr-5" name="Search[name]" placeholder="Search..."><i class="fa fa-user"></i>
  </div>
</td>
</code>```

How to add my_class div outside input field.?

答:
Question is: why would you want to do that? To me it sounds like you are looking for the GridView afterHeader function.

IF you really need something like that, you would have to extend GridView class and overwrite renderFilters().

```<code><?php

namespace app\common\override\yii2;

class GridView extends \kartik\grid\GridView
{
    /**
     * @inheritdoc
     */
    public function renderFilters()
    {
        /* Just send the Original Filter for demonstration */
        return parent::renderFilters();
    }
}
</code>```

You will find the original renderFilters function just returns a string:

```<code>return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
</code>```

Best strategy to alter the string may be to change the renderFilterCell() function, simpler approach could be

```<code>$cells[] = Html::tag('div',$column->renderFilterCell(),['class'=>'my_class']);
</code>```

Body:
                <?=
                    GridView::widget([
                        'dataProvider' => $dataProvider,
                        'filterModel' => $searchModel,
                        'tableOptions' => ['class' => 'table custom-table-view table-striped table-bordered'],
                        'columns' => [
                            ['class' => 'yii\grid\SerialColumn'],
                            [
                                'label' => 'User name',
                                'attribute' => 'name',
                                'filterInputOptions' => [
                                    'class' => 'form-control custom-form-control pr-5',
                                    'placeholder' => 'Search...',

                                ],

                            ],
                        ],
                    ])
                    ?>

This is the code which I am using, using this code I am able to add class into and this is the out put.

        <input type="text" id="search-name" class="form-control custom-form-control pr-5" name="Search[name]" placeholder="Search...">

But what I want is

    <input type="text" id="search-name" class="form-control custom-form-control pr-5" name="Search[name]" placeholder="Search...">

How to add my_class div outside input field.?

Body:
Question is: why would you want to do that? To me it sounds like you are looking for the GridView afterHeader function.

IF you really need something like that, you would have to extend GridView class and overwrite renderFilters().

<?php

namespace app\common\override\yii2;

class GridView extends \kartik\grid\GridView
{
    /**
     * @inheritdoc
     */
    public function renderFilters()
    {
        /* Just send the Original Filter for demonstration */
        return parent::renderFilters();
    }
}

You will find the original renderFilters function just returns a string:

return Html::tag('tr', implode('', $cells), $this->filterRowOptions);

Best strategy to alter the string may be to change the renderFilterCell() function, simpler approach could be

$cells[] = Html::tag('div',$column->renderFilterCell(),['class'=>'my_class']);


问:
Parallel tree traversal in C#
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

```<code>   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }
</code>```

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

答:
Since the traversal of the tree is extremely fast, that calls to Children are atomic, and that it is the expensive nature of the DoSomething delegates that need to be executed in parallel, here's my take on the solution.

I started with the idea that I needed a function that takes a node as a parameter, creates a task that executes DoSomething, recursively calls itself to create tasks for all of the children nodes, and finally returns a Task that waits for all of the internal tasks to be completed.

Here it is:

```<code>Func<Node, Task> createTask = null;
createTask = n =>
{
    var nt = Task.Factory.StartNew(() =>
    {
        if (n.Property == someValue)
            DoSomething(n);
    });
    var nts = (new [] { nt, })
        .Concat(n.Children.Select(cn => createTask(cn)))
        .ToArray();

    return Task.Factory.ContinueWhenAll(nts, ts => { });
};
</code>```

All that is required to call it and wait for the traversal to complete is:

```<code>createTask(root).Wait();
</code>```

I tested this by creating a tree of nodes with 500 children off of the root with 14 levels, with 1 or 2 subsequent children per node. This gave me a total of 319,501 nodes.

I created a DoSomething method that performed some work - for (var i = 0; i < 100000 ; i++) { }; - and then ran the above code and compared it to processing the same tree in series.

The parallel version took 5,151 ms. The sequential version 13,746 ms.

I also performed a test where I reduced the number of nodes to 3,196 and increased the processing time for DoSomething by 100x. The TPL very cleverly reverts to running sequentially if its tasks complete quickly so lengthening the processing time made the code run with more parallelism.

Now the parallel version took 3,203ms. The sequential version took 11,581ms. And, if I only called the createTask(root) function without waiting for it to complete it took just 126ms. This means that the tree is traversed very quickly, and it would then make sense to lock the tree during traversal and unlock it when processing is taking place.

I hope this helps.

Title: Parallel tree traversal in C#

Body:
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

Body:
Since the traversal of the tree is extremely fast, that calls to Children are atomic, and that it is the expensive nature of the DoSomething delegates that need to be executed in parallel, here's my take on the solution.

I started with the idea that I needed a function that takes a node as a parameter, creates a task that executes DoSomething, recursively calls itself to create tasks for all of the children nodes, and finally returns a Task that waits for all of the internal tasks to be completed.

Here it is:

Func<Node, Task> createTask = null;
createTask = n =>
{
    var nt = Task.Factory.StartNew(() =>
    {
        if (n.Property == someValue)
            DoSomething(n);
    });
    var nts = (new [] { nt, })
        .Concat(n.Children.Select(cn => createTask(cn)))
        .ToArray();

    return Task.Factory.ContinueWhenAll(nts, ts => { });
};

All that is required to call it and wait for the traversal to complete is:

createTask(root).Wait();

I tested this by creating a tree of nodes with 500 children off of the root with 14 levels, with 1 or 2 subsequent children per node. This gave me a total of 319,501 nodes.

I created a DoSomething method that performed some work - for (var i = 0; i < 100000 ; i++) { }; - and then ran the above code and compared it to processing the same tree in series.

The parallel version took 5,151 ms. The sequential version 13,746 ms.

I also performed a test where I reduced the number of nodes to 3,196 and increased the processing time for DoSomething by 100x. The TPL very cleverly reverts to running sequentially if its tasks complete quickly so lengthening the processing time made the code run with more parallelism.

Now the parallel version took 3,203ms. The sequential version took 11,581ms. And, if I only called the createTask(root) function without waiting for it to complete it took just 126ms. This means that the tree is traversed very quickly, and it would then make sense to lock the tree during traversal and unlock it when processing is taking place.

I hope this helps.


问:
Failed to target upsert by query :: could not extract exact shard key', details={}}.; nested exception is com.mongodb.MongoWriteException
We have recently moved to mongo java driver core/sync 4.4.0 from 3.12.1 with spring data mongo db from 2.2.5.RELEASE to 3.3.0 also spring boot version 2.6.2 and mongo server version 4.2.5

We are getting exceptions while hitting upsert queries on sharded collection with above mentioned error

There is way to insert shard key in query filter but that is not feasible for us, hence we tried adding @Sharded annotations to our DTO as we have different shard keys for different collections

Still we are getting the above mentioned error also we are unable to get exact meaning of what is full copy of entity meant in below statement

update/upsert operations replacing/upserting a single existing document as long as the given UpdateDefinition holds a full copy of the entity.

Other queries are working fine also upsert queries are working fine on addition of shard key in query filter but that change is not feasible for us we need quick solution

Please help as not able to find any solution on any platform. Thanks in advance!

答:
So here's the deal:

You cannot upsert on Sharded Collection in MongoDB UNLESS you include the shard key in the filter provided for update operation.

To quote MongoDB Docs:

For a db.collection.update() operation that includes upsert: true and is on a sharded collection, you must include the full shard key in the filter:

For an update operation.

For a replace document operation (starting
in MongoDB 4.2).

If you are using MongoDB 4.4+ then you have a workaround as mentioned below:

However, starting in version 4.4, documents in a sharded collection can be missing the shard key fields. To target a document that is missing the shard key, you can use the null equality match in conjunction with another filter condition (such as on the _id field). For example:

```<code>{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key
</code>```

Ref: - https://docs.mongodb.com/manual/reference/method/db.collection.update/#behavior

Body:
So here's the deal:

You cannot upsert on Sharded Collection in MongoDB UNLESS you include the shard key in the filter provided for update operation.

To quote MongoDB Docs:

For a db.collection.update() operation that includes upsert: true and is on a sharded collection, you must include the full shard key in the filter:

For an update operation.

For a replace document operation (starting
in MongoDB 4.2).

If you are using MongoDB 4.4+ then you have a workaround as mentioned below:

However, starting in version 4.4, documents in a sharded collection can be missing the shard key fields. To target a document that is missing the shard key, you can use the null equality match in conjunction with another filter condition (such as on the _id field). For example:

{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key

Ref: - https://docs.mongodb.com/manual/reference/method/db.collection.update/#behavior


问:
Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64
I'd like to install the pymongo library but I'm getting the following error:

```<code>    (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda install -c anaconda pymongo

    Fetching package metadata ...
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a
    naconda/win-64/repodata.json>
    Elapsed: -

    An HTTP error occurred when trying to retrieve this URL.
    HTTP errors are often intermittent, and a simple retry will get you on your way.

    ConnectTimeout(MaxRetryError("HTTPSConnectionPool(host='conda.anaconda.org', por
    t=443): Max retries exceeded with url: /anaconda/win-64/repodata.json (Caused by
     ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000
    00000054D6128>, 'Connection to conda.anaconda.org timed out. (connect timeout=9.
    15)'))",),)
</code>```

Steps taken to resolve:

```<code>1. Update C:\Users\\xxxxxxx\.condarc file with the following:

channels:
  - defaults
ssl_verify: false
proxy_servers:
http: http://sproxy.fg.xxx.com:1000
https: https://sproxy.fg.xxx.com:1000

2. (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda config --set ssl_verify False
</code>```

Additional Info:

```<code>(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda info

Current conda install:

               platform : win-64
          conda version : 4.3.27
       conda is private : False
      conda-env version : 4.3.27
    conda-build version : 3.0.22
         python version : 3.6.2.final.0
       requests version : 2.18.4
            config file : C:\Users\xxxxxxx\.condarc
             netrc file : None
           offline mode : False
             user-agent : conda/4.3.27 requests/2.18.4 CPython/3.6.2 Windows/7 W
indows/6.1.7601
          administrator : False
</code>```

A number of posts online simply reinstalled Anaconda, any other options apart from a fresh install?

答: Adding that I had the same problem on ubuntu on WSL. None of the solutions worked for me, until I realized I was working on WSL version 1 (I thought I'd already upgraded). Upgrading from WSL 1 to WSL 2 solved the problem for me.</p>

Body:
I'd like to install the pymongo library but I'm getting the following error:

    (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda install -c anaconda pymongo

    Fetching package metadata ...
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a
    naconda/win-64/repodata.json>
    Elapsed: -

    An HTTP error occurred when trying to retrieve this URL.
    HTTP errors are often intermittent, and a simple retry will get you on your way.

    ConnectTimeout(MaxRetryError("HTTPSConnectionPool(host='conda.anaconda.org', por
    t=443): Max retries exceeded with url: /anaconda/win-64/repodata.json (Caused by
     ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000
    00000054D6128>, 'Connection to conda.anaconda.org timed out. (connect timeout=9.
    15)'))",),)

Steps taken to resolve:

1. Update C:\Users\\xxxxxxx\.condarc file with the following:

channels:
  - defaults
ssl_verify: false
proxy_servers:
http: http://sproxy.fg.xxx.com:1000
https: https://sproxy.fg.xxx.com:1000

2. (C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
    conda config --set ssl_verify False

Additional Info:

(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda info

Current conda install:

               platform : win-64
          conda version : 4.3.27
       conda is private : False
      conda-env version : 4.3.27
    conda-build version : 3.0.22
         python version : 3.6.2.final.0
       requests version : 2.18.4
            config file : C:\Users\xxxxxxx\.condarc
             netrc file : None
           offline mode : False
             user-agent : conda/4.3.27 requests/2.18.4 CPython/3.6.2 Windows/7 W
indows/6.1.7601
          administrator : False

A number of posts online simply reinstalled Anaconda, any other options apart from a fresh install?


问:
Best way to pass the logged in user to the backend in Django
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account

Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template?

For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in

Currently, I manage the My account page as below.

navbar.html

```<code>{% if user.is_authenticated %}
   <li class="">
      <a href="{% url 'account' %}">
         <i class='bx bxs-user-detail icon' ></i>
         <span class="text nav-text">My profile</span>
      </a>
   </li>
</code>```

urls.py

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('account', views.account_user, name="account"),
]
</code>```

答:
You can do this by incorporating a key to identify the user in the url structure. This requires changes in three places: 1. navbar.html, 2. urls.py, 3. views.py. See a suggestion for 1. and 2. below.

navbar.html

```<code>{% if user.is_authenticated %}
   <li class="">
      <a href="{% url 'account' user.user_name %}">
         <i class='bx bxs-user-detail icon' ></i>
         <span class="text nav-text">My profile</span>
      </a>
   </li>
</code>```

urls.py

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('account/<str:user_name>/', views.account_user, name="account"),
]
</code>```

views.py

```<code>def your_view(request):
    context = {}
    ..
    # pass user object to context
    context['user'] = request.user
    # then pass context to the view

def account_user(request, user_name):
    # use user_name to update querysets or context
</code>```

However, if I correctly understand what you are trying to accomplish (i.e. you want to personalise the 'account' page to each user), I would approach it differently, namely by incorporating the user specific data in the 'account_user' view. You can do this by accessing the request.user object. This way you do not need to rework the url structure (saving you the steps outlines above).

views.py

```<code>def account_user(request):
    context = {}
    ..
    # pass user object to context
    context['user'] = request.user

    # filter any queries using the request.user object

    # then pass context to the view
</code>```

Body:
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account

Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template?

For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in

Currently, I manage the My account page as below.

navbar.html

{% if user.is_authenticated %}

         My profile

urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('account', views.account_user, name="account"),
]

Body:
You can do this by incorporating a key to identify the user in the url structure. This requires changes in three places: 1. navbar.html, 2. urls.py, 3. views.py. See a suggestion for 1. and 2. below.

navbar.html

{% if user.is_authenticated %}
   <li class="">
      <a href="{% url 'account' user.user_name %}">
         <i class='bx bxs-user-detail icon' ></i>
         <span class="text nav-text">My profile</span>
      </a>
   </li>

urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('account/<str:user_name>/', views.account_user, name="account"),
]

views.py

def your_view(request):
    context = {}
    ..
    # pass user object to context
    context['user'] = request.user
    # then pass context to the view

def account_user(request, user_name):
    # use user_name to update querysets or context

However, if I correctly understand what you are trying to accomplish (i.e. you want to personalise the 'account' page to each user), I would approach it differently, namely by incorporating the user specific data in the 'account_user' view. You can do this by accessing the request.user object. This way you do not need to rework the url structure (saving you the steps outlines above).

views.py

def account_user(request):
    context = {}
    ..
    # pass user object to context
    context['user'] = request.user

    # filter any queries using the request.user object

    # then pass context to the view


问:
Manipulate base64 file in expo
I need to manipulate this file I get in Base64 (download it or share it):

```<code>const generatePDF = async () => {
    const companyReponse = await CompanyService.getCompany();
    const peopleResponse = await PeopleService.getPerson(sale.customerId);

    const company = companyReponse.response.company;
    const people = peopleResponse.response;
    const quote = false;

    const json = await SaleService.generatePDF({
      sale,
      company,
      people,
      quote,
    });

    await ensureFolderExists();

    if (json && json.success) {
      const path = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;

      await FileSystem.writeAsStringAsync(path, json.data, {
        encoding: FileSystem.EncodingType.Base64,
      });

      const url = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;

      Linking.openURL(url);
    }
  };
</code>```

using the base64 string returns and searching like this in the browser data:application/pdf;base64,${json.data} I can even see it. but I've tried it in several ways and none of them worked, I believe this one may be closer to success.

```<code>[Unhandled promise rejection: Error: Could not open URL 'file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf': file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf exposed beyond app through Intent.getData()]
</code>```

答:
I solved this issue in this another ask

[https://stackoverflow.com/questions/69738812/problem-to-generate-pdf-from-a-blob-in-an-expo-app-using-filesystem][1]

Title: Manipulate base64 file in expo

Body:
I need to manipulate this file I get in Base64 (download it or share it):

const generatePDF = async () => {
    const companyReponse = await CompanyService.getCompany();
    const peopleResponse = await PeopleService.getPerson(sale.customerId);

    const company = companyReponse.response.company;
    const people = peopleResponse.response;
    const quote = false;

    const json = await SaleService.generatePDF({
      sale,
      company,
      people,
      quote,
    });

    await ensureFolderExists();

    if (json && json.success) {
      const path = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;

      await FileSystem.writeAsStringAsync(path, json.data, {
        encoding: FileSystem.EncodingType.Base64,
      });

      const url = `${FileSystem.documentDirectory}MyFolder/Sale_${sale._id}.pdf`;

      Linking.openURL(url);
    }
  };

using the base64 string returns and searching like this in the browser data:application/pdf;base64,${json.data} I can even see it. but I've tried it in several ways and none of them worked, I believe this one may be closer to success.

[Unhandled promise rejection: Error: Could not open URL 'file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf': file:///data/user/0/host.exp.exponent/files/ExperienceData/%2540sensiogabriel%252FSensio/MyFolder/Sale_61a122679719d630dc416f91.pdf exposed beyond app through Intent.getData()]