问:
Long For Loop Excecution Time
I am attempting to compare the numerical output of a MATLAB script to that of numpy.

The task, from a homework assignment, is to add the value of 10^-N to itself 10^N times.

The goal is to demonstrate that computers have limitations that will compound in such a calculation.  The result should always be 1, but as N increases, the error will also increase.  For this problem, N should be 0, 1, 2, ..., 8.

My MATLAB script runs quickly with no issues:

```<code>solns = zeros(1, 9);

for N = 0:8
    for ii = 1:(10^N)
        solns(N+1) = solns(N+1) + 10^-N;
    end
end
</code>```

However, using Python 3.8.12 on an Anaconda installation with numpy, this code will not terminate (See Update, code does execute):

import numpy as np

solns = np.zeros((9, 1))

for N in range(len(solns)):
    for _ in range(10**N):
        solns[N] += (10**-N)
```

Is there an error in the Python code or is there some significance difference between the languages that creates this result.

EDIT:

I let the python code run for awhile and it eventually terminated after 230 seconds.  The whole array printed out as just [1., 1., 1., etc.].

For reference, using the tic toc commands on MATLAB, the program was executed in 0.155760 seconds

答:
You're rather abusing NumPy there. Especially the += with an array element seems to take almost all of the time.

This is how I'd do it, takes about 0.5 seconds:

```<code>from itertools import repeat

for N in range(9):
    print(sum(repeat(10**-N, 10**N)))
</code>```

Output (Try it online!):

```<code>1
0.9999999999999999
1.0000000000000007
1.0000000000000007
0.9999999999999062
0.9999999999980838
1.000000000007918
0.99999999975017
1.0000000022898672
</code>```

As @AndrasDeak commented, it's fast due to several optimizations. Let's try fewer optimizations as well.

First, only get rid of NumPy, use simple Python floats. Your original btw takes me about 230 seconds as well. This only about 29 seconds:

```<code>for N in range(9):
    total = 0
    for _ in range(10**N):
        total += (10**-N)
    print(total)
</code>```

Next, don't recompute the added value over and over again. Takes about 11 seconds:

```<code>for N in range(9):
    total = 0
    add = 10**-N
    for _ in range(10**N):
        total += add
    print(total)
</code>```

Next, get rid of range producing lots of int objects for no good reason. Let's use itertools.repeat, it's the fastest iterable I know. Takes about 9 seconds:

```<code>from itertools import repeat

for N in range(9):
    total = 0
    add = 10**-N
    for _ in repeat(None, 10**N):
        total += add
    print(total)
</code>```

Or alternatively, about the same speed:

```<code>from itertools import repeat

for N in range(9):
    total = 0
    for add in repeat(10**-N, 10**N):
        total += add
    print(total)
</code>```

Simply put it into a function to benefit from local variables being faster than globals. Takes about 3.3 seconds then:

```<code>from itertools import repeat

def run():
    for N in range(9):
        total = 0
        for add in repeat(10**-N, 10**N):
            total += add
        print(total)
run()
</code>```

That might be the fastest I can do with an ordinary clean for loop (loop unrolling would help some more, but ugh...).

My sum(repeat(...)) version lets C code do all the work (and sum even optimizes the summation of floats), making it still quite a bit faster.

Title: Long For Loop Excecution Time

Body:
I am attempting to compare the numerical output of a MATLAB script to that of numpy.

The task, from a homework assignment, is to add the value of 10^-N to itself 10^N times.

The goal is to demonstrate that computers have limitations that will compound in such a calculation.  The result should always be 1, but as N increases, the error will also increase.  For this problem, N should be 0, 1, 2, ..., 8.

My MATLAB script runs quickly with no issues:

solns = zeros(1, 9);

for N = 0:8
    for ii = 1:(10^N)
        solns(N+1) = solns(N+1) + 10^-N;
    end
end

However, using Python 3.8.12 on an Anaconda installation with numpy, this code will not terminate (See Update, code does execute):

import numpy as np

solns = np.zeros((9, 1))

for N in range(len(solns)):
    for _ in range(10**N):
        solns[N] += (10**-N)

Is there an error in the Python code or is there some significance difference between the languages that creates this result.

EDIT:

I let the python code run for awhile and it eventually terminated after 230 seconds.  The whole array printed out as just [1., 1., 1., etc.].

For reference, using the tic toc commands on MATLAB, the program was executed in 0.155760 seconds

Body:
You're rather abusing NumPy there. Especially the += with an array element seems to take almost all of the time.

This is how I'd do it, takes about 0.5 seconds:

from itertools import repeat

for N in range(9):
    print(sum(repeat(10**-N, 10**N)))

Output (Try it online!):

1
0.9999999999999999
1.0000000000000007
1.0000000000000007
0.9999999999999062
0.9999999999980838
1.000000000007918
0.99999999975017
1.0000000022898672

As @AndrasDeak commented, it's fast due to several optimizations. Let's try fewer optimizations as well.

First, only get rid of NumPy, use simple Python floats. Your original btw takes me about 230 seconds as well. This only about 29 seconds:

for N in range(9):
    total = 0
    for _ in range(10**N):
        total += (10**-N)
    print(total)

Next, don't recompute the added value over and over again. Takes about 11 seconds:

for N in range(9):
    total = 0
    add = 10**-N
    for _ in range(10**N):
        total += add
    print(total)

Next, get rid of range producing lots of int objects for no good reason. Let's use itertools.repeat, it's the fastest iterable I know. Takes about 9 seconds:

from itertools import repeat

for N in range(9):
    total = 0
    add = 10**-N
    for _ in repeat(None, 10**N):
        total += add
    print(total)

Or alternatively, about the same speed:

from itertools import repeat

for N in range(9):
    total = 0
    for add in repeat(10**-N, 10**N):
        total += add
    print(total)

Simply put it into a function to benefit from local variables being faster than globals. Takes about 3.3 seconds then:

from itertools import repeat

def run():
    for N in range(9):
        total = 0
        for add in repeat(10**-N, 10**N):
            total += add
        print(total)
run()

That might be the fastest I can do with an ordinary clean for loop (loop unrolling would help some more, but ugh...).

My sum(repeat(...)) version lets C code do all the work (and sum even optimizes the summation of floats), making it still quite a bit faster.


来源: stackexchange

问:
Retrieve groups-only from a replace function
I am using named groups in a replacement method, and I want to only work with that groups object, as it may have a variable number of capture groups. As an example:

function reFunc(match, p1, p2, p3, p4, offset, string, groups) {
    console.log('*****', groups);
}
"Bob Jones is the mayor of Dallas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+)/, reFunc);
"Bob Jones is the mayor of Dallas, Texas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+), (?<state>\w+)/, reFunc);```
</div>
</div>
</p>
<p>Is there a way to just ignore everything except the groups in the replacement function, for example something like:</p>
```function reFunc(..., groups) {
    ...
}
```

答:
You can capture all arguments with either the rest parameter syntax or using the arguments reference, and then take the last entry from that:

function reFunc(...groups) {
    groups = groups.pop();
    console.log(groups);
}
"Bob Jones is the mayor of Dallas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+)/, reFunc);
"Bob Jones is the mayor of Dallas, Texas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+), (?<state>\w+)/, reFunc);```

ContentLicense: CC BY-SA 4.0

Body:
I am using named groups in a replacement method, and I want to only work with that groups object, as it may have a variable number of capture groups. As an example:

function reFunc(match, p1, p2, p3, p4, offset, string, groups) {
    console.log('*****', groups);
}
"Bob Jones is the mayor of Dallas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+)/, reFunc);
"Bob Jones is the mayor of Dallas, Texas.".replace(/(?<first>\w+) (?<last>\w+) is the (?<position>\w+) of (?<city>\w+), (?<state>\w+)/, reFunc);

Is there a way to just ignore everything except the groups in the replacement function, for example something like:

function reFunc(..., groups) {
    ...
}


问:
Having trouble getting Blazor to rerender component on change in state shared between components

 Context

I'm following a pattern that's something like https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/ or https://jonhilton.net/blazor-state-management/

So I have two razor components Hen.razor and Basket.razor as child components inside index.razor. A button inside Hen adds to the number of eggs displayed inside Basket.

The button calls a service I've injected called EggService that handles the number of eggs in Basket by storing it in local storage using Blazored.LocalStorage.

 Problem

Clicking the button increases the number of eggs in local storage but doesn't update the Basket component unless I refresh.

 Code

Repository for convenience: https://github.com/EducatedStrikeCart/EggTest/

EggService:

```<code>using Blazored.LocalStorage;

namespace BlazorSandbox.Services
{
    public class EggService
    {
        public event Action OnChange;

        private readonly ILocalStorageService _localStorageService;

        public EggService(ILocalStorageService localStorageService)
        {
            this._localStorageService = localStorageService;
        }

        public async Task<int> GetEggs()
        {
            int currentEggs =  await _localStorageService.GetItemAsync<int>("Eggs");
            return currentEggs;
        }

        public async Task AddEgg()
        {
            int newEggs = await GetEggs();
            if (newEggs == null)
            {
                newEggs = 0;
            } else
            {
                newEggs += 1;
            }
            await _localStorageService.SetItemAsync("Eggs", newEggs);
            OnChange?.Invoke();
        }
    }
}

</code>```

Hen:

```<code>@using BlazorSandbox.Services
@inject EggService EggService

<div>
    <h3>Hen</h3>
<button @onclick="TakeAnEgg">Take an egg</button>
</div>

@code {
    public async Task TakeAnEgg()
    {
        await EggService.AddEgg();
    }
}

</code>```

Egg:

```<code>@using BlazorSandbox.Services
@inject EggService EggService
@implements IDisposable

<div>
    <h3>Basket</h3>
    Eggs: @Eggs
</div>

@code {
    public int Eggs { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Eggs = await EggService.GetEggs();
        EggService.OnChange += StateHasChanged;

    }

    public void Dispose()
    {
        EggService.OnChange -= StateHasChanged;
    }
}
</code>```

Index:

```<code>@page "/"
@using BlazorSandbox.Services
@inject EggService EggService

<h1>
    Eggs!
</h1>
<div class="d-flex flex-row justify-content-around">
    <Hen />
    <Basket />
</div>
@code {

}
</code>```

Program.cs:

```<code>using BlazorSandbox;
using BlazorSandbox.Services;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Blazored.LocalStorage;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<EggService>();
builder.Services.AddBlazoredLocalStorage();

await builder.Build().RunAsync();
</code>```

 Solution

Special thank you to person who deleted their comment. I'm kind of new to asking questions on StackOverflow so I'm sorry if I should've selected your answer as the Answer!
```<code>@code {
    public int Eggs { get; set; }

    protected override void OnInitialized()
    {

        //Subscribe
        EggService.OnChange += UpdateEgg;
        //Set value of Eggs on load
        UpdateEgg();
    }

    public void UpdateEgg()
    {
        // Set value of Eggs to new value and trigger component rerender
        InvokeAsync(async () => {Eggs = await EggService.GetEggs(); StateHasChanged(); });

    }

    public void Dispose()
    {
        // Unsubscribe
        EggService.OnChange -= UpdateEgg;
    }
}
</code>```

答:
There are a few oddities in your code.

```<code>if (newEggs == null)
</code>```

This is an int, so it can never be null. The default value for int is 0. You should be seeing a warning for this.

```<code>Eggs = await EggService.GetEggs();
</code>```

After you set Eggs here, you never update it anywhere in your code! So even if you call StateHasChanged, there is nothing to update.

What you will want to do is keep track of the egg count inside of your EggService and then inside of your Basket component you will need a way to know that the egg count has increased so you can update your Egg property and then call StateHasChanged. Let me know if you need help with this.

Body:
 Context

I'm following a pattern that's something like https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/ or https://jonhilton.net/blazor-state-management/

So I have two razor components Hen.razor and Basket.razor as child components inside index.razor. A button inside Hen adds to the number of eggs displayed inside Basket.

The button calls a service I've injected called EggService that handles the number of eggs in Basket by storing it in local storage using Blazored.LocalStorage.

 Problem

Clicking the button increases the number of eggs in local storage but doesn't update the Basket component unless I refresh.

 Code

Repository for convenience: https://github.com/EducatedStrikeCart/EggTest/

EggService:

using Blazored.LocalStorage;

namespace BlazorSandbox.Services
{
    public class EggService
    {
        public event Action OnChange;

        private readonly ILocalStorageService _localStorageService;

        public EggService(ILocalStorageService localStorageService)
        {
            this._localStorageService = localStorageService;
        }

        public async Task<int> GetEggs()
        {
            int currentEggs =  await _localStorageService.GetItemAsync<int>("Eggs");
            return currentEggs;
        }

        public async Task AddEgg()
        {
            int newEggs = await GetEggs();
            if (newEggs == null)
            {
                newEggs = 0;
            } else
            {
                newEggs += 1;
            }
            await _localStorageService.SetItemAsync("Eggs", newEggs);
            OnChange?.Invoke();
        }
    }
}

Hen:

@using BlazorSandbox.Services
@inject EggService EggService

Hen

<button @onclick="TakeAnEgg">Take an egg</button>

@code {
    public async Task TakeAnEgg()
    {
        await EggService.AddEgg();
    }
}

Egg:

@using BlazorSandbox.Services
@inject EggService EggService
@implements IDisposable

Basket

    Eggs: @Eggs

@code {
    public int Eggs { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Eggs = await EggService.GetEggs();
        EggService.OnChange += StateHasChanged;

    }

    public void Dispose()
    {
        EggService.OnChange -= StateHasChanged;
    }
}

Index:

@page "/"
@using BlazorSandbox.Services
@inject EggService EggService

    Eggs!

    <Hen />
    <Basket />

@code {

}

Program.cs:

using BlazorSandbox;
using BlazorSandbox.Services;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Blazored.LocalStorage;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<EggService>();
builder.Services.AddBlazoredLocalStorage();

await builder.Build().RunAsync();

 Solution

Special thank you to person who deleted their comment. I'm kind of new to asking questions on StackOverflow so I'm sorry if I should've selected your answer as the Answer!

@code {
    public int Eggs { get; set; }

    protected override void OnInitialized()
    {

        //Subscribe
        EggService.OnChange += UpdateEgg;
        //Set value of Eggs on load
        UpdateEgg();
    }

    public void UpdateEgg()
    {
        // Set value of Eggs to new value and trigger component rerender
        InvokeAsync(async () => {Eggs = await EggService.GetEggs(); StateHasChanged(); });

    }

    public void Dispose()
    {
        // Unsubscribe
        EggService.OnChange -= UpdateEgg;
    }
}

Body:
There are a few oddities in your code.

if (newEggs == null)

This is an int, so it can never be null. The default value for int is 0. You should be seeing a warning for this.

Eggs = await EggService.GetEggs();

After you set Eggs here, you never update it anywhere in your code! So even if you call StateHasChanged, there is nothing to update.

What you will want to do is keep track of the egg count inside of your EggService and then inside of your Basket component you will need a way to know that the egg count has increased so you can update your Egg property and then call StateHasChanged. Let me know if you need help with this.


问:
how to rename files you put into a tar archive using linux 'tar'
I'm trying to create a tar archive with a couple files, but rename those files in the archive. Right now I have something like this:

```<code>tar -czvf file1 /some/path/to/file2 file3 etc
</code>```

But I'd like to do something like:

```<code>tar -czvf file1=file1 /some/path/to/file2=file2 file3=path/to/renamedFile3 etc=etc
</code>```

Where, when extracted into directory testDir, you would see the files:

testDir/file1

testDir/file2

testDir/path/to/renamedFile3

testDir/etc

How can I do this?

答:
This question has been up for a while, but for anyone who's looking for another suitable solution:

I've created a fork of the original GNU tar utility with additional support for file name mapping.

Usage example:

> touch myfile.txt
> tar cf file.tar ':myfile.txt:dir/inside/tar/newname.txt'
> tar tvf file.tar
  -rw-rw-r-- user/user      0  2022-02-12 14:27 dir/inside/tar/newname.txt
```
<p>The feature is triggered by prefixing file names with a colon (<code>:</code>) as shown above. A second colon functions as a separator between the source file location and the desired file name inside the archive.</p>
<p><code>:[source file]:[desired name inside the tar]</code></p>
<p>This feature is compatible with the <code>-T</code> (input list from file) flag.</p>
<p><strong>How to compile it</strong></p>
<pre class="lang-sh prettyprint-override"><code>> git clone https://github.com/leso-kn/tar
> cd tar
> ./bootstrap
> ./configure
> make -j4
# Run it
> src/tar --version
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a tar archive with a couple files, but rename those files in the archive. Right now I have something like this:

tar -czvf file1 /some/path/to/file2 file3 etc

But I'd like to do something like:

tar -czvf file1=file1 /some/path/to/file2=file2 file3=path/to/renamedFile3 etc=etc

Where, when extracted into directory testDir, you would see the files:

testDir/file1

testDir/file2

testDir/path/to/renamedFile3

testDir/etc

How can I do this?

Body:
This question has been up for a while, but for anyone who's looking for another suitable solution:

I've created a fork of the original GNU tar utility with additional support for file name mapping.

Usage example:

> touch myfile.txt
> tar cf file.tar ':myfile.txt:dir/inside/tar/newname.txt'
> tar tvf file.tar
  -rw-rw-r-- user/user      0  2022-02-12 14:27 dir/inside/tar/newname.txt

The feature is triggered by prefixing file names with a colon (:) as shown above. A second colon functions as a separator between the source file location and the desired file name inside the archive.

:[source file]:[desired name inside the tar]

This feature is compatible with the -T (input list from file) flag.

How to compile it

> git clone https://github.com/leso-kn/tar
> cd tar
> ./bootstrap
> ./configure
> make -j4
# Run it
> src/tar --version


问:
Create data.frame with count function
I have a data table about movies with approximately 1600000 rows and 9 columns. I want to create a table that shows the number of movies released per year. This table should include two columns of my current data frame: year and n_movies. The first column should contain the year, the second the number of movies in that year, and the third which would be a new column, counting up n_movies by the first year until the last year.

I manage to get the first two columns from my current data table, but I do not know how to get the third column, which should count up n_movies by first year.

I have tried the following code:

```<code>df.movies <- data.frame(dt.movies.actor$year,
                        dt.movies.actor$n_movies,
                        count(dt.movies.actor$n_movies))
</code>```

Below an example of my current data frame.

```<code>                                           movie                 actor year duration adult_movie rating votes n_movies
 1:                     The Gay Divorcee (1934) Fred Astaire (b.1899) 1934      107           0    7.5  6446     7524
 2:                              Roberta (1935) Fred Astaire (b.1899) 1935      106           0    7.1  2761     7708
 3:                              Top Hat (1935) Fred Astaire (b.1899) 1935      101           0    7.8 16254     7708
 4:                     Follow the Fleet (1936) Fred Astaire (b.1899) 1936      110           0    7.2  3745     8071
 5:                           Swing Time (1936) Fred Astaire (b.1899) 1936      103           0    7.6 11487     8071
 6:                 A Damsel in Distress (1937) Fred Astaire (b.1899) 1937      101           0    6.8  1657     8165
 7:                       Shall We Dance (1937) Fred Astaire (b.1899) 1937      109           0    7.5  6143     8165
 8:                             Carefree (1938) Fred Astaire (b.1899) 1938       83           0    7.1  3070     8170
 9: The Story of Vernon and Irene Castle (1939) Fred Astaire (b.1899) 1939       93           0    6.9  2145     7846
10:              Broadway Melody of 1940 (1940) Fred Astaire (b.1899) 1940      102           0    7.4  2001     7455
11:                        Second Chorus (1940) Fred Astaire (b.1899) 1940       84           0    5.8  1211     7455
12:                You'll Never Get Rich (1941) Fred Astaire (b.1899) 1941       88           0    6.8  1995     6425
13:                          Holiday Inn (1942) Fred Astaire (b.1899) 1942      100           0    7.4 12406     5659
14:              You Were Never Lovelier (1942) Fred Astaire (b.1899) 1942       97           0    7.3  3012     5659
15:                  The Sky's the Limit (1943) Fred Astaire (b.1899) 1943       89           0    6.4   770     5203
16:                Yolanda and the Thief (1945) Fred Astaire (b.1899) 1945      108           0    6.0   793     4229
17:                           Blue Skies (1946) Fred Astaire (b.1899) 1946       99           0    6.5  1172     5206
18:                     Ziegfeld Follies (1945) Fred Astaire (b.1899) 1945      110           0    6.5  2727     4229
19:                        Easter Parade (1948) Fred Astaire (b.1899) 1948      103           0    7.4  8007     6378
20:             The Barkleys of Broadway (1949) Fred Astaire (b.1899) 1949      109           0    7.0  2592     6921 ```
```

Title: Create data.frame with count function

Body:
I have a data table about movies with approximately 1600000 rows and 9 columns. I want to create a table that shows the number of movies released per year. This table should include two columns of my current data frame: year and n_movies. The first column should contain the year, the second the number of movies in that year, and the third which would be a new column, counting up n_movies by the first year until the last year.

I manage to get the first two columns from my current data table, but I do not know how to get the third column, which should count up n_movies by first year.

I have tried the following code:

df.movies <- data.frame(dt.movies.actor$year,
                        dt.movies.actor$n_movies,
                        count(dt.movies.actor$n_movies))

Below an example of my current data frame.

                                           movie                 actor year duration adult_movie rating votes n_movies
 1:                     The Gay Divorcee (1934) Fred Astaire (b.1899) 1934      107           0    7.5  6446     7524
 2:                              Roberta (1935) Fred Astaire (b.1899) 1935      106           0    7.1  2761     7708
 3:                              Top Hat (1935) Fred Astaire (b.1899) 1935      101           0    7.8 16254     7708
 4:                     Follow the Fleet (1936) Fred Astaire (b.1899) 1936      110           0    7.2  3745     8071
 5:                           Swing Time (1936) Fred Astaire (b.1899) 1936      103           0    7.6 11487     8071
 6:                 A Damsel in Distress (1937) Fred Astaire (b.1899) 1937      101           0    6.8  1657     8165
 7:                       Shall We Dance (1937) Fred Astaire (b.1899) 1937      109           0    7.5  6143     8165
 8:                             Carefree (1938) Fred Astaire (b.1899) 1938       83           0    7.1  3070     8170
 9: The Story of Vernon and Irene Castle (1939) Fred Astaire (b.1899) 1939       93           0    6.9  2145     7846
10:              Broadway Melody of 1940 (1940) Fred Astaire (b.1899) 1940      102           0    7.4  2001     7455
11:                        Second Chorus (1940) Fred Astaire (b.1899) 1940       84           0    5.8  1211     7455
12:                You'll Never Get Rich (1941) Fred Astaire (b.1899) 1941       88           0    6.8  1995     6425
13:                          Holiday Inn (1942) Fred Astaire (b.1899) 1942      100           0    7.4 12406     5659
14:              You Were Never Lovelier (1942) Fred Astaire (b.1899) 1942       97           0    7.3  3012     5659
15:                  The Sky's the Limit (1943) Fred Astaire (b.1899) 1943       89           0    6.4   770     5203
16:                Yolanda and the Thief (1945) Fred Astaire (b.1899) 1945      108           0    6.0   793     4229
17:                           Blue Skies (1946) Fred Astaire (b.1899) 1946       99           0    6.5  1172     5206
18:                     Ziegfeld Follies (1945) Fred Astaire (b.1899) 1945      110           0    6.5  2727     4229
19:                        Easter Parade (1948) Fred Astaire (b.1899) 1948      103           0    7.4  8007     6378
20:             The Barkleys of Broadway (1949) Fred Astaire (b.1899) 1949      109           0    7.0  2592     6921 ```

Body:
Are you looking for such a solution?

library(dplyr)

df %>%
  count(year, n_movies)

    year n_movies     n
   <dbl>    <dbl> <int>
 1  1934     7524     1
 2  1935     7708     2
 3  1936     8071     2
 4  1937     8165     2
 5  1938     8170     1
 6  1939     7846     1
 7  1940     7455     2
 8  1941     6425     1
 9  1942     5659     2
10  1943     5203     1
11  1945     4229     2
12  1946     5206     1
13  1948     6378     1

data:

df <- structure(list(movie = c("The Gay Divorcee (1934)", "Roberta (1935)",
"Top Hat (1935)", "Follow the Fleet (1936)", "Swing Time (1936)",
"A Damsel in Distress (1937)", "Shall We Dance (1937)", "Carefree (1938)",
"The Story of Vernon and Irene Castle (1939)", "Broadway Melody of 1940 (1940)",
"Second Chorus (1940)", "You'll Never Get Rich (1941)", "Holiday Inn (1942)",
"You Were Never Lovelier (1942)", "The Sky's the Limit (1943)",
"Yolanda and the Thief (1945)", "Blue Skies (1946)", "Ziegfeld Follies (1945)",
"Easter Parade (1948)"), actor = c("Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)", "Fred Astaire (b.1899)",
"Fred Astaire (b.1899)", "Fred Astaire (b.1899)"), year = c(1934,
1935, 1935, 1936, 1936, 1937, 1937, 1938, 1939, 1940, 1940, 1941,
1942, 1942, 1943, 1945, 1946, 1945, 1948), duration = c(107,
106, 101, 110, 103, 101, 109, 83, 93, 102, 84, 88, 100, 97, 89,
108, 99, 110, 103), adult_movie = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), rating = c(7.5, 7.1, 7.8, 7.2,
7.6, 6.8, 7.5, 7.1, 6.9, 7.4, 5.8, 6.8, 7.4, 7.3, 6.4, 6, 6.5,
6.5, 7.4), votes = c(644, 276, 1625, 374, 1148, 165, 614, 307,
214, 200, 121, 199, 1240, 301, 77, 79, 117, 272, 800), n_movies = c(7524,
7708, 7708, 8071, 8071, 8165, 8165, 8170, 7846, 7455, 7455, 6425,
5659, 5659, 5203, 4229, 5206, 4229, 6378)), row.names = c(NA,
-19L), spec = structure(list(cols = list(movie = structure(list(), class = c("collector_character",
"collector")), actor = structure(list(), class = c("collector_character",
"collector")), year = structure(list(), class = c("collector_double",
"collector")), duration = structure(list(), class = c("collector_double",
"collector")), adult_movie = structure(list(), class = c("collector_double",
"collector")), rating = structure(list(), class = c("collector_double",
"collector")), votes = structure(list(), class = c("collector_double",
"collector")), n_movies = structure(list(), class = c("collector_double",
"collector")), ...9 = structure(list(), class = c("collector_skip",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x00000190f1f5db30>, class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))


问:
Should virtual dispatch happen when a virtual method is called within a virtual method using object?
```<code>struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};
</code>```

Now we call foo() using an object of B as,

```<code>B obj;
obj.foo();  // calls B::bar()
</code>```

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).

答:
It must be a virtual call. The code that you're compiling cannot know if there's not a more-derived class that it actually is that has overridden the other function.

Note that this assumes that you're compiling these separately. If the compiler inlines the call to foo() (due to its static type being known) it'll also inline the call to bar().

Body:
struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};

Now we call foo() using an object of B as,

B obj;
obj.foo();  // calls B::bar()

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).


问:
Direct User to HTML page after Login
I am trying to simply direct a user to the correct html page after they login. I'm doing this as learning and I know a database with API's is a better method, however in my scenario for now, the User and Password (accounts) are hardcoded.

login.ejs

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Login Page</title>
<link rel="stylesheet" href="css/login_style.css">

Login

    <form id="login-form">

      <input type="text" id="username" name="username" placeholder="Username" required>

      <input type="password" id="password" name="password" placeholder="Password" required>

      <input type="submit" value="Login" onclick="validate()">

   </form>

WMGSS - Calendar Board

```
</div>
</div>
</p>
<p>loginScript.js</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const app = express()

function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.location = ("index.ejs")
        return false
    }
    else(null)

}</code>```

server.js
This states the pages that can be connected to with the correct HTML as their relation.

app.get('/tutorview', (req, res) => {
    res.render('index.ejs')
})

app.get('/studentview',(req, res) => {
    res.render('student_page.ejs')
})

app.get('/', (req, res) => {
    res.render('login.ejs')
})

app.post('/', passport.authenticate('local', {
    successRedirect: '/studentview',
    failureRedirect: '/',
    failureFlash: true
}))

function setUser(req, res, next) {
    const userId = req.body.userId
    if (userId) {
        req.user = users.find(user => user.id === userId)
    }
    next()
}

app.listen(3000)```

答:
I figured out what was needed, instead of:

const app = express()

function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.location = ("index.ejs")
        return false
    }
    else(null)

}```
</div>
</div>
</p>
<p>I have done</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.open("/tutorview")
    }</code>```

Title: Direct User to HTML page after Login

Body:
I am trying to simply direct a user to the correct html page after they login. I'm doing this as learning and I know a database with API's is a better method, however in my scenario for now, the User and Password (accounts) are hardcoded.

login.ejs

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Login Page</title>
<link rel="stylesheet" href="css/login_style.css">

Login

    <form id="login-form">

      <input type="text" id="username" name="username" placeholder="Username" required>

      <input type="password" id="password" name="password" placeholder="Password" required>

      <input type="submit" value="Login" onclick="validate()">

   </form>

WMGSS - Calendar Board

loginScript.js

const app = express()

function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.location = ("index.ejs")
        return false
    }
    else(null)

}

server.js
This states the pages that can be connected to with the correct HTML as their relation.

app.get('/tutorview', (req, res) => {
    res.render('index.ejs')
})

app.get('/studentview',(req, res) => {
    res.render('student_page.ejs')
})

app.get('/', (req, res) => {
    res.render('login.ejs')
})

app.post('/', passport.authenticate('local', {
    successRedirect: '/studentview',
    failureRedirect: '/',
    failureFlash: true
}))

function setUser(req, res, next) {
    const userId = req.body.userId
    if (userId) {
        req.user = users.find(user => user.id === userId)
    }
    next()
}

app.listen(3000)

Body:
I figured out what was needed, instead of:

const app = express()

function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.location = ("index.ejs")
        return false
    }
    else(null)

}

I have done

function validate(){
    var username=document.getElementById("username").value
    var password=document.getElementById("password").value

    if(username =="Young"&& password=="Park"){
        window.open("/tutorview")
    }


问:
Why does file size remain static despite ImageSharp JpegEncoder.Quality setting?
I’m trying to reduce the size of photo thumbnails (100x75 px) generated with SixLabors ImageSharp, using the JpegEncoder. However the images don’t seem to vary in file size much, despite quality level used.

In my legacy System.Drawing code, when I used an ImageCodecInfo encoder and an EncoderParameter for Imaging.Encoder.Quality set to 30, I’d receive nice low-quality images — about 2k. Perfect for thumbnails.

With ImageSharp, no matter what I set the SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder.Quality to, the images are always about 24k. Quality can be set 0-100, and the visible quality goes down, but the file size doesn’t dip much — even when the jpegs are comically compressed. Always about 24k.

Can anyone explain why this is? Why does an image at .Quality 5 get written to about the same size as 90, despite dramatic visible compression? Are there other properties I need to set with this encoder? Should I be using a different format for better results?

```<code>image.Mutate(x => x.Resize(width, height));

SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder encoder = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();

encoder.Quality = 30; //0-100. 30 was my System.Drawing code.

image.Save(thumbnailPath, encoder);
</code>```

EDIT: My legacy code may have "extracted" the thumbnail image from the source image, via System.Drawing.GetThumbnailImage, then saved that. These thumbs may be very small to begin with. Sounds like this is different than scaling a new thumbnail from the source image? Legacy code:

```<code>Image theThumb = theImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);

//set up parameter for compression quality
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 30);

//codec to use
ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders()[1]; //"image/jpeg"

theThumb.Save(thumbnailPath, encoder, encoderParameters);
</code>```

...Seems like the MS documentation is saying about the same -- extracted thumbnails are different than scaling the source image:

https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image.getthumbnailimage?view=dotnet-plat-ext-6.0

If the Image contains an embedded thumbnail image, this method
retrieves the embedded thumbnail and scales it to the requested size.
If the Image does not contain an embedded thumbnail image, this method
creates a thumbnail image by scaling the main image.

(I'm new to .NET 6 tho, so not sure what "Platform extensions" are and if this will work in a .NET Core library. Looks like they may be part of the "Windows Compatibility Pack" NuGet package, but is for Windows-only deployments. Since I'm deploying on Mac this System.Drawing.GetThumbnailImage may not work -- thus working with ImageSharp.)

EDIT: The ImageSharp code is scaling a new image from the source, and it appears to retain EXIF data. My legacy code thumbs (extracted from the source) don't contain EXIF data. This may be the source of the bloat. Especially if there is a thumbnail in the EXIF data itself.

I'll try finding a method or library to scrub the EXIF prior to saving a new scaled thumbnail, and see if that is smaller.

Thanks!

答:
It was the XMP metadata. Resizing source images down to thumbnails maintains their meta collections. You must remove it prior to saving. Alternatively, use the method to extract the actual thumbnail from the metadata rather than create it new.

Related question on the EXIF removal:

How do I clear an Image's EXIF data with ImageSharp?

Related question on extracting thumbnails:

How do I extract a jpeg's EXIF thumbnail using ImageSharp?

Body:
I’m trying to reduce the size of photo thumbnails (100x75 px) generated with SixLabors ImageSharp, using the JpegEncoder. However the images don’t seem to vary in file size much, despite quality level used.

In my legacy System.Drawing code, when I used an ImageCodecInfo encoder and an EncoderParameter for Imaging.Encoder.Quality set to 30, I’d receive nice low-quality images — about 2k. Perfect for thumbnails.

With ImageSharp, no matter what I set the SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder.Quality to, the images are always about 24k. Quality can be set 0-100, and the visible quality goes down, but the file size doesn’t dip much — even when the jpegs are comically compressed. Always about 24k.

Can anyone explain why this is? Why does an image at .Quality 5 get written to about the same size as 90, despite dramatic visible compression? Are there other properties I need to set with this encoder? Should I be using a different format for better results?

image.Mutate(x => x.Resize(width, height));

SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder encoder = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();

encoder.Quality = 30; //0-100. 30 was my System.Drawing code.

image.Save(thumbnailPath, encoder);

EDIT: My legacy code may have "extracted" the thumbnail image from the source image, via System.Drawing.GetThumbnailImage, then saved that. These thumbs may be very small to begin with. Sounds like this is different than scaling a new thumbnail from the source image? Legacy code:

Image theThumb = theImage.GetThumbnailImage(width, height, myCallback, IntPtr.Zero);

//set up parameter for compression quality
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 30);

//codec to use
ImageCodecInfo encoder = ImageCodecInfo.GetImageEncoders()[1]; //"image/jpeg"

theThumb.Save(thumbnailPath, encoder, encoderParameters);

...Seems like the MS documentation is saying about the same -- extracted thumbnails are different than scaling the source image:

https://learn.microsoft.com/en-us/dotnet/api/system.drawing.image.getthumbnailimage?view=dotnet-plat-ext-6.0

If the Image contains an embedded thumbnail image, this method
retrieves the embedded thumbnail and scales it to the requested size.
If the Image does not contain an embedded thumbnail image, this method
creates a thumbnail image by scaling the main image.

(I'm new to .NET 6 tho, so not sure what "Platform extensions" are and if this will work in a .NET Core library. Looks like they may be part of the "Windows Compatibility Pack" NuGet package, but is for Windows-only deployments. Since I'm deploying on Mac this System.Drawing.GetThumbnailImage may not work -- thus working with ImageSharp.)

EDIT: The ImageSharp code is scaling a new image from the source, and it appears to retain EXIF data. My legacy code thumbs (extracted from the source) don't contain EXIF data. This may be the source of the bloat. Especially if there is a thumbnail in the EXIF data itself.

I'll try finding a method or library to scrub the EXIF prior to saving a new scaled thumbnail, and see if that is smaller.

Thanks!


Title: how to split time stamped data as train and test

Body:
I have a dataset with timestamped given below:

date        type, price
1990-01-01, 'A', 100
1990-01-02, 'A', 200
1990-01-03, 'A', 300
1990-01-04, 'A', 400
1990-01-05, 'A', 500
1990-01-06, 'A', 600
1990-01-07, 'A', 700
1990-01-08, 'A', 800
1990-01-09, 'A', 900
1990-01-10, 'A', 1000
1990-01-11, 'B', 1100
1990-01-12, 'B', 1200
1990-01-13, 'B', 1300
1990-01-14, 'B', 1400
1990-01-15, 'B', 1500

I am trying to split this data as train and test with keeping the order based on date. If the split ratio is 0.8 for train and test, the expected output is supposed to be the following data:
train_data:

date        type, price
1990-01-01, 'A', 100
1990-01-02, 'A', 200
1990-01-03, 'A', 300
1990-01-04, 'A', 400
1990-01-05, 'A', 500
1990-01-06, 'A', 600
1990-01-07, 'A', 700
1990-01-08, 'A', 800
1990-01-11, 'B', 1100
1990-01-12, 'B', 1200
1990-01-13, 'B', 1300
1990-01-14, 'B', 1400

test_data:

    date        type, price
    1990-01-09, 'A', 900
    1990-01-10, 'A', 1000
    1990-01-15, 'B', 1500

Is there any way to do this in a pythonic way?

Body:
transform & transform

# grouper
g = df.groupby("type", sort=False).type

# first is 1..size second is [size, size, ...]
sample_nos  = g.transform("cumcount").add(1)
group_sizes = g.transform("size")

# belongs to training or not
train_mask = sample_nos <= 0.8 * group_sizes

# then choose so
train_data = df[train_mask].copy()
test_data  = df[~train_mask].copy()

train_data

          date type  price
0   1990-01-01  'A'    100
1   1990-01-02  'A'    200
2   1990-01-03  'A'    300
3   1990-01-04  'A'    400
4   1990-01-05  'A'    500
5   1990-01-06  'A'    600
6   1990-01-07  'A'    700
7   1990-01-08  'A'    800
10  1990-01-11  'B'   1100
11  1990-01-12  'B'   1200
12  1990-01-13  'B'   1300
13  1990-01-14  'B'   1400

and

test_data

          date type  price
8   1990-01-09  'A'    900
9   1990-01-10  'A'   1000
14  1990-01-15  'B'   1500


问:
Access a saved ipython notebook on an external drive (mac)
I'm trying to access an ipython notebook that was saved to an external HD.  Is this possible?

Specifically, I saved an ipython notebook to a dropbox folder (locally synced) on one computer.  I am now trying to open that ipython notebook on another computer that syncs to the same dropbox account -- only computer b's dropbox folder is on an external HD.

This seems so basic, but I've looked everywhere for an answer on this and am afraid I'm missing something more fundamental here.

答:
From terminal, if you have Anaconda installed, type:</p>
```<code>jupyter notebook --notebook-dir=/Volumes/NameofExternalDrive
</code>```

Body:
From terminal, if you have Anaconda installed, type:

jupyter notebook --notebook-dir=/Volumes/NameofExternalDrive


问:
Option element not found while selecting from the dropdown
Not able to click the dropdown even after providing correct xpath. Please find below the code for your reference. Here I am using Select class.

BasePage:

```<code>def SelectSumInsured(self,sumvalue):
    sumdropdown = Select(self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']"))
    suminsured = sumdropdown.select_by_value(sumvalue)
    return suminsured
</code>```

Page Object Screen:

```<code>class HealthInsurancePage(BasePage):

    def __init__(self, driver):
        super().__init__(driver)

    def SelectSum(self,sumvalue):
        self.SelectSumInsured(sumvalue)
</code>```

Test Script:

Now in the testscript, I have used pytest parameterized for the data driven approach which should select the dropdown value as per my data I have provided in the excel sheet.

```<code>class Test_RSA_Health(BaseTest):
@pytest.mark.parametrize("pin,sumvalue", dataProvider.get_data("excelsheetname"))
def test_RSA_Health(self,pin,sumvalue):
    home = HomePage(self.driver)
    healthinsuranepage = home.SelectHealth()
    self.VerifyPresence_PinCodeTextBox()
    healthinsuranepage.landing_page()
    healthinsuranepage.InputPin(pin)
    healthinsuranepage.SelectSum(str(sumvalue))
</code>```

Error:
During the execution, I have seen that the dropdown is not even clicked and I am getting the below error for your reference

```<code>selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000
</code>```

But if I use simple click method using the same xpath, the drop down is clicking successfully.

```<code>self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']").click
</code>```

My question is why the dropdown is not clicking using the Select class?

Full error trace for your reference if you need:

```<code>self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x000002A63A562DF0>, pin = 560008, sumvalue = 700000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(str(sumvalue))

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:23: in SelectSum
    self.SelectSumInsured(sumvalue)
..\Pages\BasePage.py:79: in SelectSumInsured
    suminsured = sumdropdown.select_by_value(sumvalue)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x000002A63A56D7F0>, value = '700000'

    def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specified value in SELECT
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
>           raise NoSuchElementException("Cannot locate option with value: %s" % value)
E           selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:87: NoSuchElementException
---------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------
INFO     Pages.BasePage:BasePage.py:27 Clicking on an Element health_XPATH
INFO     Pages.BasePage:BasePage.py:60 Typing in an Element pin_XPATH entered the value as : 560008
_ Test_RSA_Health.test_RSA_Health[560008-500000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-SaltLake-180-75-testn
omineefirst-testnomineelast-1/2/1992] _

self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x000002A63A63D4F0>, pin = 560008, sumvalue = 500000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(str(sumvalue))

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:23: in SelectSum
    self.SelectSumInsured(sumvalue)
..\Pages\BasePage.py:79: in SelectSumInsured
    suminsured = sumdropdown.select_by_value(sumvalue)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x000002A63A56DC40>, value = '500000'

    def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specified value in SELECT
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
>           raise NoSuchElementException("Cannot locate option with value: %s" % value)
E           selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 500000

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:87: NoSuchElementException
</code>```

As per request, following is the element for your reference

```<code><select _ngcontent-tpo-c7="" formcontrolname="income" class="ng-pristine ng-valid ng-touched">
<!---->
<option _ngcontent-tpo-c7="" class="ng-star-inserted">100000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">200000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">300000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">400000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">700000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">1000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">1500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">2000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">2500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">3000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">4000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">5000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">7500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">10000000</option>
</select>
</code>```

The xpath I have written is

```<code>//select[@formcontrolname = 'income'] `or` `//select[@class='ng-pristine ng-valid ng-touched']`
</code>```

答:
This error message...

```<code>raise NoSuchElementException("Cannot locate option with value: %s" % value)
selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000
</code>```

and this error message...

```<code>raise NoSuchElementException("Cannot locate option with value: %s" % value)
selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 500000
</code>```

...implies that the html-select element have no descendent <option> elements with value attribute as 700000 or 500000.

You need to crosscheck if the <select> have the following structure:

```<code><select formcontrolname="income" ...>
    <option value="700000" ...>foo</option>
    <option value="500000" ...>bar</option>
</select>
</code>```

Conclusion

As you mentioned seen that the dropdown is not even clicked, this implies that the locator strategies doesn't identifies the desired select element uniquely.

Body:
Not able to click the dropdown even after providing correct xpath. Please find below the code for your reference. Here I am using Select class.

BasePage:

def SelectSumInsured(self,sumvalue):
    sumdropdown = Select(self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']"))
    suminsured = sumdropdown.select_by_value(sumvalue)
    return suminsured

Page Object Screen:

class HealthInsurancePage(BasePage):

    def __init__(self, driver):
        super().__init__(driver)

    def SelectSum(self,sumvalue):
        self.SelectSumInsured(sumvalue)

Test Script:

Now in the testscript, I have used pytest parameterized for the data driven approach which should select the dropdown value as per my data I have provided in the excel sheet.

class Test_RSA_Health(BaseTest):
@pytest.mark.parametrize("pin,sumvalue", dataProvider.get_data("excelsheetname"))
def test_RSA_Health(self,pin,sumvalue):
    home = HomePage(self.driver)
    healthinsuranepage = home.SelectHealth()
    self.VerifyPresence_PinCodeTextBox()
    healthinsuranepage.landing_page()
    healthinsuranepage.InputPin(pin)
    healthinsuranepage.SelectSum(str(sumvalue))

Error:
During the execution, I have seen that the dropdown is not even clicked and I am getting the below error for your reference

selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000

But if I use simple click method using the same xpath, the drop down is clicking successfully.

self.driver.find_element(By.XPATH, "//select[@formcontrolname = 'income']").click

My question is why the dropdown is not clicking using the Select class?

Full error trace for your reference if you need:

self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x000002A63A562DF0>, pin = 560008, sumvalue = 700000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(str(sumvalue))

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:23: in SelectSum
    self.SelectSumInsured(sumvalue)
..\Pages\BasePage.py:79: in SelectSumInsured
    suminsured = sumdropdown.select_by_value(sumvalue)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x000002A63A56D7F0>, value = '700000'

    def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specified value in SELECT
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
>           raise NoSuchElementException("Cannot locate option with value: %s" % value)
E           selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:87: NoSuchElementException
---------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------
INFO     Pages.BasePage:BasePage.py:27 Clicking on an Element health_XPATH
INFO     Pages.BasePage:BasePage.py:60 Typing in an Element pin_XPATH entered the value as : 560008
_ Test_RSA_Health.test_RSA_Health[560008-500000-9836680067-30-Apratim Chaudhuri-apratim.chaudhuri@riskcovr.com-Apratim-Chaudhuri-1/2/1992-1000000-AMHPC9725D-QA-GD-SaltLake-180-75-testn
omineefirst-testnomineelast-1/2/1992] _

self = <TestCases.test_RSA_Health.Test_RSA_Health object at 0x000002A63A63D4F0>, pin = 560008, sumvalue = 500000, mobileno = 9836680067, selfage = 30, fullname = 'Apratim Chaudhuri'
email = 'apratim.chaudhuri@riskcovr.com', firstname = 'Apratim', lastname = 'Chaudhuri', dob = '1/2/1992', income = 1000000, pan = 'AMHPC9725D', designation = 'QA', add1 = 'GD'
add2 = 'SaltLake', height = 180, weight = 75, nomfirstname = 'testnomineefirst', nomlastname = 'testnomineelast', nomdob = '1/2/1992'

    @pytest.mark.parametrize("pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob", dataP
rovider.get_data("rsa_health"))
    def test_RSA_Health(self,pin,sumvalue,mobileno,selfage,fullname,email,firstname,lastname,dob,income,pan,designation,add1,add2,height,weight,nomfirstname,nomlastname,nomdob):
        home = HomePage(self.driver)
        healthinsuranepage = home.SelectHealth()
        self.VerifyPresence_PinCodeTextBox()
        healthinsuranepage.landing_page()
        healthinsuranepage.InputPin(pin)
>       healthinsuranepage.SelectSum(str(sumvalue))

test_RSA_Health.py:17:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\Pages\HealthInsurancePage.py:23: in SelectSum
    self.SelectSumInsured(sumvalue)
..\Pages\BasePage.py:79: in SelectSumInsured
    suminsured = sumdropdown.select_by_value(sumvalue)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.support.select.Select object at 0x000002A63A56DC40>, value = '500000'

    def select_by_value(self, value):
        """Select all options that have a value matching the argument. That is, when given "foo" this
           would select an option like:

           <option value="foo">Bar</option>

           :Args:
            - value - The value to match against

           throws NoSuchElementException If there is no option with specified value in SELECT
           """
        css = "option[value =%s]" % self._escapeString(value)
        opts = self._el.find_elements(By.CSS_SELECTOR, css)
        matched = False
        for opt in opts:
            self._setSelected(opt)
            if not self.is_multiple:
                return
            matched = True
        if not matched:
>           raise NoSuchElementException("Cannot locate option with value: %s" % value)
E           selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 500000

..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\select.py:87: NoSuchElementException

As per request, following is the element for your reference

<select _ngcontent-tpo-c7="" formcontrolname="income" class="ng-pristine ng-valid ng-touched">

<option _ngcontent-tpo-c7="" class="ng-star-inserted">100000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">200000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">300000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">400000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">700000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">1000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">1500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">2000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">2500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">3000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">4000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">5000000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">7500000</option>
<option _ngcontent-tpo-c7="" class="ng-star-inserted">10000000</option>
</select>

The xpath I have written is

//select[@formcontrolname = 'income'] `or` `//select[@class='ng-pristine ng-valid ng-touched']`

Body:
This error message...

raise NoSuchElementException("Cannot locate option with value: %s" % value)
selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 700000

and this error message...

raise NoSuchElementException("Cannot locate option with value: %s" % value)
selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 500000

...implies that the html-select element have no descendent <option> elements with value attribute as 700000 or 500000.

You need to crosscheck if the <select> have the following structure:

<select formcontrolname="income" ...>
    <option value="700000" ...>foo</option>
    <option value="500000" ...>bar</option>
</select>

Conclusion

As you mentioned seen that the dropdown is not even clicked, this implies that the locator strategies doesn't identifies the desired select element uniquely.


问:
How do I format and post Json in the post request body (RestSharp)
I don't understand how to sent this json in the request body.
Here is the json from the postman create collection body (https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-049042b8-447f-4f71-8b79-ae978cf40a04):

```<code>{
    "collection": {
        "info": {
            "name": "Sample Collection 909",
            "description": "This is just a sample collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": [
            {
                "name": "This is a folder",
                "item": [
                    {
                        "name": "Sample POST Request",
                        "request": {
                            "url": "https://postman-echo.com/post",
                            "method": "POST",
                            "header": [
                                {
                                    "key": "Content-Type",
                                    "value": "application/json"
                                }
                            ],
                            "body": {
                                "mode": "raw",
                                "raw": "{\"data\": \"123\"}"
                            },
                            "description": "This is a sample POST Request"
                        }
                    }
                ]
            },
            {
                "name": "Sample GET Request",
                "request": {
                    "url": "https://postman-echo/get",
                    "method": "GET",
                    "description": "This is a sample GET Request"
                }
            }
        ]
    }
}
</code>```

Json above works fine using the Postman app, my attempt at it:

```<code>RestSharp.Settings.Init("collections", Method.Post);
RestSharp.Settings.AddHeader("X-Api-Key", "I hid my key");
RestSharp.Settings.restRequest.RequestFormat = DataFormat.Json;

RestSharp.Settings.restRequest.AddParameter("application/json; charset=utf-8", "{\n    \"collection\": {\n        \"info\": {\n            \"name\": \"Sample Collection 909\",\n            \"description\": \"This is just a sample collection.\",\n            \"schema\": \"https://schema.getpostman.com/json/collection/v2.1.0/collection.json\"\n        },\n        \"item\": [\n            {\n                \"name\": \"This is a folder\",\n                \"item\": [\n                    {\n                        \"name\": \"Sample POST Request\",\n                        \"request\": {\n                            \"url\": \"https://postman-echo.com/post\",\n                            \"method\": \"POST\",\n                            \"header\": [\n                                {\n                                    \"key\": \"Content-Type\",\n                                    \"value\": \"application/json\"\n                                }\n                            ],\n                            \"body\": {\n                                \"mode\": \"raw\",\n                                \"raw\": \"{\\\"data\\\": \\\"123\\\"}\"\n                            },\n                            \"description\": \"This is a sample POST Request\"\n                        }\n                    }\n                ]\n            },\n            {\n                \"name\": \"Sample GET Request\",\n                \"request\": {\n                    \"url\": \"https://postman-echo/get\",\n                    \"method\": \"GET\",\n                    \"description\": \"This is a sample GET Request\"\n                }\n            }\n        ]\n    }\n}",ParameterType.RequestBody);

var response = RestSharp.Settings.restClient.ExecuteAsync(RestSharp.Settings.restRequest).Result;

Console.WriteLine("Returned http status code is: " + response.StatusCode + " expected OK");

Assert.IsTrue((int)response.StatusCode == 200);
</code>```

答:
Have a look at the RestSharp quick start guide.  There are a couple of methods that could come in useful for you.

If you have an object to serialize you can use AddJsonBody() to post Json.  This is taken from that guide:

For example, you'd only need these lines to make a request with
JSON body:

var request = new RestRequest("address/update").AddJsonBody(updatedAddress);
var response = await client.PostAsync<AddressUpdateResponse>(request);
```
</blockquote>
<p><code>AddJsonBody</code> automatically sets the <code>ContentType</code> and <code>DataFormat</code>:</p>
<blockquote>
<p>There is no need to set the <code>Content-Type</code> or add the <code>DataFormat</code>
parameter to the request when using those methods, RestSharp will do
it for you.</p>
</blockquote>
<hr />
<p>However, since you already have Json as a string, the correct method to use is <code>AddStringBody()</code> (credit to Alexey Zimarev for the comment). You need to pass the content type:</p>
<blockquote>
<p>If you have a pre-serialized payload like a JSON string, you can use
<code>AddStringBody</code> to add it as a body parameter. You need to specify the
content type, so the remote endpoint knows what to do with the request
body. For example:</p>
``````
const json = // your json string;
request.AddStringBody(json, ContentType.Json);
```
```

I'd recommend awaiting the response too, as in the examples above, rather than using .Result.

Body:
I don't understand how to sent this json in the request body.
Here is the json from the postman create collection body (https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-049042b8-447f-4f71-8b79-ae978cf40a04):

{
    "collection": {
        "info": {
            "name": "Sample Collection 909",
            "description": "This is just a sample collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
        },
        "item": [
            {
                "name": "This is a folder",
                "item": [
                    {
                        "name": "Sample POST Request",
                        "request": {
                            "url": "https://postman-echo.com/post",
                            "method": "POST",
                            "header": [
                                {
                                    "key": "Content-Type",
                                    "value": "application/json"
                                }
                            ],
                            "body": {
                                "mode": "raw",
                                "raw": "{\"data\": \"123\"}"
                            },
                            "description": "This is a sample POST Request"
                        }
                    }
                ]
            },
            {
                "name": "Sample GET Request",
                "request": {
                    "url": "https://postman-echo/get",
                    "method": "GET",
                    "description": "This is a sample GET Request"
                }
            }
        ]
    }
}

Json above works fine using the Postman app, my attempt at it:

RestSharp.Settings.Init("collections", Method.Post);
RestSharp.Settings.AddHeader("X-Api-Key", "I hid my key");
RestSharp.Settings.restRequest.RequestFormat = DataFormat.Json;

RestSharp.Settings.restRequest.AddParameter("application/json; charset=utf-8", "{\n    \"collection\": {\n        \"info\": {\n            \"name\": \"Sample Collection 909\",\n            \"description\": \"This is just a sample collection.\",\n            \"schema\": \"https://schema.getpostman.com/json/collection/v2.1.0/collection.json\"\n        },\n        \"item\": [\n            {\n                \"name\": \"This is a folder\",\n                \"item\": [\n                    {\n                        \"name\": \"Sample POST Request\",\n                        \"request\": {\n                            \"url\": \"https://postman-echo.com/post\",\n                            \"method\": \"POST\",\n                            \"header\": [\n                                {\n                                    \"key\": \"Content-Type\",\n                                    \"value\": \"application/json\"\n                                }\n                            ],\n                            \"body\": {\n                                \"mode\": \"raw\",\n                                \"raw\": \"{\\\"data\\\": \\\"123\\\"}\"\n                            },\n                            \"description\": \"This is a sample POST Request\"\n                        }\n                    }\n                ]\n            },\n            {\n                \"name\": \"Sample GET Request\",\n                \"request\": {\n                    \"url\": \"https://postman-echo/get\",\n                    \"method\": \"GET\",\n                    \"description\": \"This is a sample GET Request\"\n                }\n            }\n        ]\n    }\n}",ParameterType.RequestBody);

var response = RestSharp.Settings.restClient.ExecuteAsync(RestSharp.Settings.restRequest).Result;

Console.WriteLine("Returned http status code is: " + response.StatusCode + " expected OK");

Assert.IsTrue((int)response.StatusCode == 200);

Body:
Have a look at the RestSharp quick start guide.  There are a couple of methods that could come in useful for you.

If you have an object to serialize you can use AddJsonBody() to post Json.  This is taken from that guide:

For example, you'd only need these lines to make a request with
JSON body:

var request = new RestRequest("address/update").AddJsonBody(updatedAddress);
var response = await client.PostAsync<AddressUpdateResponse>(request);

AddJsonBody automatically sets the ContentType and DataFormat:

There is no need to set the Content-Type or add the DataFormat
parameter to the request when using those methods, RestSharp will do
it for you.

However, since you already have Json as a string, the correct method to use is AddStringBody() (credit to Alexey Zimarev for the comment). You need to pass the content type:

If you have a pre-serialized payload like a JSON string, you can use
AddStringBody to add it as a body parameter. You need to specify the
content type, so the remote endpoint knows what to do with the request
body. For example:

```
const json = // your json string;
request.AddStringBody(json, ContentType.Json);
```

I'd recommend awaiting the response too, as in the examples above, rather than using .Result.


问:
Error when adding Datepicker to a remote component in module federation
I am trying to use datepicker within an remote component using module federation and am getting the attached error message.

Troubleshooting steps tried

Added @angular/material as shared library to webpack config of all
projects

Tried adding @angular/material/core as shared library to webpack
config of all projects

Added MatDatepickerModule and MatNativeDateModule to import of App
Modules of both base and remote projects

Tried Adding MatDatepickerModule and MatNativeDateModule as providers
too.

Tried installing @angular/material-moment-adapter and using it
instead of MatNativeDateModule.

Reproduction

Steps to reproduce:

Clone the repo with the sample app containing the error(click this link)

run npm install

run following commands in separate terminals

npx ng s

npx nx build remote -c=development --watch

npx http-server dist/apps

Environment

Angular: 12.3.3

CDK/Material: 12.2.13

Browser(s): Microsoft Edge

Operating System (e.g. Windows, macOS, Ubuntu): Windows 10

答:
The error indicates your app is not providing the necessary service DateAdapter;

The angular material's docs state that we need to import MatNativeDateModule from the root component; or provide an alternative for it. (have a look on their live examples to see how they recommend you use it)

In your git repo, you are importing it from the component which uses the date picker, and that might be your problem in the actual app.

Your git repo worked fine for me btw, without console errors:


问:
Need help to convert this chunk of Google Sign in and registration code from fragment to viewModel for fragment so I can follow the MVVM
I need to convert the below chunk of codes to my viewModel so that I can follow the MVVM.
I did a lot of googling and see some so; solutions in StackOverflow which never worked for me and also not for Kotlin especially.

here is the fragment code with all the google authentication code in it:

class LoginFragment : Fragment() {

```<code>private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
private val scope = CoroutineScope(CoroutineName("loginFragmentScope"))
private val viewModel by viewModels<LoginViewModel>()

private lateinit var googleSignInClient: GoogleSignInClient

companion object {
    const val TAG = "LoginFragment"
    const val RC_SIGN_IN = 9139;
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    _binding = FragmentLoginBinding.inflate(inflater, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.btnContinueWithGoogle.setOnClickListener {
        UiUtils.showProgress(requireContext())
        requestGoogleSignIn()
        signIn()
        UiUtils.hideProgress()
    }

}

private fun requestGoogleSignIn() {
    val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build()

    googleSignInClient = GoogleSignIn.getClient(requireActivity(), gso)
}

private fun signIn() {
    val signInIntent = googleSignInClient.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    UiUtils.showProgress(requireContext())

    if (requestCode == RC_SIGN_IN) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        try {

            val account = task.getResult(ApiException::class.java)!!
            Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
            firebaseAuthWithGoogle(account.idToken!!)
        } catch (e: ApiException) {

            Log.w(TAG, "Google sign in failed", e)
            UiUtils.hideProgress()
            UiUtils.showErrorSnackBar(requireView(), "Google sign in failed", 0)

        }
    }
}

private fun firebaseAuthWithGoogle(idToken: String) {
    val credential = GoogleAuthProvider.getCredential(idToken, null)
    FirestoreAuth().auth.signInWithCredential(credential)
        .addOnCompleteListener(requireActivity()) { task ->
            if (task.isSuccessful) {

                Log.d(TAG, "signInWithCredential:success")
                FirestoreAuth().getUserDetails { user ->
                    FirestoreAuth().registerUserWithEmailAndPassword(user.email, "islamic123") {
                        if (it) {
                            updateUi(FirestoreAuth().auth.currentUser)
                        }
                        UiUtils.hideProgress()
                    }
                    DataStoreUtil(requireActivity()).storeInitialData(
                        user.userId,
                        user.firstName
                    )
                    updateUi(FirestoreAuth().auth.currentUser)
                }

            } else {

                Log.w(TAG, "signInWithCredential:failure", task.exception)
                UiUtils.hideProgress()
            }
        }
}

private fun updateUi(user: FirebaseUser? = null) {
    if (user == null) {
        Log.i(TAG, "User is Null!! Failed!")
        return
    }
    startActivity(Intent(activity, TestActivity::class.java))
}
</code>```

答:
I guess it makes way more sense to have your logic like this:

View: onBtnClick(viewmodel.signIn())

Viewmodel: signIn() { FirebaseConnectorClass.doSignIn() }

FirebaseConnectorClass {

firebaseAuthWithGoogle()

}

EDIT:
To break it down very simple, with MVVM you want to divide your UI from the backend repositories.

The main goal is not to freeze the UI while doing some heavy lifting in the backend.

Therefore you have your view (UI) trigger an event in the viewModel. The viewModel then asks the backend to do the given task. When the backend is finished, it informs the viewModel and the viewModel updates the view (UI). This way your UI stays responsive all the time.

Checkout the links of Alex Mamo above to get a better understanding.

Body:
I need to convert the below chunk of codes to my viewModel so that I can follow the MVVM.
I did a lot of googling and see some so; solutions in StackOverflow which never worked for me and also not for Kotlin especially.

here is the fragment code with all the google authentication code in it:

class LoginFragment : Fragment() {

private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
private val scope = CoroutineScope(CoroutineName("loginFragmentScope"))
private val viewModel by viewModels<LoginViewModel>()

private lateinit var googleSignInClient: GoogleSignInClient

companion object {
    const val TAG = "LoginFragment"
    const val RC_SIGN_IN = 9139;
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    _binding = FragmentLoginBinding.inflate(inflater, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.btnContinueWithGoogle.setOnClickListener {
        UiUtils.showProgress(requireContext())
        requestGoogleSignIn()
        signIn()
        UiUtils.hideProgress()
    }

}

private fun requestGoogleSignIn() {
    val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestIdToken(getString(R.string.default_web_client_id))
        .requestEmail()
        .build()

    googleSignInClient = GoogleSignIn.getClient(requireActivity(), gso)
}

private fun signIn() {
    val signInIntent = googleSignInClient.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    UiUtils.showProgress(requireContext())

    if (requestCode == RC_SIGN_IN) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        try {

            val account = task.getResult(ApiException::class.java)!!
            Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
            firebaseAuthWithGoogle(account.idToken!!)
        } catch (e: ApiException) {

            Log.w(TAG, "Google sign in failed", e)
            UiUtils.hideProgress()
            UiUtils.showErrorSnackBar(requireView(), "Google sign in failed", 0)

        }
    }
}

private fun firebaseAuthWithGoogle(idToken: String) {
    val credential = GoogleAuthProvider.getCredential(idToken, null)
    FirestoreAuth().auth.signInWithCredential(credential)
        .addOnCompleteListener(requireActivity()) { task ->
            if (task.isSuccessful) {

                Log.d(TAG, "signInWithCredential:success")
                FirestoreAuth().getUserDetails { user ->
                    FirestoreAuth().registerUserWithEmailAndPassword(user.email, "islamic123") {
                        if (it) {
                            updateUi(FirestoreAuth().auth.currentUser)
                        }
                        UiUtils.hideProgress()
                    }
                    DataStoreUtil(requireActivity()).storeInitialData(
                        user.userId,
                        user.firstName
                    )
                    updateUi(FirestoreAuth().auth.currentUser)
                }

            } else {

                Log.w(TAG, "signInWithCredential:failure", task.exception)
                UiUtils.hideProgress()
            }
        }
}

private fun updateUi(user: FirebaseUser? = null) {
    if (user == null) {
        Log.i(TAG, "User is Null!! Failed!")
        return
    }
    startActivity(Intent(activity, TestActivity::class.java))
}


问:
WPF linebreak problems
I have a TextBlock and want to show information from the database.
I wan't to display the text like this:

```<code>Task for Day xy
- blabla
- blabla
- more blablabla
</code>```

Somehow I need to include a character for the newlines.. I thoug about \n.. so the text in the database would look like:

Task for Day xy\n- blabla\n- blabla\n- more blablabla

doesn't work.

I tried and searched online for hours.. no solution how to do that.
Also this doesn't work:

```<code>Task for Day xy<LineBreak />- blabla<LineBreak />- blabla<LineBreak />- more blablabla
</code>```

the application shows exactly that string from the database without new lines..

here the part of the xaml:

```<code><Grid>
  <Grid.ColumnDefinitions>
      <ColumnDefinition Width="100" />
      <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <TextBlock Grid.Column="1" Text="{Binding Date, StringFormat={}{0:dd.MM.yyyy}}" Margin="6" />
  <TextBlock Grid.Column="2" Text="{Binding Notes}" Margin="6" />
</Grid>
</code>```

any ideas?

答:
Just include a regular newline character in the text, no fancy escape sequences or XML tags:</p>

```<code> string fromDb = ... // get string from DB
 myPropertyWhichIsBoundToWpf = fromDb.Replace("hereShouldBeALinebreak",
                                              System.Environment.NewLine);
</code>```

Title: WPF linebreak problems

Body:
I have a TextBlock and want to show information from the database.
I wan't to display the text like this:

Task for Day xy
- blabla
- blabla
- more blablabla

Somehow I need to include a character for the newlines.. I thoug about \n.. so the text in the database would look like:

Task for Day xy\n- blabla\n- blabla\n- more blablabla

doesn't work.

I tried and searched online for hours.. no solution how to do that.
Also this doesn't work:

Task for Day xy<LineBreak />- blabla<LineBreak />- blabla<LineBreak />- more blablabla

the application shows exactly that string from the database without new lines..

here the part of the xaml:

<Grid>
  <Grid.ColumnDefinitions>
      <ColumnDefinition Width="100" />
      <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <TextBlock Grid.Column="1" Text="{Binding Date, StringFormat={}{0:dd.MM.yyyy}}" Margin="6" />
  <TextBlock Grid.Column="2" Text="{Binding Notes}" Margin="6" />
</Grid>

any ideas?

Body:
Just include a regular newline character in the text, no fancy escape sequences or XML tags:

 string fromDb = ... // get string from DB
 myPropertyWhichIsBoundToWpf = fromDb.Replace("hereShouldBeALinebreak",
                                              System.Environment.NewLine);


问:
java interface reference type object can acess other interface memeber in same classe even it not defined inside it?
If I understand this correctly, the reference type determines which member can be accessed (compile time) while the object type determines which member will be used (runtime).

I have class that implements two interfaces. These interfaces are not related (no inheritance relation allowing one to extends member of the other).

One interface when used as reference type of an object can access a method inside the other method.

```<code>interface Jump {
    // this one do not define anything
}

interface Climb {
    default void greeting(){
        System.out.println("greeting from Climb interface");
    }
}

public class Test implements Jump, Climb {
    public Test(){
        greeting();
    }

    public static void main(String[] args) {
        Climb climb = new Test(); // this is clear that will call default method in Climb
        Jump jump = new Test(); // but why this did compile and print method defined in Jump ?!!!
    }
}
</code>```

The object with reference type Jump interface is assumed to access the member in this interface. And the interfaces are not related. What is going on?

答:
Why wouldn't this work?  It doesn't matter what the variable is defined as; its internal implementation will work the same.  You could write

```<code>public static void main(String[] args) {
  new Test();
}
</code>```

You don't have to assign it to any variable.  There's no typo in that code; it'll work; it'll print greeting from Climb interface.

Body:
If I understand this correctly, the reference type determines which member can be accessed (compile time) while the object type determines which member will be used (runtime).

I have class that implements two interfaces. These interfaces are not related (no inheritance relation allowing one to extends member of the other).

One interface when used as reference type of an object can access a method inside the other method.

interface Jump {
    // this one do not define anything
}

interface Climb {
    default void greeting(){
        System.out.println("greeting from Climb interface");
    }
}

public class Test implements Jump, Climb {
    public Test(){
        greeting();
    }

    public static void main(String[] args) {
        Climb climb = new Test(); // this is clear that will call default method in Climb
        Jump jump = new Test(); // but why this did compile and print method defined in Jump ?!!!
    }
}

The object with reference type Jump interface is assumed to access the member in this interface. And the interfaces are not related. What is going on?

Body:
Why wouldn't this work?  It doesn't matter what the variable is defined as; its internal implementation will work the same.  You could write

public static void main(String[] args) {
  new Test();
}

You don't have to assign it to any variable.  There's no typo in that code; it'll work; it'll print greeting from Climb interface.


问:
How to switch all 1's and 0's in a string at once
I have a string of numbers made up of 1's and 0's and I'd like to switch all the 1's to 0's and 0's to 1's at the same time.

My main issue is I can only figure out how to do it one at a time so the result is always either 0000 or 1111.

答:
Assuming the string contains only 1s or 0s:

```<code>s = '100110'

out = ''.join('1' if c == '0' else '0' for c in s)
</code>```

Output:

```<code>'011001'
</code>```

You can also use a translation table (str.mktrans + str.translate), which would also work if you have characters other than 0/1 (they would remain unchanged):

```<code>s = '1002110'

t = str.maketrans('01', '10')

out = s.translate(t)
</code>```

Output:

```<code>'0112001'
</code>```

Body:
Assuming the string contains only 1s or 0s:

s = '100110'

out = ''.join('1' if c == '0' else '0' for c in s)

Output:

'011001'

You can also use a translation table (str.mktrans + str.translate), which would also work if you have characters other than 0/1 (they would remain unchanged):

s = '1002110'

t = str.maketrans('01', '10')

out = s.translate(t)

Output:

'0112001'


问:
How to set build status on incoming GitHub pull request from bash?

Issue

From this answer, I learned that one can normally set the build status of a commit using something like:

```<code>https://api.github.com/repos/[owner]/[repository]/statuses/[commit sha]
</code>```

However, since I do not own the repositories of which the pull request is incoming, I cannot set the build status of their commits. Hence, I was wondering whether it was possible to (use the GitHub API to) set the build status of an incoming pull request instead.

Question

Suppose one uses a self-hosted CI, that automatically runs a build on each incoming pull request, how could one set the accompanying build status on the pull request in GitHub?

Note

From the given answer and comments by VonC I can derive that the default "pull request build status" is the build status that belongs to the commit of the incoming pull request. And that the only way to change the build status is to either acquire collaborator status on the random/other repository, or to become owner of the random/other repository. However, my question is: is it possible to override/set a manual build status belonging to a pull request, instead of belonging to the incoming commit?

I've included a sketch to illustrate the difference, as I thought my verbal explanation was insufficient. The blue line represents the default way a pull request gets a build status. (By making the person who receives the pull request, owner or collaborator on the incoming random repository.) My question (in terms of the image) is: does there exist that red box in the pull request that allows the owner of the repository that is receiving a pull request to set/override the build status belonging to the pull request (instead of belonging to the commit build status)?

Based on the following part of a comment by VonC:

PR don't have exactly a "build status", only commit status or "status check"

I think I can conclude the answer to this question (in terms of the image) is: No.

答:
However, since I do not own the repositories of which the pull request is incoming

That means you would not be able to modify anything in that repository though: no commit status (2012) or even check API (2017).

You would need to be a collaborator on that repository to do anything on it.

Body:
Issue

From this answer, I learned that one can normally set the build status of a commit using something like:

https://api.github.com/repos/[owner]/[repository]/statuses/[commit sha]

However, since I do not own the repositories of which the pull request is incoming, I cannot set the build status of their commits. Hence, I was wondering whether it was possible to (use the GitHub API to) set the build status of an incoming pull request instead.

Question

Suppose one uses a self-hosted CI, that automatically runs a build on each incoming pull request, how could one set the accompanying build status on the pull request in GitHub?

Note

From the given answer and comments by VonC I can derive that the default "pull request build status" is the build status that belongs to the commit of the incoming pull request. And that the only way to change the build status is to either acquire collaborator status on the random/other repository, or to become owner of the random/other repository. However, my question is: is it possible to override/set a manual build status belonging to a pull request, instead of belonging to the incoming commit?

I've included a sketch to illustrate the difference, as I thought my verbal explanation was insufficient. The blue line represents the default way a pull request gets a build status. (By making the person who receives the pull request, owner or collaborator on the incoming random repository.) My question (in terms of the image) is: does there exist that red box in the pull request that allows the owner of the repository that is receiving a pull request to set/override the build status belonging to the pull request (instead of belonging to the commit build status)?

Based on the following part of a comment by VonC:

PR don't have exactly a "build status", only commit status or "status check"

I think I can conclude the answer to this question (in terms of the image) is: No.