问:
Is it possible to set a discovery URI for token acquisition in Microsoft.Identity.Web?
I have a .NET5 app that is utilizing Microsoft.Identity.Web for a secure API.  When attempting to retrieve the access token:

```<code>var accessToken = await _tokenAcquisition.GetAccessTokenForAppAsync(scopesToAccessDownstreamApi);
</code>```

The first thing that happens is it makes a request to the discovery endpoint:

```<code>https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=.......%2Fauthorize
</code>```

I have a static authority specified in my config which I thought it should be using instead.  For my Blazor app it works just fine.  MS.Identity.Web first gets my key information at my authority:

```<code>https://myCustomAuthority/myTenantId/oauth2/v2.0/.well-known/openid-configuration
</code>```

With the tokenAcquisition however, it always calls login.microsoft.com, fails, and then finally redirects to my endpoint.

Digging through both the MS.Identity.Web and MS.Identity.Client code they definitely had this in mind.

```<code>/// Allows developers to configure their own valid authorities. A json string similar to https://aka.ms/aad-instance-discovery should be provided.
</code>```

See here: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/AbstractApplicationBuilder.cs#L51

```<code>        public InstanceDiscoveryResponse CustomInstanceDiscoveryMetadata { get; set; }
    public Uri CustomInstanceDiscoveryMetadataUri { get; set; }
</code>```

And here:
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ApplicationConfiguration.cs#L95

But I'm unable to find it on the API side.  And when I look at TokenAquisition it's calling ConfidentialClientApplicationBuilder.CreateWithApplicationOptions

```<code>                var builder = ConfidentialClientApplicationBuilder
                    .CreateWithApplicationOptions(_applicationOptions)
                    .WithHttpClientFactory(_httpClientFactory);
</code>```

https://github.com/AzureAD/microsoft-identity-web/blob/b106d9a9250522d0bf9ed0e78e0e3dbd376d8170/src/Microsoft.Identity.Web/TokenAcquisition.cs#L583

Which then creates a new ConfidentialClientApplicationBuilder with an empty ApplicationConfiguration object so the CustomInstanceDiscovery is always null

```<code>            var config = new ApplicationConfiguration();
        var builder = new ConfidentialClientApplicationBuilder(config).WithOptions(options);
</code>```

https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ConfidentialClientApplicationBuilder.cs#L42

All the hooks seem to be there so I feel like I'm missing some configuration but it also could be a feature / bug request.

答:
This was an actual defect that the Microsoft.Identity.Web team has fixed.  I asked the same question to the team:
https://github.com/AzureAD/microsoft-identity-web/discussions/1202

And they created an issue:
https://github.com/AzureAD/microsoft-identity-web/issues/1212

So this was fixed with build 1.13.

Body:
I have a .NET5 app that is utilizing Microsoft.Identity.Web for a secure API.  When attempting to retrieve the access token:

var accessToken = await _tokenAcquisition.GetAccessTokenForAppAsync(scopesToAccessDownstreamApi);

The first thing that happens is it makes a request to the discovery endpoint:

https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=.......%2Fauthorize

I have a static authority specified in my config which I thought it should be using instead.  For my Blazor app it works just fine.  MS.Identity.Web first gets my key information at my authority:

https://myCustomAuthority/myTenantId/oauth2/v2.0/.well-known/openid-configuration

With the tokenAcquisition however, it always calls login.microsoft.com, fails, and then finally redirects to my endpoint.

Digging through both the MS.Identity.Web and MS.Identity.Client code they definitely had this in mind.

/// Allows developers to configure their own valid authorities. A json string similar to https://aka.ms/aad-instance-discovery should be provided.

See here: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/AbstractApplicationBuilder.cs#L51

        public InstanceDiscoveryResponse CustomInstanceDiscoveryMetadata { get; set; }
    public Uri CustomInstanceDiscoveryMetadataUri { get; set; }

And here:
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ApplicationConfiguration.cs#L95

But I'm unable to find it on the API side.  And when I look at TokenAquisition it's calling ConfidentialClientApplicationBuilder.CreateWithApplicationOptions

                var builder = ConfidentialClientApplicationBuilder
                    .CreateWithApplicationOptions(_applicationOptions)
                    .WithHttpClientFactory(_httpClientFactory);

https://github.com/AzureAD/microsoft-identity-web/blob/b106d9a9250522d0bf9ed0e78e0e3dbd376d8170/src/Microsoft.Identity.Web/TokenAcquisition.cs#L583

Which then creates a new ConfidentialClientApplicationBuilder with an empty ApplicationConfiguration object so the CustomInstanceDiscovery is always null

            var config = new ApplicationConfiguration();
        var builder = new ConfidentialClientApplicationBuilder(config).WithOptions(options);

https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/ac7541c1aa1c7bdbb20df5c7e72628161f826f44/src/client/Microsoft.Identity.Client/AppConfig/ConfidentialClientApplicationBuilder.cs#L42

All the hooks seem to be there so I feel like I'm missing some configuration but it also could be a feature / bug request.


来源: stackexchange

问:
Get the file extension in the JavaScript
I have a problem checking what is an extension in my multiple input files. I am added pathinfo in the javascript and alert to check the file extension, but cannot work. Below is my coding:

<!DOCTYPE html>

<input type="file" name="vasplus_multiple_files" id="vasplus_multiple_files"   accept="application/msword, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*" multiple="multiple"/>
    <input type="submit" name="next" class="action-button" value="Submit" onclick="sendFunc_web()"/>

```

For example, if the file names are abcdefg.pdf and haha.jpeg, I want to alert twice data to show extensions are pdf and jpeg``.

The result might be like below the pictures;

Hope someone can guide me which part I am getting wrong.

答:
RegEx (Fast & Accurate) version of pathInfo:

function pathInfo(s) {
    s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}
var sample='folder/myfolder/another/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "folder/myfolder/another/",
  "file": "file.min.js",
  "name": "file.min",
  "ext": ".js"
}
*/
console.log(result.ext);```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem checking what is an extension in my multiple input files. I am added pathinfo in the javascript and alert to check the file extension, but cannot work. Below is my coding:

<!DOCTYPE html>

<input type="file" name="vasplus_multiple_files" id="vasplus_multiple_files"   accept="application/msword, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*" multiple="multiple"/>
    <input type="submit" name="next" class="action-button" value="Submit" onclick="sendFunc_web()"/>

For example, if the file names are abcdefg.pdf and haha.jpeg, I want to alert twice data to show extensions are pdf and jpeg``.

The result might be like below the pictures;

Hope someone can guide me which part I am getting wrong.


问:
Hosting of VSCode for browser based access
Like Eclipse Theia, is it possible to run VSCode centrally, so it can be accessed remotely via browser (in multi-user scenarios using)? I am NOT talking about "https://vscode.dev/" (I am aware of that). I am curious about private hosting, with custom plugins, etc. (like Eclipse Theia).</p>

答:
Thankyou @lawrence-Cherone coder.com

if you are using Docker

simply create docker-compose.yml

run docker-compose up in cmd

```<code>    version: "2.1"
services:
  code-server:
    image: lscr.io/linuxserver/code-server
    container_name: code-server
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/London
      - PASSWORD=password #optional
      - HASHED_PASSWORD= #optional
      - SUDO_PASSWORD=password #optional
      - SUDO_PASSWORD_HASH= #optional
      - PROXY_DOMAIN=code-server.my.domain #optional
      - DEFAULT_WORKSPACE=/config/workspace #optional
    volumes:
      - /path/to/appdata/config:/config
    ports:
      - 8443:8443
    restart: unless-stopped
</code>```

After Completing your IDE available in localhost:8443 (As mentioned in the dockercompose.yml)

For more information visit Docker Hub

Installing on Windows (use git bash):

Windows
We currently do not publish Windows releases. We recommend installing code-server onto Windows with yarn or npm.

Note: You will also need to build coder/cloud-agent manually if you would like to use code-server --link on Windows.
Document

```<code>    yarn global add code-server
# Or: npm install -g code-server
code-server
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
</code>```

Body:
Thankyou @lawrence-Cherone coder.com

if you are using Docker

simply create docker-compose.yml

run docker-compose up in cmd

    version: "2.1"
services:
  code-server:
    image: lscr.io/linuxserver/code-server
    container_name: code-server
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/London
      - PASSWORD=password #optional
      - HASHED_PASSWORD= #optional
      - SUDO_PASSWORD=password #optional
      - SUDO_PASSWORD_HASH= #optional
      - PROXY_DOMAIN=code-server.my.domain #optional
      - DEFAULT_WORKSPACE=/config/workspace #optional
    volumes:
      - /path/to/appdata/config:/config
    ports:
      - 8443:8443
    restart: unless-stopped

After Completing your IDE available in localhost:8443 (As mentioned in the dockercompose.yml)

For more information visit Docker Hub

Installing on Windows (use git bash):

Windows
We currently do not publish Windows releases. We recommend installing code-server onto Windows with yarn or npm.

Note: You will also need to build coder/cloud-agent manually if you would like to use code-server --link on Windows.
Document

    yarn global add code-server
# Or: npm install -g code-server
code-server
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml


问:
lua recursive function gets true and then false within a false
not sure what is happening.  i have a recursive function getting data from a table.  and it's finds an key to be true and then false twice within it being false..

i am wanting to check the isActive boolean and if it's false return false.  if it's true then continue the script.

DUMMY_DATA

```<code>    local DummyData = {
    data = {
        ['id'] = 34523456,
        ['question'] = 'whats milk?',
        ['isActive'] = true,
        ['questionCountdownTimerInSeconds'] = (60),
    }
}
</code>```

RECURSIVE

```<code>    function FindQuestionInfo(Object)
    local Data = {
        ['id'] = '',
        ['question'] = '',
        ['isActive'] = true or false,
        ['questionCountdownTimerInSeconds'] = (0),
    }

    for index, child in pairs(Object) do

        local ChildIsTable = type(child) == 'table'
        if not ChildIsTable then
            local isActive = index == 'isActive'

            local isId = index == 'id'
            local isQuestion = index == 'question'
            local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'

            if isQuestion then
                Data['question'] = child
            end

            if isId then
                Data['id'] = child
            end
        end

        if ChildIsTable then
            local FoundItem = FindQuestionInfo(child)
            if FoundItem then
                return FoundItem
            end
        end
    end

    return Data
end
</code>```

PRINT

答:
Your code doesn't make too much sense. I'm not even sure what you want to achieve with it.

I'll just mention a few issues:

```<code>['isActive'] = true or false
</code>```

As Nifim already pointed out in his comment true or false equals true. Sou you could simply do

```<code>['isActive'] = true
</code>```

You don't need parenthesis around numbers as in ['questionCountdownTimerInSeconds'] = (0)

You don't mention how you use this code. I assume you call FindQuestionInfo(DummyData)

So let's run your code. First you define Data

```<code>local Data = {
        ['id'] = '',
        ['question'] = '',
        ['isActive'] = true or false,
        ['questionCountdownTimerInSeconds'] = (0),
    }
</code>```

Then you traverse over the table Object with a generic for loop and the pairs iterator. Assuming Object is DummyData this will give us a key value pair of DummyData each cycle.

First you check if child (our value) is a table. I don't see how it can be a table with the provided code. If it is not a table you create various booleans.

```<code> local isActive = index == 'isActive'

 local isId = index == 'id'
 local isQuestion = index == 'question'
 local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'
</code>```

And then you assign values conditionally.

```<code>if isQuestion then
     Data['question'] = child
   end
   if isId then
     Data['id'] = child
   end
</code>```

So only if index equals one of the keys you assign the same table field from Object to Data.

This whole loop doesn't make sense. If you want to assign values from one table to another you simply assign them. You don't traverse over the entire table until you find the right key to assign.

Aside from your isTable condition which seems to be always false you can replace that for loop by

```<code>Data.isQuestion = Object.isQuestion and Object.isQuestion or Data.isQuestion
Data.isId = Object.isId and Object.isId or Data.isId
</code>```

Because you simply assign those values if they exist in Object.

Then there is this section which I cannot make sense of as I don't see how child will ever be a table:

```<code>if ChildIsTable then
  local FoundItem = FindQuestionInfo(child)
  if FoundItem then
   return FoundItem
  end
end
</code>```

Also FindQuestionInfo(child) always returns Data so the condition

```<code>if FoundItem then
  return FoundItem
end
</code>```

is not necessary.

So unless your Object will have a table inside that you didn't show in your example I don't see any reason to have this code at all. Especially not the recursive part.

You only copy parts of Object into a new table Data.

I cannot make sense of your problem description either.

I'm assuming you're asking about a xy-problem here. So I suggest you ask a new question about the actual problem you're trying to solve rather than about how to fix this code.

Body:
not sure what is happening.  i have a recursive function getting data from a table.  and it's finds an key to be true and then false twice within it being false..

i am wanting to check the isActive boolean and if it's false return false.  if it's true then continue the script.

DUMMY_DATA

    local DummyData = {
    data = {
        ['id'] = 34523456,
        ['question'] = 'whats milk?',
        ['isActive'] = true,
        ['questionCountdownTimerInSeconds'] = (60),
    }
}

RECURSIVE

    function FindQuestionInfo(Object)
    local Data = {
        ['id'] = '',
        ['question'] = '',
        ['isActive'] = true or false,
        ['questionCountdownTimerInSeconds'] = (0),
    }

    for index, child in pairs(Object) do

        local ChildIsTable = type(child) == 'table'
        if not ChildIsTable then
            local isActive = index == 'isActive'

            local isId = index == 'id'
            local isQuestion = index == 'question'
            local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'

            if isQuestion then
                Data['question'] = child
            end

            if isId then
                Data['id'] = child
            end
        end

        if ChildIsTable then
            local FoundItem = FindQuestionInfo(child)
            if FoundItem then
                return FoundItem
            end
        end
    end

    return Data
end

PRINT

Body:
Your code doesn't make too much sense. I'm not even sure what you want to achieve with it.

I'll just mention a few issues:

['isActive'] = true or false

As Nifim already pointed out in his comment true or false equals true. Sou you could simply do

['isActive'] = true

You don't need parenthesis around numbers as in ['questionCountdownTimerInSeconds'] = (0)

You don't mention how you use this code. I assume you call FindQuestionInfo(DummyData)

So let's run your code. First you define Data

local Data = {
        ['id'] = '',
        ['question'] = '',
        ['isActive'] = true or false,
        ['questionCountdownTimerInSeconds'] = (0),
    }

Then you traverse over the table Object with a generic for loop and the pairs iterator. Assuming Object is DummyData this will give us a key value pair of DummyData each cycle.

First you check if child (our value) is a table. I don't see how it can be a table with the provided code. If it is not a table you create various booleans.

 local isActive = index == 'isActive'

 local isId = index == 'id'
 local isQuestion = index == 'question'
 local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'

And then you assign values conditionally.

if isQuestion then
     Data['question'] = child
   end
   if isId then
     Data['id'] = child
   end

So only if index equals one of the keys you assign the same table field from Object to Data.

This whole loop doesn't make sense. If you want to assign values from one table to another you simply assign them. You don't traverse over the entire table until you find the right key to assign.

Aside from your isTable condition which seems to be always false you can replace that for loop by

Data.isQuestion = Object.isQuestion and Object.isQuestion or Data.isQuestion
Data.isId = Object.isId and Object.isId or Data.isId

Because you simply assign those values if they exist in Object.

Then there is this section which I cannot make sense of as I don't see how child will ever be a table:

if ChildIsTable then
  local FoundItem = FindQuestionInfo(child)
  if FoundItem then
   return FoundItem
  end
end

Also FindQuestionInfo(child) always returns Data so the condition

if FoundItem then
  return FoundItem
end

is not necessary.

So unless your Object will have a table inside that you didn't show in your example I don't see any reason to have this code at all. Especially not the recursive part.

You only copy parts of Object into a new table Data.

I cannot make sense of your problem description either.

I'm assuming you're asking about a xy-problem here. So I suggest you ask a new question about the actual problem you're trying to solve rather than about how to fix this code.


问:
How to shuffle and split a large csv with headers?
I am trying to find a way to shuffle the lines of a large csv files in Python and then split it into multiple csv files (assigning a number of rows for each files) but I can't manage to find a way to shuffle the large dataset, and keep the headers in each csv.
It would help a lot if someone would know how to

Here's the code I found useful for splitting a csv file:

```<code>number_of_rows = 100

def write_splitted_csvs(part, lines):
    with open('mycsvhere.csv'+ str(part) +'.csv', 'w') as f_out:
        f_out.write(header)
        f_out.writelines(lines)

with open("mycsvhere.csv", "r") as f:
    count = 0
    header = f.readline()
    lines = []
    for line in f:
        count += 1
        lines.append(line)
        if count % number_of_rows == 0:
            write_splitted_csvs(count // number_of_rows, lines)
            lines = []

    if len(lines) > 0:
        write_splitted_csvs((count // number_of_rows) + 1, lines)
</code>```

If anyone knows how to shuffle all these splitted csv this would help a lot!
Thank you very much

答:
I would suggest using Pandas if possible.

Shuffling rows, reset the index in place:

```<code>import pandas as pd
df = pd.read_csv('mycsvhere.csv'+ str(part) +'.csv')
df.sample(frac=1).reset_index(drop=True)
</code>```

Then you can split into multiple dataframes into a list:

```<code>number_of_rows = 100
sub_dfs = [df[i:i + number_of_rows] for i in range(0, df.shape[0], number_of_rows)]
</code>```

Then if you want to save the csvs locally:

```<code>for idx, sub_df in enumerate(sub_dfs):
    sub_df.to_csv(f'csv_{idx}.csv', index=False)
</code>```

Body:
I am trying to find a way to shuffle the lines of a large csv files in Python and then split it into multiple csv files (assigning a number of rows for each files) but I can't manage to find a way to shuffle the large dataset, and keep the headers in each csv.
It would help a lot if someone would know how to

Here's the code I found useful for splitting a csv file:

number_of_rows = 100

def write_splitted_csvs(part, lines):
    with open('mycsvhere.csv'+ str(part) +'.csv', 'w') as f_out:
        f_out.write(header)
        f_out.writelines(lines)

with open("mycsvhere.csv", "r") as f:
    count = 0
    header = f.readline()
    lines = []
    for line in f:
        count += 1
        lines.append(line)
        if count % number_of_rows == 0:
            write_splitted_csvs(count // number_of_rows, lines)
            lines = []

    if len(lines) > 0:
        write_splitted_csvs((count // number_of_rows) + 1, lines)

If anyone knows how to shuffle all these splitted csv this would help a lot!
Thank you very much

Body:
I would suggest using Pandas if possible.

Shuffling rows, reset the index in place:

import pandas as pd
df = pd.read_csv('mycsvhere.csv'+ str(part) +'.csv')
df.sample(frac=1).reset_index(drop=True)

Then you can split into multiple dataframes into a list:

number_of_rows = 100
sub_dfs = [df[i:i + number_of_rows] for i in range(0, df.shape[0], number_of_rows)]

Then if you want to save the csvs locally:

for idx, sub_df in enumerate(sub_dfs):
    sub_df.to_csv(f'csv_{idx}.csv', index=False)


答:
There are 3 needs here :

Shuffle your dataset

Split your dataset

Formatting

For the first 2 steps, there are some nice tools in Sklearn. You can try the stratified shuffle splitter.
Sklearn SSS
You did not mention Stratified part, but you may need it without knowing it yet ;)

Last part, formatting, it is all up to you. You can check pandas to_csv() function where you can specify your headers, you can(need) specify your headers in the data object aswell (DataFrame). Nothing hard here, just spend a bit of time to specify what you want, and implement it easily :)

Side comments : You can drop pandas, depending on what 'big' is for you, pandas is not 'good' on big data.

Title: How to shuffle and split a large csv with headers?


问:
Break While Loop adding "last" to

In WordPress, I'm using this:

```<code>while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
echo "<div class='test'>test</div>";
<?php endwhile; ?>
</code>```

I'd now like it so for every 2nd element, it would add the "last" class to the div, so the final code could be:

```<code><div class='test'>test</div>
<div class='test last'>test</div>
<div class='test'>test</div>
<div class='test last'>test</div>
<div class='test'>test</div>
<div class='test last'>test</div>.....
</code>```

Many thanks for any pointers.

答:
```<code>for ($i = 0; $wp_query->have_posts(); $i++) {
    $wp_query->the_post();
    echo ($i %% 2) ? "<div class='test last'>test</div>" : "<div class='test'>test</div>";
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Break While Loop adding "last" to <div>

Body:
In WordPress, I'm using this:

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
echo "
test
";
<?php endwhile; ?>

I'd now like it so for every 2nd element, it would add the "last" class to the div, so the final code could be:

test

test

test

test

test

test
.....

Many thanks for any pointers.


问:
How to make a condition in a React hook?
how to properly make a condition in a useState hook?

I have this code snippet:

```<code>  const [ input, setInput ] = useState('Hello');

  const inputHandler = (e) => {
    setInput((prevInput) => (
    (e.target.value.length == 6) && { ...prevInput, [e.target.id]: e.target.value });
</code>```

Where is the problem, please, if such a piece of code ends up with an error? And points to a semicolon?

```<code>Unexpected token, expected "," (9:84)
</code>```

Thanks

答:
You have a syntax error because you're missing a closing parenthesis ) in the setInput and a closing bracket for the first arrow function }

```<code>const inputHandler = (e) => {
  setInput(
    (prevInput) =>
      (e.target.value.length === 6 && {
        ...prevInput,
        [e.target.id]: e.target.value
      })
  );
};
</code>```

It is worth to mention that this setInput is changing the state from a string to an object or to false if the condition is not met. You should pass the e.target.value to avoid changing the state type.

Body:
how to properly make a condition in a useState hook?

I have this code snippet:

  const [ input, setInput ] = useState('Hello');

  const inputHandler = (e) => {
    setInput((prevInput) => (
    (e.target.value.length == 6) && { ...prevInput, [e.target.id]: e.target.value });

Where is the problem, please, if such a piece of code ends up with an error? And points to a semicolon?

Unexpected token, expected "," (9:84)

Thanks

Body:
You have a syntax error because you're missing a closing parenthesis ) in the setInput and a closing bracket for the first arrow function }

const inputHandler = (e) => {
  setInput(
    (prevInput) =>
      (e.target.value.length === 6 && {
        ...prevInput,
        [e.target.id]: e.target.value
      })
  );
};

It is worth to mention that this setInput is changing the state from a string to an object or to false if the condition is not met. You should pass the e.target.value to avoid changing the state type.


问:
Is there any way to delete useless functions in JS libraries?
I'm building a project in javascript, using paper.js in some features.
Most of my project is built in vanilla Javascript, just some minimum but important features are built with paper.js

The problem is that the library (.min library) is 200kb.
The normal library is 300kb, I was wondering if there is an automatic way to see which functions are being used in the main paper.js library, in order to delete the useless functions.
If  there is no program or automatic way to do this, maybe some advice of how to do it manually, or which tools you recommend for me and my team in order to delete useless functions, then minify the file and run it smaller.

Thank you all guys, I did not added any specific code because I want this anwser to be global.

Greetings

答:
You have to do it manually but it's not an easy (and certainly not quick) process. You'll have to find which functions you're using and then find whatever classes or functions those functions reference. You would probably have an easier time creating a new script then copy/pasting what you're using (and any referenced content) then running it with your script, log errors, and repeat.

When you're done there's many minify libraries and services online you can use to minify the new script.


问:
Set property value on object loaded from json containing comments
When loading an object from a json file one can normally set the value on properties and write the file back out like so:

```<code>$manifest = (gc $manifestPath) | ConvertFrom-Json -AsHashtable
$manifest.name = "$($manifest.name)-sxs"
$manifest | ConvertTo-Json -depth 100 | Out-File $manifestPath -Encoding utf8NoBOM
</code>```

But if the source json file contains comments, the object's properties can't be set:

```<code>// *******************************************************
// GENERATED FILE - DO NOT EDIT DIRECTLY
// *******************************************************
{
  "name": "PublishBuildArtifacts"
}
</code>```

Running the code above throws an error:

```<code>$manifest

id                 : 1D341BB0-2106-458C-8422-D00BCEA6512A
name               : PublishBuildArtifacts
friendlyName       : ms-resource:loc.friendlyName
description        : ms-resource:loc.description
category           : Build
visibility         : {Build}
author             : Microsoft Corporation
version            : @{Major=0; Minor=1; Patch=71}
demands            : {}
inputs             : {@{name=CopyRoot; type=filePath; label=ms-resource:loc.input.label.CopyRoot; defaultValue=;
                     required=False; helpMarkDown=Root folder to apply copy patterns to.  Empty is the root of the
                     repo.}, @{name=Contents; type=multiLine; label=ms-resource:loc.input.label.Contents;
                     defaultValue=; required=True; helpMarkDown=File or folder paths to include as part of the
                     artifact.}, @{name=ArtifactName; type=string; label=ms-resource:loc.input.label.ArtifactName;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.},
                     @{name=ArtifactType; type=pickList; label=ms-resource:loc.input.label.ArtifactType;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.; options=}…}
instanceNameFormat : Publish Artifact: $(ArtifactName)
execution          : @{PowerShell=; Node=}

$manifest.name
PublishBuildArtifacts

$manifest.name = "sxs"
InvalidOperation: The property 'name' cannot be found on this object. Verify that the property exists and can be set.
</code>```

When I strip the comments, I can overwrite the property.

Is there a way I can coax PowerShell to ignore the comments while loading the json file/convert the object and generate a writable object?

答:
Santiago Squarzon's helpful answer shows an effective solution and analyzes the symptom. Let me complement it with some background information.

tl;dr

You're seeing a variation of a known bug, still present as of PowerShell 7.2.1, where a blank line or a single-line comment as the first input object unexpectedly causes $null to be emitted (first) - see GitHub issue #12229.

Using -Raw with Get-Content isn't just a workaround, it is the right - and faster - thing to do when piping a file containing JSON to be parsed as whole to ConvertFrom-Json

For multiple input objects (strings), ConverFrom-Json has a(n unfortunate) heuristic built in that tries to infer whether the multiple strings represent either (a) the lines of a single JSON document or (b) separate, individual JSON documents, each on its own line, as follows:

If the first input string is valid JSON by itself, (b) is assumed, and an object representing the parsed JSON ([pscustomobject] or , with -AsHashtable, [hastable], or an array of either) is output for each input string.

Otherwise, (a) is assumed and all input strings are collected first, in a multi-line string, which is then parsed.

The aforementioned bug is that if the first string is an empty/blank line or a single-line comment[1] (applies to both // ... comments, which are invariably single-line, and /* ... */ if they happen to be single-line), (b) is (justifiably) assumed, but an extraneous $null is emitted before the remaining (non-blank, non-comment) lines are parsed and their object representation(s) are output.

As a result an array is invariably returned, whose first element is $null - which isn't obvious, but results in subtle changes in behavior, as you've experienced:

Notably, attempting to set a property on what is presumed to be a single object then fails, because the fact that an array is being accessed makes the property access an instance of member-access enumeration - implicitly applying property access to all elements of a collection rather than the collection itself - which only works for getting property values - and fails obscurely when setting is attempted - see this answer for details.

A simplified example:

# Sample output hashtable parsed from JSON
$manifest = @{ name = 'foo' }

# This is what you (justifiably) THOUGHT you were doing.
$manifest.name = 'bar' # OK

# Due to the bug, this is what you actually attempted.
($null, $manifest).name = 'bar' # !! FAILS - member-access enumeration doesn't support setting.
```

As noted above, the resulting error message - The property 'name' cannot be found on this object. ... - is unhelpful, as it doesn't indicate the true cause of the problem.

Improving it would be tricky, however, as the user's intent is inherently ambiguous: the property name may EITHER be a situationally unsuccessful attempt to reference a nonexistent property of the collection itself OR, as in this case, a fundamentally unsupported attempt at setting properties via member-access enumeration.

Conceivably, the following would help if the target object is a collection (enumerable) from PowerShell's perspective: The property 'name' cannot be found on this collection, and setting a collection's elements' properties by member-access enumeration isn't supported.

[1] Note that comments in JSON are supported in PowerShell (Core) v6+ only.

Body:
When loading an object from a json file one can normally set the value on properties and write the file back out like so:

$manifest = (gc $manifestPath) | ConvertFrom-Json -AsHashtable
$manifest.name = "$($manifest.name)-sxs"
$manifest | ConvertTo-Json -depth 100 | Out-File $manifestPath -Encoding utf8NoBOM

But if the source json file contains comments, the object's properties can't be set:

// *******************************************************
// GENERATED FILE - DO NOT EDIT DIRECTLY
// *******************************************************
{
  "name": "PublishBuildArtifacts"
}

Running the code above throws an error:

$manifest

id                 : 1D341BB0-2106-458C-8422-D00BCEA6512A
name               : PublishBuildArtifacts
friendlyName       : ms-resource:loc.friendlyName
description        : ms-resource:loc.description
category           : Build
visibility         : {Build}
author             : Microsoft Corporation
version            : @{Major=0; Minor=1; Patch=71}
demands            : {}
inputs             : {@{name=CopyRoot; type=filePath; label=ms-resource:loc.input.label.CopyRoot; defaultValue=;
                     required=False; helpMarkDown=Root folder to apply copy patterns to.  Empty is the root of the
                     repo.}, @{name=Contents; type=multiLine; label=ms-resource:loc.input.label.Contents;
                     defaultValue=; required=True; helpMarkDown=File or folder paths to include as part of the
                     artifact.}, @{name=ArtifactName; type=string; label=ms-resource:loc.input.label.ArtifactName;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.},
                     @{name=ArtifactType; type=pickList; label=ms-resource:loc.input.label.ArtifactType;
                     defaultValue=; required=True; helpMarkDown=The name of the artifact to create.; options=}…}
instanceNameFormat : Publish Artifact: $(ArtifactName)
execution          : @{PowerShell=; Node=}

$manifest.name
PublishBuildArtifacts

$manifest.name = "sxs"
InvalidOperation: The property 'name' cannot be found on this object. Verify that the property exists and can be set.

When I strip the comments, I can overwrite the property.

Is there a way I can coax PowerShell to ignore the comments while loading the json file/convert the object and generate a writable object?

Body:
Santiago Squarzon's helpful answer shows an effective solution and analyzes the symptom. Let me complement it with some background information.

tl;dr

You're seeing a variation of a known bug, still present as of PowerShell 7.2.1, where a blank line or a single-line comment as the first input object unexpectedly causes $null to be emitted (first) - see GitHub issue #12229.

Using -Raw with Get-Content isn't just a workaround, it is the right - and faster - thing to do when piping a file containing JSON to be parsed as whole to ConvertFrom-Json

For multiple input objects (strings), ConverFrom-Json has a(n unfortunate) heuristic built in that tries to infer whether the multiple strings represent either (a) the lines of a single JSON document or (b) separate, individual JSON documents, each on its own line, as follows:

If the first input string is valid JSON by itself, (b) is assumed, and an object representing the parsed JSON ([pscustomobject] or , with -AsHashtable, [hastable], or an array of either) is output for each input string.

Otherwise, (a) is assumed and all input strings are collected first, in a multi-line string, which is then parsed.

The aforementioned bug is that if the first string is an empty/blank line or a single-line comment[1] (applies to both // ... comments, which are invariably single-line, and /* ... */ if they happen to be single-line), (b) is (justifiably) assumed, but an extraneous $null is emitted before the remaining (non-blank, non-comment) lines are parsed and their object representation(s) are output.

As a result an array is invariably returned, whose first element is $null - which isn't obvious, but results in subtle changes in behavior, as you've experienced:

Notably, attempting to set a property on what is presumed to be a single object then fails, because the fact that an array is being accessed makes the property access an instance of member-access enumeration - implicitly applying property access to all elements of a collection rather than the collection itself - which only works for getting property values - and fails obscurely when setting is attempted - see this answer for details.

A simplified example:

# Sample output hashtable parsed from JSON
$manifest = @{ name = 'foo' }

# This is what you (justifiably) THOUGHT you were doing.
$manifest.name = 'bar' # OK

# Due to the bug, this is what you actually attempted.
($null, $manifest).name = 'bar' # !! FAILS - member-access enumeration doesn't support setting.

As noted above, the resulting error message - The property 'name' cannot be found on this object. ... - is unhelpful, as it doesn't indicate the true cause of the problem.

Improving it would be tricky, however, as the user's intent is inherently ambiguous: the property name may EITHER be a situationally unsuccessful attempt to reference a nonexistent property of the collection itself OR, as in this case, a fundamentally unsupported attempt at setting properties via member-access enumeration.

Conceivably, the following would help if the target object is a collection (enumerable) from PowerShell's perspective: The property 'name' cannot be found on this collection, and setting a collection's elements' properties by member-access enumeration isn't supported.

[1] Note that comments in JSON are supported in PowerShell (Core) v6+ only.


问:
Storing composite/nested object graph
I am currently developing a document store in Mongo DB which contains a complete material breakdown of a specific item. The breakdown is calculated and contains a composite structure.

The domain model:

```<code>public interface IReagent
{
    int ItemId { get; set; }
    int Quantity { get; set; }
    ConcurrentBag<IReagent> Reagents { get; set; }
}

public class Craft : IReagent
{
    public int ItemId { get; set; }
    public int Quantity { get; set; }
    public int SpellId { get; set; }
    public int Skill { get; set; }
    public Profession Profession { get; set; }
    public ConcurrentBag<IReagent> Reagents { get; set; }
}

public class Reagent : IReagent
{
    public int ItemId { get; set; }
    public int Quantity { get; set; }
    public ConcurrentBag<IReagent> Reagents { get; set; }
}
</code>```

Now the problem is that a composite structure is not correctly stored. Reagents stays null in mongodb.

```<code>/* 28 */
{
  "_id" : ObjectId("4e497efa97e8b617f0d229d4"),
  "ItemId" : 52186,
  "Quantity" : 0,
  "SpellId" : 0,
  "Skill" : 475,
  "Profession" : 8,
  "Reagents" : { }
}</code>```

Example of how it should look

```<code>{
    "_id" : ObjectId("4e497efa97e8b617f0d229d4"),
    "ItemId" : 52186,
    "Quantity" : 0,
    "SpellId" : 0,
    "Skill" : 475,
    "Profession" : 8,
    "Reagents" : [
        {
            "ItemId" : 521833,
            "Quantity" : 3,
            "SpellId" : 0,
            "Skill" : 400,
            "Profession" : 7,
            "Reagents" : [
                {
                    "ItemId" : 52186,
                    "Quantity" : 3,
                    "SpellId" : 0,
                    "Skill" : 475,
                    "Profession" : 8,
                    "Reagents" : [
                        {
                            "ItemId" : 52183,
                            "Quantity" : 2,
                            "Reagents" : []
                        },
                        {
                            "ItemId" : 521832,
                            "Quantity" : 1,
                            "Reagents" : []
                        }
                    ]
                },
                {
                    "ItemId" : 52386,
                    "Quantity" : 2
                    "SpellId" : 0,
                    "Skill" : 400,
                    "Profession" : 8,
                    "Reagents" : [
                        {
                            "ItemId" : 52383,
                            "Quantity" : 2,
                            "Reagents" : []
                        },
                        {
                            "ItemId" : 523832,
                            "Quantity" : 1,
                            "Reagents" : []
                        }
                    ]
                }
            ]
        }
    ]
}</code>```

What could be the problem?

答:
The problem is you are using list of abstractions and it cannot serialize these to JSON, so basically you would need to write your own custom serialization. Here is example of custom serialization I wrote:

```<code> public class FieldsWrapper : IBsonSerializable
    {
        public List<DataFieldValue> DataFieldValues { get; set; }

        public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
        {
        if (nominalType != typeof(FieldsWrapper)) throw new ArgumentException("Cannot deserialize anything but self");
        var doc = BsonDocument.ReadFrom(bsonReader);
        var list = new List<DataFieldValue>();
        foreach (var name in doc.Names)
        {
            var val = doc[name];
            if (val.IsString)
                list.Add(new DataFieldValue {LocalIdentifier = name, Values = new List<string> {val.AsString}});
            else if (val.IsBsonArray)
            {
                DataFieldValue df = new DataFieldValue {LocalIdentifier = name};
                foreach (var elem in val.AsBsonArray)
                {
                    df.Values.Add(elem.AsString);
                }
                list.Add(df);
            }
        }
        return new FieldsWrapper {DataFieldValues = list};
        }

        public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
        {
            if (nominalType != typeof (FieldsWrapper))
                throw new ArgumentException("Cannot serialize anything but self");
            bsonWriter.WriteStartDocument();
            foreach (var dataFieldValue in DataFieldValues)
            {

                bsonWriter.WriteName(dataFieldValue.LocalIdentifier);
                if (dataFieldValue.Values.Count != 1)
                {
                    var list = new string[dataFieldValue.Values.Count];
                    for (int i = 0; i < dataFieldValue.Values.Count; i++)
                        list[i] = dataFieldValue.Values[i];
                    BsonSerializer.Serialize(bsonWriter, list);
                }
                else
                {
                    BsonSerializer.Serialize(bsonWriter, dataFieldValue.Values[0]);
                }
            }
            bsonWriter.WriteEndDocument();
        }

    }
</code>```

In your case I would write my custom serialization on the level of Reagent class

Title: Storing composite/nested object graph

Body:
I am currently developing a document store in Mongo DB which contains a complete material breakdown of a specific item. The breakdown is calculated and contains a composite structure.

The domain model:

public interface IReagent
{
    int ItemId { get; set; }
    int Quantity { get; set; }
    ConcurrentBag<IReagent> Reagents { get; set; }
}

public class Craft : IReagent
{
    public int ItemId { get; set; }
    public int Quantity { get; set; }
    public int SpellId { get; set; }
    public int Skill { get; set; }
    public Profession Profession { get; set; }
    public ConcurrentBag<IReagent> Reagents { get; set; }
}

public class Reagent : IReagent
{
    public int ItemId { get; set; }
    public int Quantity { get; set; }
    public ConcurrentBag<IReagent> Reagents { get; set; }
}

Now the problem is that a composite structure is not correctly stored. Reagents stays null in mongodb.

/* 28 */
{
  "_id" : ObjectId("4e497efa97e8b617f0d229d4"),
  "ItemId" : 52186,
  "Quantity" : 0,
  "SpellId" : 0,
  "Skill" : 475,
  "Profession" : 8,
  "Reagents" : { }
}

Example of how it should look

{
    "_id" : ObjectId("4e497efa97e8b617f0d229d4"),
    "ItemId" : 52186,
    "Quantity" : 0,
    "SpellId" : 0,
    "Skill" : 475,
    "Profession" : 8,
    "Reagents" : [
        {
            "ItemId" : 521833,
            "Quantity" : 3,
            "SpellId" : 0,
            "Skill" : 400,
            "Profession" : 7,
            "Reagents" : [
                {
                    "ItemId" : 52186,
                    "Quantity" : 3,
                    "SpellId" : 0,
                    "Skill" : 475,
                    "Profession" : 8,
                    "Reagents" : [
                        {
                            "ItemId" : 52183,
                            "Quantity" : 2,
                            "Reagents" : []
                        },
                        {
                            "ItemId" : 521832,
                            "Quantity" : 1,
                            "Reagents" : []
                        }
                    ]
                },
                {
                    "ItemId" : 52386,
                    "Quantity" : 2
                    "SpellId" : 0,
                    "Skill" : 400,
                    "Profession" : 8,
                    "Reagents" : [
                        {
                            "ItemId" : 52383,
                            "Quantity" : 2,
                            "Reagents" : []
                        },
                        {
                            "ItemId" : 523832,
                            "Quantity" : 1,
                            "Reagents" : []
                        }
                    ]
                }
            ]
        }
    ]
}

What could be the problem?

Body:
The problem is you are using list of abstractions and it cannot serialize these to JSON, so basically you would need to write your own custom serialization. Here is example of custom serialization I wrote:

 public class FieldsWrapper : IBsonSerializable
    {
        public List<DataFieldValue> DataFieldValues { get; set; }

        public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
        {
        if (nominalType != typeof(FieldsWrapper)) throw new ArgumentException("Cannot deserialize anything but self");
        var doc = BsonDocument.ReadFrom(bsonReader);
        var list = new List<DataFieldValue>();
        foreach (var name in doc.Names)
        {
            var val = doc[name];
            if (val.IsString)
                list.Add(new DataFieldValue {LocalIdentifier = name, Values = new List<string> {val.AsString}});
            else if (val.IsBsonArray)
            {
                DataFieldValue df = new DataFieldValue {LocalIdentifier = name};
                foreach (var elem in val.AsBsonArray)
                {
                    df.Values.Add(elem.AsString);
                }
                list.Add(df);
            }
        }
        return new FieldsWrapper {DataFieldValues = list};
        }

        public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
        {
            if (nominalType != typeof (FieldsWrapper))
                throw new ArgumentException("Cannot serialize anything but self");
            bsonWriter.WriteStartDocument();
            foreach (var dataFieldValue in DataFieldValues)
            {

                bsonWriter.WriteName(dataFieldValue.LocalIdentifier);
                if (dataFieldValue.Values.Count != 1)
                {
                    var list = new string[dataFieldValue.Values.Count];
                    for (int i = 0; i < dataFieldValue.Values.Count; i++)
                        list[i] = dataFieldValue.Values[i];
                    BsonSerializer.Serialize(bsonWriter, list);
                }
                else
                {
                    BsonSerializer.Serialize(bsonWriter, dataFieldValue.Values[0]);
                }
            }
            bsonWriter.WriteEndDocument();
        }

    }

In your case I would write my custom serialization on the level of Reagent class


问:
Kendo grid column number formatting
How to set number formatting in kendo column if we bind 2 data values? In my example I have to bind value with unit, so I need a value written with 2 decimals.
My code looks like:

```<code>{
    field: "Quantity",
    title: "Value ",
    width: "70px",
    type: "number",
    format:"{0:n2}",
    template: "#:Quantity# #:Unit#",
    attributes:{style:"text-align:right;"}
},
</code>```

Without binding it to unit it works great, but with unit I have a problem. Thanks in advance

答:
Above given answer is fine but you can also achieve the same result by using separate kendo templates for more customization options.

```<code>template: kendo.template($("#quantity-tmplt").html())
</code>```

Define your template.

```<code><script type="text/x-kendo-template" id="quantity-tmplt">
    <div>#= kendo.toString(Quantity, "n2") #</div>
</script>
</code>```

For more information, read KendoGrid Column Template

Title: Kendo grid column number formatting

Body:
How to set number formatting in kendo column if we bind 2 data values? In my example I have to bind value with unit, so I need a value written with 2 decimals.
My code looks like:

{
    field: "Quantity",
    title: "Value ",
    width: "70px",
    type: "number",
    format:"{0:n2}",
    template: "#:Quantity# #:Unit#",
    attributes:{style:"text-align:right;"}
},

Without binding it to unit it works great, but with unit I have a problem. Thanks in advance

Body:
Above given answer is fine but you can also achieve the same result by using separate kendo templates for more customization options.

template: kendo.template($("#quantity-tmplt").html())

Define your template.

<script type="text/x-kendo-template" id="quantity-tmplt">
    <div>#= kendo.toString(Quantity, "n2") #</div>
</script>

For more information, read KendoGrid Column Template


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答:
The DLR and Parallel Extensions, although I can't say I'm that informed as to exactly what's going to be in the box when it ships.

Edit: As per Jon Skeet, Code Contracts do look nice too. Not ground breaking, but from the samples I've seen they look like a nice way to represent it.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Steve Robbins

LastEditorDisplayName: Steve Robbins


问:
How to detect various size objects inside image using OpenCV for iPhone?
Hello Everyone i am a new to openCV for iPhone and i want to recognize different objects inside any image like pen, pencil, balloon, car, bike etc....

So is it possible ? or is there any tutorial or perfect guide for the same?

Thanks in advance.

答:
Here you find a good resource for learning opencv
http://opencv.willowgarage.com/wiki/OpenCVBooks

You can consider using pattern matching. but then you need a pattern for each object you want to detect, and the pattern matching ist not orientation-invariant. so your pattern only works for object that have the same rotation in the image. of course you could rotate that pattern and perform patternmatching again. but that's quite computative expensive.

so another approach is blob detection,
check out http://opencv.willowgarage.com/wiki/cvBlobsLib
and watch some videos on youtube on "blob detection opencv example", you will find many examples that show what it does. with blob detection you can identify where different objects are but not if it is a pencil, or a ballon ;)


问:
Saving Model Checkpoint in Tensorflow
I am using Tensorflow 2.3 and trying to save model checkpoint after n number of epochs. n can be anything but for now trying with 10

Per this thread, I tried save_freq = 'epoch' and period = 10 which works but since period parameter is deprecated, I wanted to try  an alternative approach.

```<code>HEIGHT = 256
WIDTH = 256
CHANNELS = 3
EPOCHS = 100
BATCH_SIZE = 1
SAVE_PERIOD = 10

n_monet_samples = 21

checkpoint_filepath = "./model_checkpoints/cyclegan_checkpoints.{epoch:03d}"
model_checkpoint_callback = callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE)
)
</code>```

If I use save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE) for the checkpoint callback definition, I get error

```<code>ValueError: Unrecognized save_freq: 210
</code>```

I am not sure why since per Keras callback code, as long as save_freq is in epochs or in integer, it should be good.

Please suggest.

答:
It does not show any error to me when I tried the same code in same Tensorflow version==2.3:

```<code>checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
BATCH_SIZE = 1
SAVE_PERIOD = 10

n_monet_samples = 21

# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1, save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE))

# Train the model with the new callback
model.fit(train_images,
          train_labels,
          epochs=20,
          validation_data=(test_images, test_labels),
          callbacks=[cp_callback])
</code>```

Output:

```<code>Epoch 1/20
32/32 [==============================] - 0s 14ms/step - loss: 1.1152 - sparse_categorical_accuracy: 0.6890 - val_loss: 0.6934 - val_sparse_categorical_accuracy: 0.7940
Epoch 2/20
32/32 [==============================] - 0s 9ms/step - loss: 0.4154 - sparse_categorical_accuracy: 0.8840 - val_loss: 0.5317 - val_sparse_categorical_accuracy: 0.8330
Epoch 3/20
32/32 [==============================] - 0s 8ms/step - loss: 0.2787 - sparse_categorical_accuracy: 0.9270 - val_loss: 0.4854 - val_sparse_categorical_accuracy: 0.8400
Epoch 4/20
32/32 [==============================] - 0s 8ms/step - loss: 0.2230 - sparse_categorical_accuracy: 0.9420 - val_loss: 0.4525 - val_sparse_categorical_accuracy: 0.8590
Epoch 5/20
32/32 [==============================] - 0s 10ms/step - loss: 0.1549 - sparse_categorical_accuracy: 0.9620 - val_loss: 0.4275 - val_sparse_categorical_accuracy: 0.8650
Epoch 6/20
32/32 [==============================] - 0s 10ms/step - loss: 0.1110 - sparse_categorical_accuracy: 0.9770 - val_loss: 0.4251 - val_sparse_categorical_accuracy: 0.8630
Epoch 7/20
11/32 [=========>....................] - ETA: 0s - loss: 0.0936 - sparse_categorical_accuracy: 0.9886
Epoch 00007: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 14ms/step - loss: 0.0807 - sparse_categorical_accuracy: 0.9840 - val_loss: 0.4248 - val_sparse_categorical_accuracy: 0.8610
Epoch 8/20
32/32 [==============================] - 0s 10ms/step - loss: 0.0612 - sparse_categorical_accuracy: 0.9950 - val_loss: 0.4058 - val_sparse_categorical_accuracy: 0.8650
Epoch 9/20
32/32 [==============================] - 0s 8ms/step - loss: 0.0489 - sparse_categorical_accuracy: 0.9950 - val_loss: 0.4393 - val_sparse_categorical_accuracy: 0.8610
Epoch 10/20
32/32 [==============================] - 0s 6ms/step - loss: 0.0361 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4150 - val_sparse_categorical_accuracy: 0.8620
Epoch 11/20
32/32 [==============================] - 0s 10ms/step - loss: 0.0294 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4090 - val_sparse_categorical_accuracy: 0.8670
Epoch 12/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0272 - sparse_categorical_accuracy: 0.9990 - val_loss: 0.4365 - val_sparse_categorical_accuracy: 0.8600
Epoch 13/20
32/32 [==============================] - 0s 8ms/step - loss: 0.0203 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4231 - val_sparse_categorical_accuracy: 0.8620
Epoch 14/20
 1/32 [..............................] - ETA: 0s - loss: 0.0115 - sparse_categorical_accuracy: 1.0000
Epoch 00014: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 9ms/step - loss: 0.0164 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4263 - val_sparse_categorical_accuracy: 0.8650
Epoch 15/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0128 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4260 - val_sparse_categorical_accuracy: 0.8690
Epoch 16/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0120 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4194 - val_sparse_categorical_accuracy: 0.8740
Epoch 17/20
32/32 [==============================] - 0s 9ms/step - loss: 0.0110 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4302 - val_sparse_categorical_accuracy: 0.8710
Epoch 18/20
32/32 [==============================] - 0s 6ms/step - loss: 0.0090 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4331 - val_sparse_categorical_accuracy: 0.8660
Epoch 19/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0084 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4320 - val_sparse_categorical_accuracy: 0.8760
Epoch 20/20
16/32 [==============>...............] - ETA: 0s - loss: 0.0074 - sparse_categorical_accuracy: 1.0000
Epoch 00020: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 13ms/step - loss: 0.0072 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4280 - val_sparse_categorical_accuracy: 0.8750
<tensorflow.python.keras.callbacks.History at 0x7f90f0082cd0>
</code>```

As you already know save_freq is equal to 'epoch' or integer.
 When using 'epoch', the callback saves the model after each epoch.
When using integer, the callback saves the model at end of theses many batches(end of these many steps_per_epoch).

As above definition of save_freq, checkpoints saves every after 210 steps.

Please check this for more details on ModelCheckpoint Arguments.

Title: Saving Model Checkpoint in Tensorflow

Body:
I am using Tensorflow 2.3 and trying to save model checkpoint after n number of epochs. n can be anything but for now trying with 10

Per this thread, I tried save_freq = 'epoch' and period = 10 which works but since period parameter is deprecated, I wanted to try  an alternative approach.

HEIGHT = 256
WIDTH = 256
CHANNELS = 3
EPOCHS = 100
BATCH_SIZE = 1
SAVE_PERIOD = 10

n_monet_samples = 21

checkpoint_filepath = "./model_checkpoints/cyclegan_checkpoints.{epoch:03d}"
model_checkpoint_callback = callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE)
)

If I use save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE) for the checkpoint callback definition, I get error

ValueError: Unrecognized save_freq: 210

I am not sure why since per Keras callback code, as long as save_freq is in epochs or in integer, it should be good.

Please suggest.

Body:
It does not show any error to me when I tried the same code in same Tensorflow version==2.3:

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
BATCH_SIZE = 1
SAVE_PERIOD = 10

n_monet_samples = 21

# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1, save_freq=SAVE_PERIOD * (n_monet_samples//BATCH_SIZE))

# Train the model with the new callback
model.fit(train_images,
          train_labels,
          epochs=20,
          validation_data=(test_images, test_labels),
          callbacks=[cp_callback])

Output:

Epoch 1/20
32/32 [==============================] - 0s 14ms/step - loss: 1.1152 - sparse_categorical_accuracy: 0.6890 - val_loss: 0.6934 - val_sparse_categorical_accuracy: 0.7940
Epoch 2/20
32/32 [==============================] - 0s 9ms/step - loss: 0.4154 - sparse_categorical_accuracy: 0.8840 - val_loss: 0.5317 - val_sparse_categorical_accuracy: 0.8330
Epoch 3/20
32/32 [==============================] - 0s 8ms/step - loss: 0.2787 - sparse_categorical_accuracy: 0.9270 - val_loss: 0.4854 - val_sparse_categorical_accuracy: 0.8400
Epoch 4/20
32/32 [==============================] - 0s 8ms/step - loss: 0.2230 - sparse_categorical_accuracy: 0.9420 - val_loss: 0.4525 - val_sparse_categorical_accuracy: 0.8590
Epoch 5/20
32/32 [==============================] - 0s 10ms/step - loss: 0.1549 - sparse_categorical_accuracy: 0.9620 - val_loss: 0.4275 - val_sparse_categorical_accuracy: 0.8650
Epoch 6/20
32/32 [==============================] - 0s 10ms/step - loss: 0.1110 - sparse_categorical_accuracy: 0.9770 - val_loss: 0.4251 - val_sparse_categorical_accuracy: 0.8630
Epoch 7/20
11/32 [=========>....................] - ETA: 0s - loss: 0.0936 - sparse_categorical_accuracy: 0.9886
Epoch 00007: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 14ms/step - loss: 0.0807 - sparse_categorical_accuracy: 0.9840 - val_loss: 0.4248 - val_sparse_categorical_accuracy: 0.8610
Epoch 8/20
32/32 [==============================] - 0s 10ms/step - loss: 0.0612 - sparse_categorical_accuracy: 0.9950 - val_loss: 0.4058 - val_sparse_categorical_accuracy: 0.8650
Epoch 9/20
32/32 [==============================] - 0s 8ms/step - loss: 0.0489 - sparse_categorical_accuracy: 0.9950 - val_loss: 0.4393 - val_sparse_categorical_accuracy: 0.8610
Epoch 10/20
32/32 [==============================] - 0s 6ms/step - loss: 0.0361 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4150 - val_sparse_categorical_accuracy: 0.8620
Epoch 11/20
32/32 [==============================] - 0s 10ms/step - loss: 0.0294 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4090 - val_sparse_categorical_accuracy: 0.8670
Epoch 12/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0272 - sparse_categorical_accuracy: 0.9990 - val_loss: 0.4365 - val_sparse_categorical_accuracy: 0.8600
Epoch 13/20
32/32 [==============================] - 0s 8ms/step - loss: 0.0203 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4231 - val_sparse_categorical_accuracy: 0.8620
Epoch 14/20
 1/32 [..............................] - ETA: 0s - loss: 0.0115 - sparse_categorical_accuracy: 1.0000
Epoch 00014: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 9ms/step - loss: 0.0164 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4263 - val_sparse_categorical_accuracy: 0.8650
Epoch 15/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0128 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4260 - val_sparse_categorical_accuracy: 0.8690
Epoch 16/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0120 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4194 - val_sparse_categorical_accuracy: 0.8740
Epoch 17/20
32/32 [==============================] - 0s 9ms/step - loss: 0.0110 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4302 - val_sparse_categorical_accuracy: 0.8710
Epoch 18/20
32/32 [==============================] - 0s 6ms/step - loss: 0.0090 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4331 - val_sparse_categorical_accuracy: 0.8660
Epoch 19/20
32/32 [==============================] - 0s 7ms/step - loss: 0.0084 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4320 - val_sparse_categorical_accuracy: 0.8760
Epoch 20/20
16/32 [==============>...............] - ETA: 0s - loss: 0.0074 - sparse_categorical_accuracy: 1.0000
Epoch 00020: saving model to training_1/cp.ckpt
32/32 [==============================] - 0s 13ms/step - loss: 0.0072 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.4280 - val_sparse_categorical_accuracy: 0.8750
<tensorflow.python.keras.callbacks.History at 0x7f90f0082cd0>

As you already know save_freq is equal to 'epoch' or integer.
 When using 'epoch', the callback saves the model after each epoch.
When using integer, the callback saves the model at end of theses many batches(end of these many steps_per_epoch).

As above definition of save_freq, checkpoints saves every after 210 steps.

Please check this for more details on ModelCheckpoint Arguments.


问:
FAIconLibrary addIcon method started throwing error
I have created an FAIcon Module and i am using FaiconLibrary.addIcons() method to include few icons. This was working perfectly fine but just now, i got fresh copy and did npm install and started getting following error. I tried removing node_modules and did clean cache as well, did't work.

```<code> error TS2345: Argument of type 'import("/node_modules/@fortawesome/free-solid-svg-icons/node_modules/@fortawesome/fontawesome-common-types/index").IconDefinition' is not assignable to parameter of type 'import("/node_modules/@fortawesome/fontawesome-common-types/index").IconDefinition'.
  Types of property 'iconName' are incompatible.
    Type 'import("/node_modules/@fortawesome/free-solid-svg-icons/node_modules/@fortawesome/fontawesome-common-types/index").IconName' is not assignable to type 'import("/node_modules/@fortawesome/fontawesome-common-types/index").IconName'.
      Type '"acquisitions-incorporated"' is not assignable to type 'IconName'.

24        library.addIcons(faEye);
</code>```

This is how it is implemented.

~~~~~

Following are the dependencies i am using

```<code> "dependencies": {
    "@angular/animations": "^12.2.16",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "^12.2.16",
    "@angular/compiler": "^12.2.16",
    "@angular/core": "^12.2.16",
    "@angular/forms": "^12.2.16",
    "@angular/material": "^12.2.9",
    "@angular/platform-browser": "^12.2.16",
    "@angular/platform-browser-dynamic": "^12.2.16",
    "@angular/router": "^12.2.16",
    "@fortawesome/angular-fontawesome": "^0.9.0",
    "@fortawesome/fontawesome-svg-core": "^1.3.0",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@nrwl/angular": "12.10.0",
    "@storybook/addon-a11y": "^6.3.12",
    "@storybook/addon-storysource": "^6.3.12",
    "material-design-icons": "^3.0.1",
    "ncp": "^2.0.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.0",
    "@angular-eslint/eslint-plugin": "~12.3.0",
    "@angular-eslint/eslint-plugin-template": "~12.3.0",
    "@angular-eslint/template-parser": "~12.3.0",
    "@angular/cli": "~12.2.0",
    "@angular/compiler-cli": "^12.2.0",
    "@angular/language-service": "^12.2.0",
    "@nrwl/cli": "12.10.0",
    "@nrwl/cypress": "12.10.0",
    "@nrwl/eslint-plugin-nx": "12.10.0",
    "@nrwl/jest": "12.10.0",
    "@nrwl/linter": "12.10.0",
    "@nrwl/storybook": "12.10.0",
    "@nrwl/tao": "12.10.0",
    "@nrwl/workspace": "12.10.0",
    "@storybook/addon-essentials": "~6.3.0",
    "@storybook/angular": "~6.3.0",
    "@storybook/builder-webpack5": "~6.3.0",
    "@storybook/manager-webpack5": "~6.3.0",
    "@types/jest": "27.0.2",
    "@types/node": "14.14.33",
    "@typescript-eslint/eslint-plugin": "~4.31.1",
    "@typescript-eslint/parser": "~4.31.1",
    "cypress": "^8.3.0",
    "eslint": "7.22.0",
    "eslint-config-prettier": "8.1.0",
    "eslint-plugin-cypress": "^2.10.3",
    "jest": "27.2.3",
    "jest-preset-angular": "10.0.1",
    "ng-packagr": "^12.1.1",
    "prettier": "^2.3.1",
    "ts-jest": "27.0.5",
    "typescript": "~4.3.5"
  }
</code>```

tried without using library.AddIcon and got same error

答:
It is a version mismatch issue
https://github.com/FortAwesome/angular-fontawesome/issues/125</p>

Body:
I have created an FAIcon Module and i am using FaiconLibrary.addIcons() method to include few icons. This was working perfectly fine but just now, i got fresh copy and did npm install and started getting following error. I tried removing node_modules and did clean cache as well, did't work.

 error TS2345: Argument of type 'import("/node_modules/@fortawesome/free-solid-svg-icons/node_modules/@fortawesome/fontawesome-common-types/index").IconDefinition' is not assignable to parameter of type 'import("/node_modules/@fortawesome/fontawesome-common-types/index").IconDefinition'.
  Types of property 'iconName' are incompatible.
    Type 'import("/node_modules/@fortawesome/free-solid-svg-icons/node_modules/@fortawesome/fontawesome-common-types/index").IconName' is not assignable to type 'import("/node_modules/@fortawesome/fontawesome-common-types/index").IconName'.
      Type '"acquisitions-incorporated"' is not assignable to type 'IconName'.

24        library.addIcons(faEye);

This is how it is implemented.

~~~~~

Following are the dependencies i am using

 "dependencies": {
    "@angular/animations": "^12.2.16",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "^12.2.16",
    "@angular/compiler": "^12.2.16",
    "@angular/core": "^12.2.16",
    "@angular/forms": "^12.2.16",
    "@angular/material": "^12.2.9",
    "@angular/platform-browser": "^12.2.16",
    "@angular/platform-browser-dynamic": "^12.2.16",
    "@angular/router": "^12.2.16",
    "@fortawesome/angular-fontawesome": "^0.9.0",
    "@fortawesome/fontawesome-svg-core": "^1.3.0",
    "@fortawesome/free-solid-svg-icons": "^5.15.4",
    "@nrwl/angular": "12.10.0",
    "@storybook/addon-a11y": "^6.3.12",
    "@storybook/addon-storysource": "^6.3.12",
    "material-design-icons": "^3.0.1",
    "ncp": "^2.0.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.0",
    "@angular-eslint/eslint-plugin": "~12.3.0",
    "@angular-eslint/eslint-plugin-template": "~12.3.0",
    "@angular-eslint/template-parser": "~12.3.0",
    "@angular/cli": "~12.2.0",
    "@angular/compiler-cli": "^12.2.0",
    "@angular/language-service": "^12.2.0",
    "@nrwl/cli": "12.10.0",
    "@nrwl/cypress": "12.10.0",
    "@nrwl/eslint-plugin-nx": "12.10.0",
    "@nrwl/jest": "12.10.0",
    "@nrwl/linter": "12.10.0",
    "@nrwl/storybook": "12.10.0",
    "@nrwl/tao": "12.10.0",
    "@nrwl/workspace": "12.10.0",
    "@storybook/addon-essentials": "~6.3.0",
    "@storybook/angular": "~6.3.0",
    "@storybook/builder-webpack5": "~6.3.0",
    "@storybook/manager-webpack5": "~6.3.0",
    "@types/jest": "27.0.2",
    "@types/node": "14.14.33",
    "@typescript-eslint/eslint-plugin": "~4.31.1",
    "@typescript-eslint/parser": "~4.31.1",
    "cypress": "^8.3.0",
    "eslint": "7.22.0",
    "eslint-config-prettier": "8.1.0",
    "eslint-plugin-cypress": "^2.10.3",
    "jest": "27.2.3",
    "jest-preset-angular": "10.0.1",
    "ng-packagr": "^12.1.1",
    "prettier": "^2.3.1",
    "ts-jest": "27.0.5",
    "typescript": "~4.3.5"
  }

tried without using library.AddIcon and got same error


问:
How to group by custom types with linq
I have this class

```<code>public class Item
{
       public Coordinate coordinate { get; set; }
        ...
        ...
}
</code>```

With Coordinate being define like this:

```<code>public class Coordinate
{
        public Coordinate(float latitude, float longitude)
        {
            Latitude = latitude;
            Longitude = longitude;
        }

        public float Latitude { get; private set; }
        public float Longitude { get; private set; }
}
</code>```

And I want to have a linq query like that :

```<code>var grouped = from it in items
              group it by it.Coordinate into grp
              select grp;
</code>```

As mentioned here by MSDN I thought this was possible if I would override Equals on my Coordinate class :

Use a named type if you must pass the
  query variable to another method.
  Create a special class using
  auto-implemented properties for the
  keys, and then override the Equals
  and GetHashCode  methods. You can also
  use a struct, in which case you do not
  strictly have to override those
  methods. For more information see How
  to: Implement an Immutable Class That
  Has Auto-Implemented Properties

Equals implementation for Coordinate class :

```<code>public override bool Equals(object obj)
{
       var coord = obj as Coordinate;
       if(coord == null) return false;
       return (Latitude == coord.Latitude && Longitude == coord.Longitude);
}
</code>```

still I cant get my linq query to group by similar coordinates, as my failing test shows :

```<code>[TestMethod]
public void GroupBy_3ItemsWith2DifferentCoordinates_Returns2Groups()
{
    var items = new List<Item>
        {
            new Item {Coordinate = new Coordinate(10, 10)},
            new Item {Coordinate = new Coordinate(10, 10)},
            new Item {Coordinate = new Coordinate(12, 10)},
        };
    var grouped = from it in items
                  group it by it.Coordinate into g
                  select g;
    Assert.AreEqual(2, grouped.Count());
}
</code>```

There is an overload to the GrouBy method that takes an IEqualityComparer as a parameter, but is there the equivalent using the group clause?
Am I doing something wrong?? Any thoughts?

答:
A more modern answer; In C#9/.NET6, I believe you can use record types to accomplish what anonymous types do as far as Linq comparisons, but in an automatic way.

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records

You create record types when you want value-based equality and comparison, don't want to copy values, and want to use reference variables.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record

For record types, including record struct and readonly record struct, two objects are equal if they are of the same type and store the same values.

Title: How to group by custom types with linq

Body:
I have this class

public class Item
{
       public Coordinate coordinate { get; set; }
        ...
        ...
}

With Coordinate being define like this:

public class Coordinate
{
        public Coordinate(float latitude, float longitude)
        {
            Latitude = latitude;
            Longitude = longitude;
        }

        public float Latitude { get; private set; }
        public float Longitude { get; private set; }
}

And I want to have a linq query like that :

var grouped = from it in items
              group it by it.Coordinate into grp
              select grp;

As mentioned here by MSDN I thought this was possible if I would override Equals on my Coordinate class :

Use a named type if you must pass the
  query variable to another method.
  Create a special class using
  auto-implemented properties for the
  keys, and then override the Equals
  and GetHashCode  methods. You can also
  use a struct, in which case you do not
  strictly have to override those
  methods. For more information see How
  to: Implement an Immutable Class That
  Has Auto-Implemented Properties

Equals implementation for Coordinate class :

public override bool Equals(object obj)
{
       var coord = obj as Coordinate;
       if(coord == null) return false;
       return (Latitude == coord.Latitude && Longitude == coord.Longitude);
}

still I cant get my linq query to group by similar coordinates, as my failing test shows :

[TestMethod]
public void GroupBy_3ItemsWith2DifferentCoordinates_Returns2Groups()
{
    var items = new List<Item>
        {
            new Item {Coordinate = new Coordinate(10, 10)},
            new Item {Coordinate = new Coordinate(10, 10)},
            new Item {Coordinate = new Coordinate(12, 10)},
        };
    var grouped = from it in items
                  group it by it.Coordinate into g
                  select g;
    Assert.AreEqual(2, grouped.Count());
}

There is an overload to the GrouBy method that takes an IEqualityComparer as a parameter, but is there the equivalent using the group clause?
Am I doing something wrong?? Any thoughts?


问:
How to avoid using `AnyView` type erasure in closures for callback, in SwiftUI?
I'm trying to create table views based on both List and ScrollView, with a shared base view. My current attempt uses a builder-based approach, but requires closures with AnyView type erasure.

My goal is to avoid using AnyView type erasure, to improve performance, scalability, and design.

My attempts to re-design with generic type parameters have so far failed.

The simplified (and working) code example below displays only a single String column, but captures the basic challenge. (In actuality, these are multi-column tables with various data types, specialized formatters, modifiers, etc.)

```<code>import SwiftUI

struct ContentView: View {
    let data = ["a", "b", "c", "d"]
    var body: some View {
        HStack {
            ListTable(title: "My List", data: data)
            ScrollTable(title: "My Scroll", data: data)
        }
    }
}

struct ListTable<T: Hashable>: View {
    var title: String, data: [T]
    var body: some View {
        BaseTable() { header, row in
            VStack {
                header(title)
                List(data, id: \.self) { row($0) }
            }
        }
    }
}

struct ScrollTable<T: Hashable>: View {
    var title: String, data: [T]
    var body: some View {
        BaseTable() { header, row in
            VStack {
                header(title)
                ScrollView { ForEach(data, id: \.self) { row($0) } }
            }
        }
    }
}

struct BaseTable<Content: View, T: Hashable>: View {
    typealias HBuilder = (String) -> AnyView
    typealias RBuilder = (T) -> AnyView
    var builder: (@escaping HBuilder, @escaping RBuilder) -> Content
    var body: some View {
        // NOTE this is where I'd like to avoid type-erasure to AnyView
        builder({ AnyView( Text("Header \($0)") )},
                { AnyView( Text("Row \(String(describing: $0))") ) })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View { ContentView() }
}
</code>```

Two related questions that didn't quite provide a solution:

65810765 - How to create a struct parameter that is a closure with input, returning some View instead of AnyView in SwiftUI?

64655195 - How to avoid casting SwiftUI views to AnyView when passing them in as a parameter to a function?

答:
I have a working answer to my own question.

Creating a 'wrapper' view for the row, which will serve the explicit type used in the row builder closure:

```<code>// new 'wrapper' view, which can contain Text, LazyVGrid, etc.
struct RowView<T: Hashable>: View {
    var value: T
    var body: some View {
        Text("Row \(String(describing: value))")
    }
}

// update to original BaseTable
struct BaseTable<Content: View, T: Hashable>: View {
    typealias HBuilder = (String) -> Text
    typealias RBuilder = (T) -> RowView<T>
    var builder: (@escaping HBuilder, @escaping RBuilder) -> Content
    var body: some View {
        builder({ Text("Header \($0)") },
                { RowView<T>(value: $0) })
    }
}
</code>```

Thanks to the commenters!

Body:
I'm trying to create table views based on both List and ScrollView, with a shared base view. My current attempt uses a builder-based approach, but requires closures with AnyView type erasure.

My goal is to avoid using AnyView type erasure, to improve performance, scalability, and design.

My attempts to re-design with generic type parameters have so far failed.

The simplified (and working) code example below displays only a single String column, but captures the basic challenge. (In actuality, these are multi-column tables with various data types, specialized formatters, modifiers, etc.)

import SwiftUI

struct ContentView: View {
    let data = ["a", "b", "c", "d"]
    var body: some View {
        HStack {
            ListTable(title: "My List", data: data)
            ScrollTable(title: "My Scroll", data: data)
        }
    }
}

struct ListTable<T: Hashable>: View {
    var title: String, data: [T]
    var body: some View {
        BaseTable() { header, row in
            VStack {
                header(title)
                List(data, id: \.self) { row($0) }
            }
        }
    }
}

struct ScrollTable<T: Hashable>: View {
    var title: String, data: [T]
    var body: some View {
        BaseTable() { header, row in
            VStack {
                header(title)
                ScrollView { ForEach(data, id: \.self) { row($0) } }
            }
        }
    }
}

struct BaseTable<Content: View, T: Hashable>: View {
    typealias HBuilder = (String) -> AnyView
    typealias RBuilder = (T) -> AnyView
    var builder: (@escaping HBuilder, @escaping RBuilder) -> Content
    var body: some View {
        // NOTE this is where I'd like to avoid type-erasure to AnyView
        builder({ AnyView( Text("Header \($0)") )},
                { AnyView( Text("Row \(String(describing: $0))") ) })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View { ContentView() }
}

Two related questions that didn't quite provide a solution:

65810765 - How to create a struct parameter that is a closure with input, returning some View instead of AnyView in SwiftUI?

64655195 - How to avoid casting SwiftUI views to AnyView when passing them in as a parameter to a function?

Body:
I have a working answer to my own question.

Creating a 'wrapper' view for the row, which will serve the explicit type used in the row builder closure:

// new 'wrapper' view, which can contain Text, LazyVGrid, etc.
struct RowView<T: Hashable>: View {
    var value: T
    var body: some View {
        Text("Row \(String(describing: value))")
    }
}

// update to original BaseTable
struct BaseTable<Content: View, T: Hashable>: View {
    typealias HBuilder = (String) -> Text
    typealias RBuilder = (T) -> RowView<T>
    var builder: (@escaping HBuilder, @escaping RBuilder) -> Content
    var body: some View {
        builder({ Text("Header \($0)") },
                { RowView<T>(value: $0) })
    }
}

Thanks to the commenters!


问:
How to find the corresponding pair of inbound and outbound messages in a soap handler
When I use a SOAP handler, I get the handleMessage method invoked both on the inbound and the outbound messasge. However, if there are many clients sending many messages, how can I see which two calls to handleMessage belong to a pair of corresponding inbound and outbound message? E.g. I want to build a SOAP handler which measures performance by determining the system time on the way in and on the way out, so I have to catch a pair of corresponding messages.
Thanks for your help,
Thomas</p>

答:
I just found an answer:

What I had in mind was something like

```<code>public class ServerMessageHandler implements SOAPHandler<SOAPMessageContext> {

private long timeIn;

@Override
public boolean handleMessage(SOAPMessageContext messageContext) {
    boolean outbound = (Boolean) messageContext.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {this.timeIn = System.currentTimeMillis();}
    else {System.out.println("time: " + (System.currentTimeMillis() - this.timeIn));}
    return true;
}
...
}
</code>```

So in order to measure the processing time, it is important to compare the outgoing time with the corresponding entering time, not just the entering time for some other client that entered in the meantime.
But a solution would be to use e.g. messageContext.get (MessageContext.SERVLET_REQUEST):

```<code>public boolean handleMessage(SOAPMessageContext messageContext) {
    boolean outbound = (Boolean) messageContext.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    ServletRequest request = (ServletRequest) messageContext.get (MessageContext.SERVLET_REQUEST);
    if (!outbound) {
        request.setAttribute("timeIn", System.currentTimeMillis());
    } else {
        Long timeIn = (Long) request.getAttribute("timeIn");
        System.out.println("time needed: " + (System.currentTimeMillis() - timeIn));
    }
    return true;
}
</code>```

Body:
I just found an answer:

What I had in mind was something like

public class ServerMessageHandler implements SOAPHandler<SOAPMessageContext> {

private long timeIn;

@Override
public boolean handleMessage(SOAPMessageContext messageContext) {
    boolean outbound = (Boolean) messageContext.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {this.timeIn = System.currentTimeMillis();}
    else {System.out.println("time: " + (System.currentTimeMillis() - this.timeIn));}
    return true;
}
...
}

So in order to measure the processing time, it is important to compare the outgoing time with the corresponding entering time, not just the entering time for some other client that entered in the meantime.
But a solution would be to use e.g. messageContext.get (MessageContext.SERVLET_REQUEST):

public boolean handleMessage(SOAPMessageContext messageContext) {
    boolean outbound = (Boolean) messageContext.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    ServletRequest request = (ServletRequest) messageContext.get (MessageContext.SERVLET_REQUEST);
    if (!outbound) {
        request.setAttribute("timeIn", System.currentTimeMillis());
    } else {
        Long timeIn = (Long) request.getAttribute("timeIn");
        System.out.println("time needed: " + (System.currentTimeMillis() - timeIn));
    }
    return true;
}


问:
How to get the all the values in multiple columns and store them in one variable
I'm trying to get the values of 4 columns (N, P, R, T) and store them in one column.
Also, I thought of doing the same thing but for rows ( So like concatenate 4 cells in 4 columns and store them in a variable via a for loop). I think I would start doung that when I figure the columns first.

for example:-

so here i want to store the values of each column and store them in one variable and then sum all 4 values to get the value of all four columns which is (14+12+11+7) which is 44.

I wrote this code but it doesn't seem to me like its storing the values.

```<code>function percentage(){

  const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
 var range=thisSheet.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
 var rangeN= thisSheet.getRange("N3:N");
 var valueN=rangeN.getValues();
 var rangeP= thisSheet.getRange("P3:P");
 var valueP=rangeP.getValues();
 var rangeR= thisSheet.getRange("R3:R");
 var valueR=rangeR.getValues();
 var rangeT= thisSheet.getRange("T3:T");
 var valueT=rangeT.getValues();
 console.log()
 var val =valueN + valueP + valueR + valueT;

}
</code>```

would really appreciate the help.

If you need more info please let me know

答:
This might do the works for you

```<code>function percentage(){

    const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');

    var range=ss.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
    var rangeN= ss.getRange("N3:N");
    var valueN=rangeN.getValues();
    var rangeP= ss.getRange("P3:P");
    var valueP=rangeP.getValues();
    var rangeR= ss.getRange("R3:R");
    var valueR=rangeR.getValues();
    var rangeT= ss.getRange("T3:T");
    var valueT=rangeT.getValues();
    //you can use concat or creat a new array to store these values.
    const array = valueN.concat(valueP,valueR,valueT).flat();
    //then use array.reduce function to sum all the items in the array.
    const sum = array.reduce((value,sum) => value+sum)
    // you will get the out put as 44
    console.log(sum)

}
</code>```

Is that what you asking for?

```<code>const string = array.toString();
console.log(string)
</code>```

Body:
I'm trying to get the values of 4 columns (N, P, R, T) and store them in one column.
Also, I thought of doing the same thing but for rows ( So like concatenate 4 cells in 4 columns and store them in a variable via a for loop). I think I would start doung that when I figure the columns first.

for example:-

so here i want to store the values of each column and store them in one variable and then sum all 4 values to get the value of all four columns which is (14+12+11+7) which is 44.

I wrote this code but it doesn't seem to me like its storing the values.

function percentage(){

  const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
 var range=thisSheet.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
 var rangeN= thisSheet.getRange("N3:N");
 var valueN=rangeN.getValues();
 var rangeP= thisSheet.getRange("P3:P");
 var valueP=rangeP.getValues();
 var rangeR= thisSheet.getRange("R3:R");
 var valueR=rangeR.getValues();
 var rangeT= thisSheet.getRange("T3:T");
 var valueT=rangeT.getValues();
 console.log()
 var val =valueN + valueP + valueR + valueT;

}

would really appreciate the help.

If you need more info please let me know

Body:
This might do the works for you

function percentage(){

    const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');

    var range=ss.getRangeList(['N3:N', 'P3:P', 'R3:R', 'T3:T']);
    var rangeN= ss.getRange("N3:N");
    var valueN=rangeN.getValues();
    var rangeP= ss.getRange("P3:P");
    var valueP=rangeP.getValues();
    var rangeR= ss.getRange("R3:R");
    var valueR=rangeR.getValues();
    var rangeT= ss.getRange("T3:T");
    var valueT=rangeT.getValues();
    //you can use concat or creat a new array to store these values.
    const array = valueN.concat(valueP,valueR,valueT).flat();
    //then use array.reduce function to sum all the items in the array.
    const sum = array.reduce((value,sum) => value+sum)
    // you will get the out put as 44
    console.log(sum)

}

Is that what you asking for?

const string = array.toString();
console.log(string)


问:
How to get Sentence From Long String which contains specific Word using PHP
I know How to check if a string contains a specific word

```<code>if (str_contains('How are you', 'are')) {
    echo 'true';
}
</code>```

But I am looking for give search result like below to my users

so if my string is like below

Paragraph development begins with the formulation of the controlling
idea. This idea directs the paragraph’s development. Often, the
controlling idea of a paragraph will appear in the form of a topic
sentence. In some cases, you may need more than one sentence to
express a paragraph’s controlling idea.

and then if my user search with word like idea directs then I want show result like This idea directs the paragraph’s development

I do not have idea which PHP function can help me for achieve my goal. Let me know if anyone here can help me for achieve my goal. Thanks!

答:
There is no simple function to achieve this directly. You will have to write an algorithm to get it done. Something similar below.

```<code>$text = "Paragraph development begins with the formulation of the controlling idea. This idea directs the paragraph’s development. Often, the controlling idea of a paragraph will appear in the form of a topic sentence. In some cases, you may need more than one sentence to express a paragraph’s controlling idea.";
$search = "idea directs";
$sentenses = explode(".", $text);

for($i = 0; i < sizeof($sentenses); $i++){
    if(strpos($sentenses[$i], $search))
        echo $sentenses[$i];
}
</code>```

convert the text into lowercase will help you to search case-insensitive,

Body:
I know How to check if a string contains a specific word

if (str_contains('How are you', 'are')) {
    echo 'true';
}

But I am looking for give search result like below to my users

so if my string is like below

Paragraph development begins with the formulation of the controlling
idea. This idea directs the paragraph’s development. Often, the
controlling idea of a paragraph will appear in the form of a topic
sentence. In some cases, you may need more than one sentence to
express a paragraph’s controlling idea.

and then if my user search with word like idea directs then I want show result like This idea directs the paragraph’s development

I do not have idea which PHP function can help me for achieve my goal. Let me know if anyone here can help me for achieve my goal. Thanks!

Body:
There is no simple function to achieve this directly. You will have to write an algorithm to get it done. Something similar below.

$text = "Paragraph development begins with the formulation of the controlling idea. This idea directs the paragraph’s development. Often, the controlling idea of a paragraph will appear in the form of a topic sentence. In some cases, you may need more than one sentence to express a paragraph’s controlling idea.";
$search = "idea directs";
$sentenses = explode(".", $text);

for($i = 0; i < sizeof($sentenses); $i++){
    if(strpos($sentenses[$i], $search))
        echo $sentenses[$i];
}

convert the text into lowercase will help you to search case-insensitive,


问:
typescript how to add new item to the beginning of an array
I used array.unshift() with my Angular2 project. And I got

```<code>TypeError: Cannot read property 'unshift' of undefined.
</code>```

Typescript is a superset of JavaScript. Why array.unshift() is not recognized?

How can I add new item to the beginning of an array with Typescript?

答:
```<code>let fruits = ["Banana", "Cherry"]
fruits.unshift("Apple")
</code>```
<p>>["Apple", "Banana", "Cherry"]</p>

Body:
I used array.unshift() with my Angular2 project. And I got

TypeError: Cannot read property 'unshift' of undefined.

Typescript is a superset of JavaScript. Why array.unshift() is not recognized?

How can I add new item to the beginning of an array with Typescript?

Body:
let fruits = ["Banana", "Cherry"]
fruits.unshift("Apple")

>["Apple", "Banana", "Cherry"]