问:
async functions inside jquery each() loops
I have a loop running for each selected checkbox in Javascript / Jquery.

Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.

```<code>$('#exec-perm').on('click',  function () {
            var checkboxPermanent;
            $('#checks-perm input').each(async function () {
                checkboxPermanent = $(this).attr('value');
                isChecked = $(this).prop('checked');
                permanent = permanent_layers[checkboxPermanent]   // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
                pixel_permanent = pixel_permanent_layers[checkboxPermanent]
                if (permanent) {
                    if (!isChecked) {
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                    } else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
                        //map.addLayer(permanent)
                        //map.addLayer(pixel_permanent)
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                        ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                        ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                    } else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                        permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
                        pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
                        permanent_layers[checkboxPermanent] = permanent; // armazena o valor  no array para que possa cair na condicional que irá excluir os layers do control
                        pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
                        //map.addLayer(permanent);
                        //map.addLayer(pixel_permanent);
                        ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                        ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                    }
                } else if (isChecked) {
                    console.log(checkboxPermanent)
                    permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
                    console.log(permanent)
                    pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
                    //console.log(checkboxPermanent)
                    permanent_layers[checkboxPermanent] = permanent; // armazena o valor  no array para que possa cair na condicional que irá excluir os layers do control
                    pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
                    //map.addLayer(permanent);
                    //map.addLayer(pixel_permanent);
                    ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                    ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                }
                if (checkboxPermanent == 'altimetria') {
                    leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
                    leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
                } else {
                    leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
                    leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
                }
            });
        })
</code>```

If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..

```<code>async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
        //var colorRampSLD = getStyles(faz_value, checkboxPermanent)

        if (checkboxPermanent == 'altimetria') {
            var raster_name = checkboxPermanent + '_' + faz_value
            getColors = await getStyles(faz_value, checkboxPermanent)
            var colorEnv = '';

            for (var j = 0; j < getColors.length; j++) {
                if (j + 1 >= getColors.length) {
                    colorEnv += 'c' + j + ':' + getColors[j]
                } else {
                    colorEnv += 'c' + j + ':' + getColors[j] + ';'
                }
            }

            return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
                layers: 'Emp:' + raster_name,
                transparent: true,
                format: 'image/png',
            }).setParams({
                env: colorEnv
            })
        } else {
            return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
                layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
                transparent: true,
                format: 'image/png',
            })
        }

    }
</code>```

What Am I missing here?

答:
Check here:

```<code> console.log(checkboxPermanent)
 permanent = wmsPermRasterCall(checkboxPermanent, faz_value,  profundidade_value);
 console.log(permanent)
</code>```

This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.

You need to wait for the result of wmsPermRasterCall using await:

```<code> console.log(checkboxPermanent)
 permanent = await wmsPermRasterCall(checkboxPermanent, faz_value,  profundidade_value);
 console.log(permanent)
</code>```

Your code will halt until wmsPermRasterCall is finished.

Body:
I have a loop running for each selected checkbox in Javascript / Jquery.

Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.

$('#exec-perm').on('click',  function () {
            var checkboxPermanent;
            $('#checks-perm input').each(async function () {
                checkboxPermanent = $(this).attr('value');
                isChecked = $(this).prop('checked');
                permanent = permanent_layers[checkboxPermanent]   // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
                pixel_permanent = pixel_permanent_layers[checkboxPermanent]
                if (permanent) {
                    if (!isChecked) {
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                    } else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
                        //map.addLayer(permanent)
                        //map.addLayer(pixel_permanent)
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                        ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                        ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                    } else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
                        map.removeLayer(permanent)
                        map.removeLayer(pixel_permanent)
                        ctrlLayers.removeLayer(permanent)
                        ctrlLayers.removeLayer(pixel_permanent)
                        permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
                        pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
                        permanent_layers[checkboxPermanent] = permanent; // armazena o valor  no array para que possa cair na condicional que irá excluir os layers do control
                        pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
                        //map.addLayer(permanent);
                        //map.addLayer(pixel_permanent);
                        ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                        ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                    }
                } else if (isChecked) {
                    console.log(checkboxPermanent)
                    permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
                    console.log(permanent)
                    pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
                    //console.log(checkboxPermanent)
                    permanent_layers[checkboxPermanent] = permanent; // armazena o valor  no array para que possa cair na condicional que irá excluir os layers do control
                    pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
                    //map.addLayer(permanent);
                    //map.addLayer(pixel_permanent);
                    ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
                    ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
                }
                if (checkboxPermanent == 'altimetria') {
                    leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
                    leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
                } else {
                    leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
                    leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
                }
            });
        })

If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..

async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
        //var colorRampSLD = getStyles(faz_value, checkboxPermanent)

        if (checkboxPermanent == 'altimetria') {
            var raster_name = checkboxPermanent + '_' + faz_value
            getColors = await getStyles(faz_value, checkboxPermanent)
            var colorEnv = '';

            for (var j = 0; j < getColors.length; j++) {
                if (j + 1 >= getColors.length) {
                    colorEnv += 'c' + j + ':' + getColors[j]
                } else {
                    colorEnv += 'c' + j + ':' + getColors[j] + ';'
                }
            }

            return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
                layers: 'Emp:' + raster_name,
                transparent: true,
                format: 'image/png',
            }).setParams({
                env: colorEnv
            })
        } else {
            return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
                layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
                transparent: true,
                format: 'image/png',
            })
        }

    }

What Am I missing here?

Body:
Check here:

 console.log(checkboxPermanent)
 permanent = wmsPermRasterCall(checkboxPermanent, faz_value,  profundidade_value);
 console.log(permanent)

This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.

You need to wait for the result of wmsPermRasterCall using await:

 console.log(checkboxPermanent)
 permanent = await wmsPermRasterCall(checkboxPermanent, faz_value,  profundidade_value);
 console.log(permanent)

Your code will halt until wmsPermRasterCall is finished.


来源: stackexchange

问:
Domain Driven Design - How do I model a Company and Employee use case?
I've been digging into DDD for the first time the last few weeks. I'm developing an HR application and am really struggling with the idea of Aggregate Roots.

So the current entities would be:

Company

Employee

Now given the lifecycle of an Employee, it makes sense at first to include it as a child entity on Company. An Employee can be added to a Company (new hire or existing) and then that Employee could resign or be fired - at which point that Employee record would likely be updated with some kind of status, so it can be differentiated from active Employees.

In regards to domain logic, every Employee at a Company must have a unique email. So if a Company always contained a list of all its Employees, I imagined that could be modeled as:

company.AddEmployee(employee) - This method would contain logic that makes sure the email is unique. In addition, it would update the size property of the Company, based on how many Employees they have. (<100 is small, <500 is medium, etc)

Now the biggest issue I have seen people discuss is concerning large Aggregates. I think this use case would fall under that concern, as a Company could have 10k+ Employees in this HR application. If I'm adding a single Employee at a time, it seems really wasteful to gather all 10k+, even if it's just their emails.

Am I doing the right thing here by making the Company the Aggregate Root, or is there a better way?

答:
You can keep Company as the aggregate root, but I'd use domain events to guard against duplicate emails.

My approach would be along the following lines:

```<code>class Company
{
    List<Employee> Employees = new List<Employee>();
    public int EmployeeCount { get; private set; }

    public void AddEmployee(Employee employee)
    {
        Employees.Add(employee);

        EmployeeCount++;

        AddDomainEvent(new EmployeeCreated(employee));
    }
}
</code>```

Retrieve Company without existing employees.  Just retrieve the EmployeeCount property.

Call the AddEmployee method:

Add the employee to collection

Increment EmployeeCount

Add a domain event for the new employee.

Before committing the Unit of Work, process all domain events stored on your entities in the unit of work.  In this case that will be the one EmployeeCreated event.

That event will include the proposed email of the new employee.

Your domain event handler can make a dB query that returns a scalar True/False value if the proposed email address has been used.

If it has been used, throw exception.

If no errors thrown, then commit the unit of work.

To prevent concurrency issues, add a concurrency token on Company, so that we don't have two simultaneous calls to AddEmployee resulting in two new employees in the dB but only a single increment of the Employee count.

https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation#the-deferred-approach-to-raise-and-dispatch-events

ContentLicense: CC BY-SA 4.0

Body:
You can keep Company as the aggregate root, but I'd use domain events to guard against duplicate emails.

My approach would be along the following lines:

class Company
{
    List<Employee> Employees = new List<Employee>();
    public int EmployeeCount { get; private set; }

    public void AddEmployee(Employee employee)
    {
        Employees.Add(employee);

        EmployeeCount++;

        AddDomainEvent(new EmployeeCreated(employee));
    }
}

Retrieve Company without existing employees.  Just retrieve the EmployeeCount property.

Call the AddEmployee method:

Add the employee to collection

Increment EmployeeCount

Add a domain event for the new employee.

Before committing the Unit of Work, process all domain events stored on your entities in the unit of work.  In this case that will be the one EmployeeCreated event.

That event will include the proposed email of the new employee.

Your domain event handler can make a dB query that returns a scalar True/False value if the proposed email address has been used.

If it has been used, throw exception.

If no errors thrown, then commit the unit of work.

To prevent concurrency issues, add a concurrency token on Company, so that we don't have two simultaneous calls to AddEmployee resulting in two new employees in the dB but only a single increment of the Employee count.

https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation#the-deferred-approach-to-raise-and-dispatch-events


问:
Problem with Tweet! for jQuery
Tweet! for jQuery works fine most of the time, but sporadically I get this:

```<code>"NetworkError: 400 Bad Request - http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jlowgren&count=5&include_rts=1&page=1&callback=jQuery16202827138555332698_1313661810432&_=1313661810465
</code>```

This is the jQuery call:

```<code>$(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});
</code>```

The site in question is www.jorum.se.

Anyone with a handsome solution for this will be richly rewarded in karma!

答: It works fine for me all the time (after few refreshes). Isn't there limit per IP ?</p>

ContentLicense: CC BY-SA 3.0

Title: Problem with Tweet! for jQuery

Body:
Tweet! for jQuery works fine most of the time, but sporadically I get this:

"NetworkError: 400 Bad Request - http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jlowgren&count=5&include_rts=1&page=1&callback=jQuery16202827138555332698_1313661810432&_=1313661810465

This is the jQuery call:

$(".tweet").tweet({
    username: "jlowgren",
    count: 5,
    loading_text: "Loading tweets…",
    refresh_interval: 120
});

The site in question is www.jorum.se.

Anyone with a handsome solution for this will be richly rewarded in karma!


问:
Correctly sending Flink state to Kafka
I'm building a Kafka -> Flink -> Kafka pipeline that works with delineated "session" data. My input Kafka topic has data in the following format and constitutes one session for session_key:

```<code>start_event(session_key, some_other_data...)
entry_event(session_key, some_other_data...)
entry_event(session_key, some_other_data...)
...
entry_event(session_key, some_other_data...)
end_event(session_key, some_other_data...)
</code>```

Each session like this is about 100 events long, comes in quickly (every 1-2 seconds), all events share the same session_key, and I'm transforming the session into a series of 20 or so events that go into the output topic. To build these events, I need to know about the entire session, so I need to wait for the end_event to arrive to be able to run the processing and push output events to the output topic.

The implementation is fairly simple - key by session_key, store start_event into ValueState, entries into ListState, and then when end_event arrives, run the processing logic over all events and push the results into the output Kafka topic.

My question is around checkpointing and possible failures - let's say checkpointing starts after end_event makes it out of Kafka. The offset is committed to Kafka and the checkpointing barrier gets to my processing operator which fails right before it (Kafka is down now).

How should I correctly recover from this? If the Kafka offset is already committed, and no end_event will ever make it out of Kafka for that session_key, how do I trigger the processing operator for my saved state later on? Or would the Kafka offset not be committed in this scenario and end_event will go thru Flink once more?

答:
Flink commits Kafka offsets only for the sake of monitoring, but does not rely on them for fault tolerance (btw, it does it when checkpoints are completed):

Note that Kafka source does NOT rely on committed offsets for fault tolerance. Committing offset is only for exposing the progress of consumer and consuming group for monitoring.

See Consumer Offset Committing.

Topic offsets are saved as a part of the Kafka source state during a checkpoint. In the described scenario, the whole checkpoint would fail and Flink would start consuming topics starting from the offsets saved in the previous checkpoint. No messages would be lost, but some could be possibly duplicated (assuming AT_LEAST_ONCE checkpointing mode).

So yes, the end_event will go thru Flink once more.

Title: Correctly sending Flink state to Kafka

Body:
I'm building a Kafka -> Flink -> Kafka pipeline that works with delineated "session" data. My input Kafka topic has data in the following format and constitutes one session for session_key:

start_event(session_key, some_other_data...)
entry_event(session_key, some_other_data...)
entry_event(session_key, some_other_data...)
...
entry_event(session_key, some_other_data...)
end_event(session_key, some_other_data...)

Each session like this is about 100 events long, comes in quickly (every 1-2 seconds), all events share the same session_key, and I'm transforming the session into a series of 20 or so events that go into the output topic. To build these events, I need to know about the entire session, so I need to wait for the end_event to arrive to be able to run the processing and push output events to the output topic.

The implementation is fairly simple - key by session_key, store start_event into ValueState, entries into ListState, and then when end_event arrives, run the processing logic over all events and push the results into the output Kafka topic.

My question is around checkpointing and possible failures - let's say checkpointing starts after end_event makes it out of Kafka. The offset is committed to Kafka and the checkpointing barrier gets to my processing operator which fails right before it (Kafka is down now).

How should I correctly recover from this? If the Kafka offset is already committed, and no end_event will ever make it out of Kafka for that session_key, how do I trigger the processing operator for my saved state later on? Or would the Kafka offset not be committed in this scenario and end_event will go thru Flink once more?


问:
prevent a checkbox menu from animating on page load
I have a hamburger menu that functions with a checkbox to animate a menu up and down the page. when the page loads, the menu will slide down and back up the page. What I'd like it to do is just stay hidden when the page loads. Here's the CSS of how it's set up now:

.overlay {
  position: fixed;
  background: var(--taupe-color);
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  visibility: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.menu .toggler:checked~.overlay {
  animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked)~.overlay {
  animation: slideUp 2s forwards;
}

@keyframes slideDown {
  0% {
    transform: translateY(-100%)
  }
  100% {
    visibility: visible;
    transform: translateY(0%)
  }
}

@keyframes slideUp {
  0% {
    transform: translateY(0%)
  }
  100% {
    visibility: visible;
    transform: translateY(-100%);
  }
}
```
<p>I've tried setting the opacity to 0 in the overlay class and then setting it to 1 in the animation which fixes the loading problem but when the checkbox is not checked, it no longer animates back up the page, it will just disappear. Using display none also doesn't solve the problem. Is there a way for the menu to stay hidden during page loading and only animate when the user interacts with the menu button/checkbox?</p>
<p>EDIT: adding HTML</p>
```

        <input type="checkbox" class="toggler">

```

答:
Ok I figured out a solution. Essentially, instead of preventing the keyframe from animating on page load, I made it hidden so you couldn't see it. I chose to do this by setting the initial opacity to 0.

```<code>.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
visibility: hidden;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
</code>```

Now the only issue is to set the opacity back to 1 before animating it. I realized that I could set opacity back to 1 during the hover state. You'll need to do this to the menu button when it's checked and unchecked:

```<code>.menu .toggler:checked:hover ~ .overlay {
opacity: 1;
}

.menu .toggler:not(:checked):hover ~ .overlay {
opacity: 1;
}
</code>```

this allowed the menu animation to be hidden during page load and only be visible once the user hovers over the mouse button and clicks it.

EDIT:
I realized that the menu disappears once the user navigates away form the menu button so I needed to find a way for the menu to remain visible even when the user is no longer hovering over the menu button. I think there's a way to keep the hover state even after the mouse moves using js but since my menu is full screen, I figured I can create a hover state for the menu screen itself. so far I haven't found any bugs. I just added this code to my previous solution:

```<code>.overlay:hover {
opacity: 1;
}
</code>```

Edit 2:
Ok the previous solution didn't really work well because if the mouse was not over the menu while it was closing it would abruptly disappear. Also, it did not account for users on touch screens. The best solution was to create an onclick

```<code>onclick="document.getElementById('overlay').style.opacity='1'"
</code>```

so long story short, I could not find a way to prevent a keyframe animation from happening on page load but I could hide it and then bring it back. going to mark myself as the answer now

Body:
I have a hamburger menu that functions with a checkbox to animate a menu up and down the page. when the page loads, the menu will slide down and back up the page. What I'd like it to do is just stay hidden when the page loads. Here's the CSS of how it's set up now:

.overlay {
  position: fixed;
  background: var(--taupe-color);
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  visibility: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.menu .toggler:checked~.overlay {
  animation: slideDown 2s forwards;
}

.menu .toggler:not(:checked)~.overlay {
  animation: slideUp 2s forwards;
}

@keyframes slideDown {
  0% {
    transform: translateY(-100%)
  }
  100% {
    visibility: visible;
    transform: translateY(0%)
  }
}

@keyframes slideUp {
  0% {
    transform: translateY(0%)
  }
  100% {
    visibility: visible;
    transform: translateY(-100%);
  }
}

I've tried setting the opacity to 0 in the overlay class and then setting it to 1 in the animation which fixes the loading problem but when the checkbox is not checked, it no longer animates back up the page, it will just disappear. Using display none also doesn't solve the problem. Is there a way for the menu to stay hidden during page loading and only animate when the user interacts with the menu button/checkbox?

EDIT: adding HTML

        <input type="checkbox" class="toggler">

Body:
Ok I figured out a solution. Essentially, instead of preventing the keyframe from animating on page load, I made it hidden so you couldn't see it. I chose to do this by setting the initial opacity to 0.

.overlay {
position: fixed;
background: var(--taupe-color);
opacity: 0;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
visibility: hidden;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}

Now the only issue is to set the opacity back to 1 before animating it. I realized that I could set opacity back to 1 during the hover state. You'll need to do this to the menu button when it's checked and unchecked:

.menu .toggler:checked:hover ~ .overlay {
opacity: 1;
}

.menu .toggler:not(:checked):hover ~ .overlay {
opacity: 1;
}

this allowed the menu animation to be hidden during page load and only be visible once the user hovers over the mouse button and clicks it.

EDIT:
I realized that the menu disappears once the user navigates away form the menu button so I needed to find a way for the menu to remain visible even when the user is no longer hovering over the menu button. I think there's a way to keep the hover state even after the mouse moves using js but since my menu is full screen, I figured I can create a hover state for the menu screen itself. so far I haven't found any bugs. I just added this code to my previous solution:

.overlay:hover {
opacity: 1;
}

Edit 2:
Ok the previous solution didn't really work well because if the mouse was not over the menu while it was closing it would abruptly disappear. Also, it did not account for users on touch screens. The best solution was to create an onclick

onclick="document.getElementById('overlay').style.opacity='1'"

so long story short, I could not find a way to prevent a keyframe animation from happening on page load but I could hide it and then bring it back. going to mark myself as the answer now


问:
How do I compare an entity in my local context with the one in the database in EF Core?
EF Core 6 and .NET 6.

Suppose all my entities have a LastUpdateAt property, which is a DateTime that gets updated every time an entity is added or modified.

I get an entity from the context and show it to the user (web page, WPF window, whatever). At some point, the user clicks a Save button.

Before I save, I want to check if the entity has been updated by someone else since I got my copy. However, I'm struggling to see how to do this.

If I query the context, it just gives me back the entity I already have (including any changes my user has made).

If I refresh the entity, it overwrites the one in my context, losing my user's changes.

How do I check if the database version has a newer time stamp than the one in my context?

Thanks

答:
If you are loading an entity, keeping a DbContext instance open, updating that entity, then saving to the same DbContext instance then by default you are relying on EF to manage concurrency. This follows a "last in wins". You can let EF manage the concurrency by adding a [ConcurrencyCheck] on the LastUpdateAt property or using a Row Version via [Timestamp]. This will cause EF to fail updating if the underlying data has been updated. From there you have to decide how you want to handle it.

If you want to perform the concurrency check yourself then there are a couple of options.

Structure your code to shorten the lifespan of the DbContext using either detached entities or projected View Models. This will generally have flow-on benefits to your code performance as the original longer-lived DbContext can easily find ways to cause bloat, or accumulate "poisoned" entities if alive too long. Automapper is a great tool to assist here where you can use ProjectTo to get the view models, then Map(source, destination) to copy the values across afterward. In this way you load the data including the last modified at value, make your changes, then when saving, you load the data, validate the modified at etc. then copy the values across and save.

Scope a DbContext instance to check the data before saving.

.

```<code>private DateTime getFooLastUpdateAt(int fooId)
{
    using(var context = new AppDbContext())
    {
         var lastUpdateAt = context.Foos
             .Where(x => x.FooId == fooId)
             .Select(x => x.LastUpdateAt)
             .Single();
         return lastUpdateAt;
    }
}
</code>```

This could use an injected DbContext factory or such to create the DbContext instance..

Body:
If you are loading an entity, keeping a DbContext instance open, updating that entity, then saving to the same DbContext instance then by default you are relying on EF to manage concurrency. This follows a "last in wins". You can let EF manage the concurrency by adding a [ConcurrencyCheck] on the LastUpdateAt property or using a Row Version via [Timestamp]. This will cause EF to fail updating if the underlying data has been updated. From there you have to decide how you want to handle it.

If you want to perform the concurrency check yourself then there are a couple of options.

Structure your code to shorten the lifespan of the DbContext using either detached entities or projected View Models. This will generally have flow-on benefits to your code performance as the original longer-lived DbContext can easily find ways to cause bloat, or accumulate "poisoned" entities if alive too long. Automapper is a great tool to assist here where you can use ProjectTo to get the view models, then Map(source, destination) to copy the values across afterward. In this way you load the data including the last modified at value, make your changes, then when saving, you load the data, validate the modified at etc. then copy the values across and save.

Scope a DbContext instance to check the data before saving.

.

private DateTime getFooLastUpdateAt(int fooId)
{
    using(var context = new AppDbContext())
    {
         var lastUpdateAt = context.Foos
             .Where(x => x.FooId == fooId)
             .Select(x => x.LastUpdateAt)
             .Single();
         return lastUpdateAt;
    }
}

This could use an injected DbContext factory or such to create the DbContext instance..


问:
Libtool Version mismatch error while building gcc
I am trying to add some files to GCC source code, but after running
autoreconf --install --force
i get that error

```<code>libtool: definition of this LT_INIT comes from libtool 2.2.7a.
libtool: You should recreate aclocal.m4 with macros from libtool 2.4.6 Debian-2.4.6-14
libtool: and run autoconf again.
</code>```

even without any source files added if i reconfigure i get the same error.

that's very important as i am adding new functionality to gcc

答:
Using autoreconf --install --force instead of just autoreconf is a bit questionable in this case, but maybe it's for the best.  I am surprised that it did not take care of aclocal.m4 for you automatically, but that's a generated file.  If everything else is ok then you ought to be able to simply delete the current aclocal.m4 and run autoreconf to generate a new one.

If you have an autom4te.cache subdirectory then it would probably be best to delete that first (it will be regenerated by autoreconf, too).

Body:
I am trying to add some files to GCC source code, but after running
autoreconf --install --force
i get that error

libtool: definition of this LT_INIT comes from libtool 2.2.7a.
libtool: You should recreate aclocal.m4 with macros from libtool 2.4.6 Debian-2.4.6-14
libtool: and run autoconf again.

even without any source files added if i reconfigure i get the same error.

that's very important as i am adding new functionality to gcc


问:
how to get the print of section of .aspx page?
I am printing reports as tables in .aspx page

Now i want to print that section containing table. how can i print that section only?

As I got javascript function to print the whole page with window.print() but I want only some section to get printed.

答:
You could use a print stylesheet to hide elements you don't want printed:

```<code><link type="text/css" rel="stylesheet" href="css/print.css" media="print" />
</code>```

(This article on A List Apart has some useful info on print stylesheets: http://www.alistapart.com/articles/goingtoprint/)

Body:
You could use a print stylesheet to hide elements you don't want printed:

<link type="text/css" rel="stylesheet" href="css/print.css" media="print" />

(This article on A List Apart has some useful info on print stylesheets: http://www.alistapart.com/articles/goingtoprint/)


问:
Does Fit.Line use least squares
The method Fit.Line - what algorithm does it use to determine the parameters? Hopefully least squares.</p>

答:
Check the documentation.
https://numerics.mathdotnet.com/api/MathNet.Numerics/Fit.htm#Line

"Least-Squares fitting the points (x,y) to a line y : x -> a+b*x, returning its best fitting parameters as [a, b] array, where a is the intercept and b the slope."

Title: Does Fit.Line use least squares


问:
ModuleNotFoundError: No module named 'virtualenv'
when I try to run virtualenv in command line in mac, it says

```<code>from virtualenv.__main__ import run_with_catch
ModuleNotFoundError: No module named 'virtualenv'
</code>```

but I am able to locate virtualenv with which virtualenv

```<code>/usr/local/bin/virtualenv
</code>```

答: Looks like virtualenv is not installed as a Python package. A simple pip install virtualenv should do the trick.

Body:
when I try to run virtualenv in command line in mac, it says

from virtualenv.__main__ import run_with_catch
ModuleNotFoundError: No module named 'virtualenv'

but I am able to locate virtualenv with which virtualenv

/usr/local/bin/virtualenv


问:
Solving a Positional Argument Error in a Pythonic Class and Method
Disclaimer
To preface this, I am new to programming and even newer to python, so my knowledge of the mechanics of the interpreter is very limited.

Explanation I am currently writing a pythonic code that simulates a text-based game of cheating hangman, which means the program changes the word to evade the player from guessing the correct word using "word families." The game requires three files: hangman.py, play_hangman.py, and dictionary.txt. In hangman.py, I have created a hangman class that contains the self-instance of the class, several methods for producing the necessary objects, and a play method that uses these methods. Then, in play_hangman.py, it calls the hangman instance, and the play method, and puts the play method into a while loop that repeats as long as the player enters "yes" to keep playing.

The Problem I have called the methods into the play function for executing the game. However, it gives me an error saying:

- "12 positional arguments: 'word_length', 'num_guesses',
'remaining_words', 'remainingWords', 'letters_already_guessed',
'askForWordLength', 'printGameStats', 'askForPlayerGuess',
'wordStatus', 'printCountOfRemainingWords', 'retreiveRemainingWords',
and 'askForNumberOfGuesses' "

These are the twelve variables and methods I have called in the def play(): function. I have researched that I need to call an object of the class before the method, which I attempted to do, but does not work. I am not sure how to avoid the error.

HANGMAN.PY

```<code>import re

class Hangman:

    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, lines, length):
        words = []
        for word in lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')
</code>```

答:
None of those methods have self as their first argument.
And that is what is used to define class methods and give access to attributes.
So, adding that "self" keyword is the first step to make your code work.

I would recommend installing a linter, it automatically identifies this kind of error for you:

Body:
Disclaimer
To preface this, I am new to programming and even newer to python, so my knowledge of the mechanics of the interpreter is very limited.

Explanation I am currently writing a pythonic code that simulates a text-based game of cheating hangman, which means the program changes the word to evade the player from guessing the correct word using "word families." The game requires three files: hangman.py, play_hangman.py, and dictionary.txt. In hangman.py, I have created a hangman class that contains the self-instance of the class, several methods for producing the necessary objects, and a play method that uses these methods. Then, in play_hangman.py, it calls the hangman instance, and the play method, and puts the play method into a while loop that repeats as long as the player enters "yes" to keep playing.

The Problem I have called the methods into the play function for executing the game. However, it gives me an error saying:

- "12 positional arguments: 'word_length', 'num_guesses',
'remaining_words', 'remainingWords', 'letters_already_guessed',
'askForWordLength', 'printGameStats', 'askForPlayerGuess',
'wordStatus', 'printCountOfRemainingWords', 'retreiveRemainingWords',
and 'askForNumberOfGuesses' "

These are the twelve variables and methods I have called in the def play(): function. I have researched that I need to call an object of the class before the method, which I attempted to do, but does not work. I am not sure how to avoid the error.

HANGMAN.PY

import re

class Hangman:

    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, lines, length):
        words = []
        for word in lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')


问:
PowerShell collection exported to separate row in CSV
I have the following script that will export all the Office 365 licenses per user that is enabled for a license to a CSV. The export will list each user and then the multiple licenses on the same row like this:
There is not a set number of licenses for each user, users will have different licenses.

Instead of having them export on the same row, I need to have the license for each user on a separate row like this:
How can I modify the script to make that happen?

```<code>    #### All lincesed users###

$JobCollection = @()

$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq "TRUE" }

$count=0
$fullcount = ($mbx | measure-object).count

foreach ($M in $MBX) {

$count++
$search = $m.userprincipalname.tostring()

Write-progress -activity "Getting Calendar $count out of $fullcount --- $search " -percentcomplete (($count / $fullcount)*100) -status "Processing"

$License = (((Get-MsolUser -UserPrincipalName $M.userprincipalname).Licenses.accountskuid) -join ",")

#$queuelink = $job.reportingqueueuri.absoluteuri
#$jobID = $Job.jobid

$Jobs = New-Object psobject
$JObs | Add-Member -MemberType NoteProperty -Name UserPrincipalName -Value $M.userprincipalname
$JObs | Add-Member -MemberType NoteProperty -Name License -Value $license

$JobCollection += $jobs

}

$JobCollection  | export-csv "C:\test\AllMBXlicensse.csv" -NoTypeInformation
</code>```

答:
You can create a nested loop to assign each value to it's corresponding userprincipalname in a PSCustomObject; like you're already doing:

```<code>$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq $true }
$mbxCount = $mbx.count
for ($i = 0; $i -lt $mbx.count; $i++)
{
    $UPN = $mbx[$i].userprincipalname
    $progressSplat = @{
        Activity = "Getting Calendar $i out of $mbx --- $UPN"
        PercentComplete = (($i / $mbxCount)*100)
        Status = "Processing"
    }
    Write-Progress @progressSplat
    $userLicenses = (Get-MsolUser -UserPrincipalName $UPN).Licenses.accountskuid
    foreach ($license in $userLicenses)
    {
        [PSCustomObject]@{
            UserPrincipalName = $UPN
            License = $license
        } | Export-Csv -Path "C:\test\AllMBXlicensse.csv" -Append -Force -NoTypeInformation
    }
}
</code>```

...or, as TheMadTechnician proposed, using a calculated property (very elegant might I add):

```<code>$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq $true }
$mbxCount = $mbx.count
for ($i = 0; $i -lt $mbx.count; $i++)
{
    $UPN = $mbx[$i].userprincipalname
    $progressSplat = @{
        Activity = "Getting Calendar $i out of $mbxCount --- $UPN"
        PercentComplete = (($i / $mbxCount)*100)
        Status = "Processing"
    }
    Write-Progress @progressSplat
    (Get-MsolUser -UserPrincipalName $UPN).Licenses.accountskuid |
        Select-Object -Property @{
            Name = "UserPrincipalName"
            Expression = { $UPN }
        }, @{
            Name = "License"
            Expression = { $_ }
        } | Export-Csv -Path "C:\test\AllMBXlicensse.csv" -Append -Force -NoTypeInformation
}
</code>```

Body:
I have the following script that will export all the Office 365 licenses per user that is enabled for a license to a CSV. The export will list each user and then the multiple licenses on the same row like this:
There is not a set number of licenses for each user, users will have different licenses.

Instead of having them export on the same row, I need to have the license for each user on a separate row like this:
How can I modify the script to make that happen?

    #### All lincesed users###

$JobCollection = @()

$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq "TRUE" }

$count=0
$fullcount = ($mbx | measure-object).count

foreach ($M in $MBX) {

$count++
$search = $m.userprincipalname.tostring()

Write-progress -activity "Getting Calendar $count out of $fullcount --- $search " -percentcomplete (($count / $fullcount)*100) -status "Processing"

$License = (((Get-MsolUser -UserPrincipalName $M.userprincipalname).Licenses.accountskuid) -join ",")

#$queuelink = $job.reportingqueueuri.absoluteuri
#$jobID = $Job.jobid

$Jobs = New-Object psobject
$JObs | Add-Member -MemberType NoteProperty -Name UserPrincipalName -Value $M.userprincipalname
$JObs | Add-Member -MemberType NoteProperty -Name License -Value $license

$JobCollection += $jobs

}

$JobCollection  | export-csv "C:\test\AllMBXlicensse.csv" -NoTypeInformation

Body:
You can create a nested loop to assign each value to it's corresponding userprincipalname in a PSCustomObject; like you're already doing:

$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq $true }
$mbxCount = $mbx.count
for ($i = 0; $i -lt $mbx.count; $i++)
{
    $UPN = $mbx[$i].userprincipalname
    $progressSplat = @{
        Activity = "Getting Calendar $i out of $mbx --- $UPN"
        PercentComplete = (($i / $mbxCount)*100)
        Status = "Processing"
    }
    Write-Progress @progressSplat
    $userLicenses = (Get-MsolUser -UserPrincipalName $UPN).Licenses.accountskuid
    foreach ($license in $userLicenses)
    {
        [PSCustomObject]@{
            UserPrincipalName = $UPN
            License = $license
        } | Export-Csv -Path "C:\test\AllMBXlicensse.csv" -Append -Force -NoTypeInformation
    }
}

...or, as TheMadTechnician proposed, using a calculated property (very elegant might I add):

$mbx = Get-MsolUser -all | Where-Object { $_.isLicensed -eq $true }
$mbxCount = $mbx.count
for ($i = 0; $i -lt $mbx.count; $i++)
{
    $UPN = $mbx[$i].userprincipalname
    $progressSplat = @{
        Activity = "Getting Calendar $i out of $mbxCount --- $UPN"
        PercentComplete = (($i / $mbxCount)*100)
        Status = "Processing"
    }
    Write-Progress @progressSplat
    (Get-MsolUser -UserPrincipalName $UPN).Licenses.accountskuid |
        Select-Object -Property @{
            Name = "UserPrincipalName"
            Expression = { $UPN }
        }, @{
            Name = "License"
            Expression = { $_ }
        } | Export-Csv -Path "C:\test\AllMBXlicensse.csv" -Append -Force -NoTypeInformation
}


问:
Cannot scrape input from dynamic dropdown menu due to  (Python - Selenium)
this is a somewhat discussed problem, however I haven't find a solution in other posts.

I am creating an automation to submit parcels, using Selenium on Python, for this website:
https://www.mondospedizioni.com

To select Country and City, I need to add an input on a text field.
The text field is actually a search field, that opens a dropdown menu upon adding the key.

I fail to select the option and close the dropdown menu, thus filling the "Country"/"City" field and moving fwd.

The div I refer to (Country):

```<code><span class="select2-selection__rendered" id="select2-nazione_mittente-container" title="Selezionare Nazione di ritiro">Selezionare Nazione di ritiro</span>
</code>```

The one for City:

```<code><span class="select2-selection__placeholder">Inserire il CAP e selezionare la località</span>
</code>```

This Post uses Select, but because of the  tags I receive error:

```<code>Select only works on <select> elements, not on <span>.
</code>```

I found another suggestion in this post from Anzel and even this one did not work for me.

My code gets stuck when I try to enter the sender's city, and the error is given to me when the code calls the input field for the receiver's country. My code:

```<code>import pandas as pd
import numpy as np
import time
from datetime import datetime, date

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

import itertools

driver = webdriver.Chrome(executable_path...)
url = "https://www.mondospedizioni.com/"
driver.get(url)
driver.set_page_load_timeout(-1) #Makes sure the webpage is fully loaded before scraping. Thus avoiding errors.

#All Page Components
hoCapito =driver.find_element(By.XPATH, '//*[@id="cookie-bar"]/p/a[1]')

countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-container"]')
cityFrom = driver.find_element(By.XPATH, '//*[@id="loc_mittente"]')
postFrom = driver.find_element(By.XPATH, '//*[@id="cap_mittente"]')

countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-container"]')
cityTo = driver.find_element(By.XPATH, '//*[@id="loc_destinatario"]')
postTo = driver.find_element(By.XPATH, '//*[@id="cap_destinatario"]')

myWeight = driver.find_element(By.XPATH, '//*[@id="peso1"]')
myLength = driver.find_element(By.XPATH, '//*[@id="l1"]')
myWidth = driver.find_element(By.XPATH, '//*[@id="p1"]')
myHeight = driver.find_element(By.XPATH, '//*[@id="h1"]')

calculate = driver.find_element(By.XPATH, '//*[@id="btn-calcola"]')

#MyKeys
driver = webdriver.Chrome(executable_path=r"C:\Users\AndreaPaviglianiti\Jupyter-2022\webdrivers\chromedriver.exe")
url = "https://www.mondospedizioni.com/"
driver.get(url)
driver.set_page_load_timeout(-1) #Makes sure the webpage is fully loaded before scraping. Thus avoiding errors.

hoCapito =driver.find_element(By.XPATH, '//*[@id="cookie-bar"]/p/a[1]')

countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-container"]')
cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-container"]/span')
postFrom = driver.find_element(By.XPATH, '//*[@id="cap_mittente"]')

countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-container"]')
cityTo = driver.find_element(By.XPATH, '//*[@id="loc_destinatario"]')
postTo = driver.find_element(By.XPATH, '//*[@id="cap_destinatario"]')

#Accept Cookies
hoCapito.click()

countryFrom.click()
select_countryFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Italia')
confirm_countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-results"]').click()

cityFrom.click()
select_cityFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Partinico')
confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div').click()

countryTo.click()
select_countryTo = driver.find_element(By.CLASS_NAME, 'select2-search_field').send_keys('Repubblica Slovacca')
confirm_countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-result-885w-Repubblica Slovacca"]').click()

cityTo.send_keys('Bratislava')
postFrom.send_keys(82101)

myWeight.send_keys(30)
myLength.send_keys(47)
myWidth.send_keys(25)
myHeight.send_keys(38)

calculate.click()
time.sleep(3)
driver.set_page_load_timeout(-1)
</code>```

My error (now - based on my latest attempt):

```<code><ipython-input-77-dd29b60fadf7>:2: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(executable_path=r"C:\Users\AndreaPaviglianiti\Jupyter-2022\webdrivers\chromedriver.exe")

---------------------------------------------------------------------------
NoSuchElementException                    Traceback (most recent call last)
<ipython-input-77-dd29b60fadf7> in <module>
     25 cityFrom.click()
     26 select_cityFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Partinico')
---> 27 confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div').click()
     28 #confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div/text()').click()
     29 #confirm_cityFrom = driver.find_element(By.XPATH, '/html/body/span/span/span[2]').click()

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element(self, by, value)
   1242             value = '[name="%s"]' % value
   1243
-> 1244         return self.execute(Command.FIND_ELEMENT, {
   1245             'using': by,
   1246             'value': value})['value']

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)
    422         response = self.command_executor.execute(driver_command, params)
    423         if response:
--> 424             self.error_handler.check_response(response)
    425             response['value'] = self._unwrap_value(
    426                 response.get('value', None))

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)
    245                 alert_text = value['alert'].get('text')
    246             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 247         raise exception_class(message, screen, stacktrace)
    248
    249     def _value_or_default(self, obj: Mapping[_KT, _VT], key: _KT, default: _VT) -> _VT:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="select2-loc_cap_mittente-results"]/li/div"}
  (Session info: chrome=98.0.4758.81)
Stacktrace:
Backtrace:
    Ordinal0 [0x007F7AC3+2587331]
    Ordinal0 [0x0078ADD1+2141649]
    Ordinal0 [0x00683BB8+1063864]
    Ordinal0 [0x006B01CE+1245646]
    Ordinal0 [0x006B03CB+1246155]
    Ordinal0 [0x006DA612+1418770]
    Ordinal0 [0x006C86D4+1345236]
    Ordinal0 [0x006D8A0A+1411594]
    Ordinal0 [0x006C84A6+1344678]
    Ordinal0 [0x006A53F6+1201142]
    Ordinal0 [0x006A62E6+1204966]
    GetHandleVerifier [0x0099DF22+1680738]
    GetHandleVerifier [0x00A50DBC+2413564]
    GetHandleVerifier [0x0088D151+563089]
    GetHandleVerifier [0x0088BF13+558419]
    Ordinal0 [0x0079081E+2164766]
    Ordinal0 [0x00795508+2184456]
    Ordinal0 [0x00795650+2184784]
    Ordinal0 [0x0079F5BC+2225596]
    BaseThreadInitThunk [0x77CDFA29+25]
    RtlGetAppContainerNamedObjectPath [0x77E27A9E+286]
    RtlGetAppContainerNamedObjectPath [0x77E27A6E+238]
</code>```

EDIT
To clarify the matter I am now adding two printscreens that focus on the elements I cannot manage - the Sender's Locality.

It is more advanced to what I am used to (and I am fairly new with Selenium).

答:
```<code>#select2-nazione_mittente-container
</code>```

Simply click the above element

```<code>.select2-search__field
</code>```

Send keys to the above element

```<code>//li[@class='select2-results__option' and contains(@id,'Italia')]
</code>```

Then proceed to click on the li tag with that value.

It's how to deal with any non Select dropdown element.

Title: Cannot scrape input from dynamic dropdown menu due to <span> (Python - Selenium)

Body:
this is a somewhat discussed problem, however I haven't find a solution in other posts.

I am creating an automation to submit parcels, using Selenium on Python, for this website:
https://www.mondospedizioni.com

To select Country and City, I need to add an input on a text field.
The text field is actually a search field, that opens a dropdown menu upon adding the key.

I fail to select the option and close the dropdown menu, thus filling the "Country"/"City" field and moving fwd.

The div I refer to (Country):

Selezionare Nazione di ritiro

The one for City:

Inserire il CAP e selezionare la località

This Post uses Select, but because of the  tags I receive error:

Select only works on <select> elements, not on .

I found another suggestion in this post from Anzel and even this one did not work for me.

My code gets stuck when I try to enter the sender's city, and the error is given to me when the code calls the input field for the receiver's country. My code:

import pandas as pd
import numpy as np
import time
from datetime import datetime, date

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

import itertools

driver = webdriver.Chrome(executable_path...)
url = "https://www.mondospedizioni.com/"
driver.get(url)
driver.set_page_load_timeout(-1) #Makes sure the webpage is fully loaded before scraping. Thus avoiding errors.

#All Page Components
hoCapito =driver.find_element(By.XPATH, '//*[@id="cookie-bar"]/p/a[1]')

countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-container"]')
cityFrom = driver.find_element(By.XPATH, '//*[@id="loc_mittente"]')
postFrom = driver.find_element(By.XPATH, '//*[@id="cap_mittente"]')

countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-container"]')
cityTo = driver.find_element(By.XPATH, '//*[@id="loc_destinatario"]')
postTo = driver.find_element(By.XPATH, '//*[@id="cap_destinatario"]')

myWeight = driver.find_element(By.XPATH, '//*[@id="peso1"]')
myLength = driver.find_element(By.XPATH, '//*[@id="l1"]')
myWidth = driver.find_element(By.XPATH, '//*[@id="p1"]')
myHeight = driver.find_element(By.XPATH, '//*[@id="h1"]')

calculate = driver.find_element(By.XPATH, '//*[@id="btn-calcola"]')

#MyKeys
driver = webdriver.Chrome(executable_path=r"C:\Users\AndreaPaviglianiti\Jupyter-2022\webdrivers\chromedriver.exe")
url = "https://www.mondospedizioni.com/"
driver.get(url)
driver.set_page_load_timeout(-1) #Makes sure the webpage is fully loaded before scraping. Thus avoiding errors.

hoCapito =driver.find_element(By.XPATH, '//*[@id="cookie-bar"]/p/a[1]')

countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-container"]')
cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-container"]/span')
postFrom = driver.find_element(By.XPATH, '//*[@id="cap_mittente"]')

countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-container"]')
cityTo = driver.find_element(By.XPATH, '//*[@id="loc_destinatario"]')
postTo = driver.find_element(By.XPATH, '//*[@id="cap_destinatario"]')

#Accept Cookies
hoCapito.click()

countryFrom.click()
select_countryFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Italia')
confirm_countryFrom = driver.find_element(By.XPATH, '//*[@id="select2-nazione_mittente-results"]').click()

cityFrom.click()
select_cityFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Partinico')
confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div').click()

countryTo.click()
select_countryTo = driver.find_element(By.CLASS_NAME, 'select2-search_field').send_keys('Repubblica Slovacca')
confirm_countryTo = driver.find_element(By.XPATH, '//*[@id="select2-nazione_destinatario-result-885w-Repubblica Slovacca"]').click()

cityTo.send_keys('Bratislava')
postFrom.send_keys(82101)

myWeight.send_keys(30)
myLength.send_keys(47)
myWidth.send_keys(25)
myHeight.send_keys(38)

calculate.click()
time.sleep(3)
driver.set_page_load_timeout(-1)

My error (now - based on my latest attempt):

<ipython-input-77-dd29b60fadf7>:2: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(executable_path=r"C:\Users\AndreaPaviglianiti\Jupyter-2022\webdrivers\chromedriver.exe")

---------------------------------------------------------------------------
NoSuchElementException                    Traceback (most recent call last)
<ipython-input-77-dd29b60fadf7> in <module>
     25 cityFrom.click()
     26 select_cityFrom = driver.find_element(By.CLASS_NAME, 'select2-search__field').send_keys('Partinico')
---> 27 confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div').click()
     28 #confirm_cityFrom = driver.find_element(By.XPATH, '//*[@id="select2-loc_cap_mittente-results"]/li/div/text()').click()
     29 #confirm_cityFrom = driver.find_element(By.XPATH, '/html/body/span/span/span[2]').click()

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in find_element(self, by, value)
   1242             value = '[name="%s"]' % value
   1243
-> 1244         return self.execute(Command.FIND_ELEMENT, {
   1245             'using': by,
   1246             'value': value})['value']

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py in execute(self, driver_command, params)
    422         response = self.command_executor.execute(driver_command, params)
    423         if response:
--> 424             self.error_handler.check_response(response)
    425             response['value'] = self._unwrap_value(
    426                 response.get('value', None))

~\Miniconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py in check_response(self, response)
    245                 alert_text = value['alert'].get('text')
    246             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 247         raise exception_class(message, screen, stacktrace)
    248
    249     def _value_or_default(self, obj: Mapping[_KT, _VT], key: _KT, default: _VT) -> _VT:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="select2-loc_cap_mittente-results"]/li/div"}
  (Session info: chrome=98.0.4758.81)
Stacktrace:
Backtrace:
    Ordinal0 [0x007F7AC3+2587331]
    Ordinal0 [0x0078ADD1+2141649]
    Ordinal0 [0x00683BB8+1063864]
    Ordinal0 [0x006B01CE+1245646]
    Ordinal0 [0x006B03CB+1246155]
    Ordinal0 [0x006DA612+1418770]
    Ordinal0 [0x006C86D4+1345236]
    Ordinal0 [0x006D8A0A+1411594]
    Ordinal0 [0x006C84A6+1344678]
    Ordinal0 [0x006A53F6+1201142]
    Ordinal0 [0x006A62E6+1204966]
    GetHandleVerifier [0x0099DF22+1680738]
    GetHandleVerifier [0x00A50DBC+2413564]
    GetHandleVerifier [0x0088D151+563089]
    GetHandleVerifier [0x0088BF13+558419]
    Ordinal0 [0x0079081E+2164766]
    Ordinal0 [0x00795508+2184456]
    Ordinal0 [0x00795650+2184784]
    Ordinal0 [0x0079F5BC+2225596]
    BaseThreadInitThunk [0x77CDFA29+25]
    RtlGetAppContainerNamedObjectPath [0x77E27A9E+286]
    RtlGetAppContainerNamedObjectPath [0x77E27A6E+238]

EDIT
To clarify the matter I am now adding two printscreens that focus on the elements I cannot manage - the Sender's Locality.

It is more advanced to what I am used to (and I am fairly new with Selenium).

Body:
#select2-nazione_mittente-container

Simply click the above element

.select2-search__field

Send keys to the above element

//li[@class='select2-results__option' and contains(@id,'Italia')]

Then proceed to click on the li tag with that value.

It's how to deal with any non Select dropdown element.


问:
How can I make commands in Discord.py not allow any extra characters after the actual command?
```<code>@bot.command()
async def ping(ctx):
    await ctx.send("Pong! {0}ms".format(round(bot.latency * 1000)))
</code>```

This is my ping command for my bot I made, however the issue is when I use this command
-ping, it works just fine but if I do, -ping whateverhere

Then the command still runs! I'm not quite sure why this happens but it accepts the other arguments for some reason. The same happens with my other commands.

答:
It might not be the best solution, but what you can actually try is adding an additional argument arg (or whatever you'd like to call it) to your function, and set its default value to None. Then, in the function's body, you'll want to check if any extra arguments were provided - if not, then the function should just run, if yes - it could throw an exception for you, or send a message to the text channel, where the command was used. See the modified code below:

```<code>@bot.command()
async def ping(ctx, arg=None):
    if arg:
        await ctx.send('This command takes no arguments.')
    else:
        await ctx.send("Pong! {0}ms".format(round(bot.latency * 1000)))
</code>```

Body:
@bot.command()
async def ping(ctx):
    await ctx.send("Pong! {0}ms".format(round(bot.latency * 1000)))

This is my ping command for my bot I made, however the issue is when I use this command
-ping, it works just fine but if I do, -ping whateverhere

Then the command still runs! I'm not quite sure why this happens but it accepts the other arguments for some reason. The same happens with my other commands.

Body:
It might not be the best solution, but what you can actually try is adding an additional argument arg (or whatever you'd like to call it) to your function, and set its default value to None. Then, in the function's body, you'll want to check if any extra arguments were provided - if not, then the function should just run, if yes - it could throw an exception for you, or send a message to the text channel, where the command was used. See the modified code below:

@bot.command()
async def ping(ctx, arg=None):
    if arg:
        await ctx.send('This command takes no arguments.')
    else:
        await ctx.send("Pong! {0}ms".format(round(bot.latency * 1000)))


问:
What does export const { x: y} = z; do?
I'm really confused by the following statement in an index.ts:

```<code>import z from 'path/to/z';
export const { x: y } = z;
</code>```

What does the second line actually export and how does the value of z correlate with it? Also, what purpose does this kind of export serve?

答:
This is an export declaration with a const destructuring pattern. y is the variable being declared, which is initialised with the x property of z.

It could (and perhaps should) be written as the equivalent

```<code>export const y = z.x;
</code>```

Title: What does export const { x: y} = z; do?

Body:
I'm really confused by the following statement in an index.ts:

import z from 'path/to/z';
export const { x: y } = z;

What does the second line actually export and how does the value of z correlate with it? Also, what purpose does this kind of export serve?

Body:
This is an export declaration with a const destructuring pattern. y is the variable being declared, which is initialised with the x property of z.

It could (and perhaps should) be written as the equivalent

export const y = z.x;


问:
.NET 6 Custom model binding - fall back to default binding?
I am trying to change the way one specific property of my Specification models are bound in .NET 6. I have a bunch of Specification classes that inherit from SpecificationBase<>. There is an int[]? Ids { get; set; } property that is part of the base class. I created a custom binder to take a CSV string of numbers and convert them to an int[]? array. (Note: I am aware the arrays can be passed to controller actions in the form ?Ids=1&Ids3=&Ids=5 which will bind correctly to arrays).

In older examples I've seen on the web, custom model binders inherited from DefaultModelBinder. We could then use base.BindModel or base.BindProperty. I cannot find anything similar for .Net 6. There is a ComplexObjectModelBinder but it is sealed.

Everything below works okay as long as the Specification properties are simple types. The TypeDescriptor conversion seems to work well for those. I'm worried about when there are complex types. Is there a way to fall back to default binding for everything other than my Ids property?

```<code>public class SpecificationModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        ArgumentNullException.ThrowIfNull(bindingContext);

        // If not a specification, skip
        if (bindingContext.ModelType.BaseType?.GetGenericTypeDefinition() != typeof(SpecificationBase<>))
            return Task.CompletedTask;

        // Type of specification
        var type = bindingContext.ModelType;

        // Create default instance of the specification
        var model = Activator.CreateInstance(type);

        // We are passing the specification parameters via the querystring, so loop over the querystring keys to set specification properties
        foreach (var name in bindingContext.HttpContext.Request.Query.Keys)
        {
            // Check to make sure there is a matching property. If not continue.
            var property = type.GetProperty(name);
            if (property is null)
                continue;

            if (property.Name == "Ids")
            {
                // Custom binding to convert int csv string into int[] array
                string? idsString = bindingContext.ValueProvider.GetValue("Ids").FirstValue;
                int[]? ids = null;
                if (!string.IsNullOrEmpty(idsString))
                    ids = idsString.Split(',', StringSplitOptions.RemoveEmptyEntries).Where(x => int.TryParse(x, out _)).Select(x => int.Parse(x)).ToArray();
                property.SetValue(model, ids);
            }
            else
            {
                // Is there a standard way to bind all of the other properties? This will only handle simple types
                var value = bindingContext.ValueProvider.GetValue(property.Name).FirstValue;
                var converter = TypeDescriptor.GetConverter(property.PropertyType);
                var convertedValue = converter.ConvertFrom(value!);
                property.SetValue(model, convertedValue);
            }
        }

        // Set the result to our populated model
        bindingContext.Result = ModelBindingResult.Success(model);

        return Task.CompletedTask;
    }
}
</code>```

答:
If you are really just looking to have a custom model binder for just one property.

You can actually set the Binder on the property level specifically. https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#modelbinder-attribute

Going from what I can from your example:

```<code>class CountrySpecification : SpecificationBase<>
{
    //Country specific properties handled by the default Binders
}
</code>```
```<code>class SpecificationBase<>
{
    [ModelBinder(typeof(SpecificationModelBinder))]
    int[]? Ids { get; set; }
    //Extra properties handled by the default Binders
}
</code>```

Another added benefit is now your custom Binder handle your one property as well.

Body:
I am trying to change the way one specific property of my Specification models are bound in .NET 6. I have a bunch of Specification classes that inherit from SpecificationBase<>. There is an int[]? Ids { get; set; } property that is part of the base class. I created a custom binder to take a CSV string of numbers and convert them to an int[]? array. (Note: I am aware the arrays can be passed to controller actions in the form ?Ids=1&Ids3=&Ids=5 which will bind correctly to arrays).

In older examples I've seen on the web, custom model binders inherited from DefaultModelBinder. We could then use base.BindModel or base.BindProperty. I cannot find anything similar for .Net 6. There is a ComplexObjectModelBinder but it is sealed.

Everything below works okay as long as the Specification properties are simple types. The TypeDescriptor conversion seems to work well for those. I'm worried about when there are complex types. Is there a way to fall back to default binding for everything other than my Ids property?

public class SpecificationModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        ArgumentNullException.ThrowIfNull(bindingContext);

        // If not a specification, skip
        if (bindingContext.ModelType.BaseType?.GetGenericTypeDefinition() != typeof(SpecificationBase<>))
            return Task.CompletedTask;

        // Type of specification
        var type = bindingContext.ModelType;

        // Create default instance of the specification
        var model = Activator.CreateInstance(type);

        // We are passing the specification parameters via the querystring, so loop over the querystring keys to set specification properties
        foreach (var name in bindingContext.HttpContext.Request.Query.Keys)
        {
            // Check to make sure there is a matching property. If not continue.
            var property = type.GetProperty(name);
            if (property is null)
                continue;

            if (property.Name == "Ids")
            {
                // Custom binding to convert int csv string into int[] array
                string? idsString = bindingContext.ValueProvider.GetValue("Ids").FirstValue;
                int[]? ids = null;
                if (!string.IsNullOrEmpty(idsString))
                    ids = idsString.Split(',', StringSplitOptions.RemoveEmptyEntries).Where(x => int.TryParse(x, out _)).Select(x => int.Parse(x)).ToArray();
                property.SetValue(model, ids);
            }
            else
            {
                // Is there a standard way to bind all of the other properties? This will only handle simple types
                var value = bindingContext.ValueProvider.GetValue(property.Name).FirstValue;
                var converter = TypeDescriptor.GetConverter(property.PropertyType);
                var convertedValue = converter.ConvertFrom(value!);
                property.SetValue(model, convertedValue);
            }
        }

        // Set the result to our populated model
        bindingContext.Result = ModelBindingResult.Success(model);

        return Task.CompletedTask;
    }
}

Body:
If you are really just looking to have a custom model binder for just one property.

You can actually set the Binder on the property level specifically. https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#modelbinder-attribute

Going from what I can from your example:

class CountrySpecification : SpecificationBase<>
{
    //Country specific properties handled by the default Binders
}

class SpecificationBase<>
{
    [ModelBinder(typeof(SpecificationModelBinder))]
    int[]? Ids { get; set; }
    //Extra properties handled by the default Binders
}

Another added benefit is now your custom Binder handle your one property as well.


问:
Blazor pass context to RenderFragment
So, I have a page that contains a grid

SearchPage.razor

```<code><FiGrid @ref="Grid"
    <Columns>
        @Columns
    </Columns>
    <EditFormTemplate Context="contextEntity">
        @EditFormTemplate(contextEntity)
    </EditFormTemplate>
</FiGrid>

@code{
protected RenderFragment Columns { get; set; }

protected RenderFragment<object> EditFormTemplate { get; set; }
}
</code>```

this page has a RenderFragment to render the columns and one to render an editForm whenever is necessary

i inherit from this SearchPage to customize this 2 props:

CustomSearchPage.razor

```<code>@inherits SearchPage

@{
    base.BuildRenderTree(__builder);
}

@code {

    private static RenderFragment _customColumns = __builder =>
    {
        <CustomColumn FieldName="@nameof(Factory.Id)" Width="75px"/>
        <CustomColumn FieldName="@nameof(Factory.BusinessName)"/>
        <CustomColumn FieldName="@nameof(Factory.Address)"/>
    };

    private static RenderFragment<object> _customEditFormTemplate = editModel => __builder =>
    {
        <CustomEditForm Entity="editModel"/>;
    };

    protected override void OnInitialized()
    {
        Columns = _customColumns;
        EditFormTemplate = _customEditFormTemplate;
        base.OnInitialized();
    }

}
</code>```

but it gives me this error on the console:

Operation is not valid due to the current state of the object.

maybe I'm using the wrong approach, in that case, how should I accomplish the same thing?

I need to be able to inherit from a page and pass the page a custom edit form that takes the context of the template

basically I want to pass the context of the template down to a RenderFragment created via code

答:
You are getting the error because you can't build component inheritance in the way you envisage.  You can't call BuildRenderTree manually like this:

```<code>base.BuildRenderTree(__builder);
</code>```

because you don't have a reference to the Renderer's RenderTreeBuilder.

A RenderFragment is a delegate defined as:

```<code>public delegate void RenderFragment(RenderTreeBuilder builder);
</code>```

It's run by the Renderer which invokes it and passes in the Renderer's instance of RenderTreeBuilder.

All Razor pages are pre-compiled into C# classes.  So this simple component DisplayDiv.razor:

```<code><h3>@Header</h3>

@code {
    [Parameter] public string Header { get; set; } = "Hello Blazor";
}
</code>```

gets pre-compiled by the Razor processor to something like this:

```<code>public class DisplayDiv : ComponentBase
{
    [Parameter] public string Header { get; set; } = "Hello Blazor";

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "h3");
        builder.AddContent(1, this.Header);
        builder.CloseElement();
    }
}
</code>```

BuildRenderTree gets added to ComponentBase's base RenderFragment which StateHasChanged passes to the Renderer when it's called to render the component.

```<code>private readonly RenderFragment _renderFragment;

public ComponentBase()
{
    _renderFragment = builder =>
    {
        _hasPendingQueuedRender = false;
        _hasNeverRendered = false;
        BuildRenderTree(builder);
    };
}
</code>```

You are trying to define multiple copies of BuildRenderTree, which you can't do within the razor page setting.  The child BuildRenderTree method built by the Razor pre-compiler overrides that of the parent.

Your SearchPage is a component which you then use in a page

```<code><SearchPage>
    <Columns>
        <CustomColumn FieldName="@nameof(Factory.Id)" Width="75px"/>
        <CustomColumn FieldName="@nameof(Factory.BusinessName)"/>
        <CustomColumn FieldName="@nameof(Factory.Address)"/>
    </Columns>
    <EditFormTemplate>
        <CustomEditForm Entity="editModel"/>
    </EditFormTemplate>
</SearchPage>

</code>```

You can do inheritance in components, but your parent components need to be classes, not Razor components, and build out any markup directly in code.

Title: Blazor pass context to RenderFragment

Body:
So, I have a page that contains a grid

SearchPage.razor

<FiGrid @ref="Grid"
    <Columns>
        @Columns
    </Columns>
    <EditFormTemplate Context="contextEntity">
        @EditFormTemplate(contextEntity)
    </EditFormTemplate>
</FiGrid>

@code{
protected RenderFragment Columns { get; set; }

protected RenderFragment<object> EditFormTemplate { get; set; }
}

this page has a RenderFragment to render the columns and one to render an editForm whenever is necessary

i inherit from this SearchPage to customize this 2 props:

CustomSearchPage.razor

@inherits SearchPage

@{
    base.BuildRenderTree(__builder);
}

@code {

    private static RenderFragment _customColumns = __builder =>
    {
        <CustomColumn FieldName="@nameof(Factory.Id)" Width="75px"/>
        <CustomColumn FieldName="@nameof(Factory.BusinessName)"/>
        <CustomColumn FieldName="@nameof(Factory.Address)"/>
    };

    private static RenderFragment<object> _customEditFormTemplate = editModel => __builder =>
    {
        <CustomEditForm Entity="editModel"/>;
    };

    protected override void OnInitialized()
    {
        Columns = _customColumns;
        EditFormTemplate = _customEditFormTemplate;
        base.OnInitialized();
    }

}

but it gives me this error on the console:

Operation is not valid due to the current state of the object.

maybe I'm using the wrong approach, in that case, how should I accomplish the same thing?

I need to be able to inherit from a page and pass the page a custom edit form that takes the context of the template

basically I want to pass the context of the template down to a RenderFragment created via code

Body:
You are getting the error because you can't build component inheritance in the way you envisage.  You can't call BuildRenderTree manually like this:

base.BuildRenderTree(__builder);

because you don't have a reference to the Renderer's RenderTreeBuilder.

A RenderFragment is a delegate defined as:

public delegate void RenderFragment(RenderTreeBuilder builder);

It's run by the Renderer which invokes it and passes in the Renderer's instance of RenderTreeBuilder.

All Razor pages are pre-compiled into C# classes.  So this simple component DisplayDiv.razor:

<h3>@Header</h3>

@code {
    [Parameter] public string Header { get; set; } = "Hello Blazor";
}

gets pre-compiled by the Razor processor to something like this:

public class DisplayDiv : ComponentBase
{
    [Parameter] public string Header { get; set; } = "Hello Blazor";

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "h3");
        builder.AddContent(1, this.Header);
        builder.CloseElement();
    }
}

BuildRenderTree gets added to ComponentBase's base RenderFragment which StateHasChanged passes to the Renderer when it's called to render the component.

private readonly RenderFragment _renderFragment;

public ComponentBase()
{
    _renderFragment = builder =>
    {
        _hasPendingQueuedRender = false;
        _hasNeverRendered = false;
        BuildRenderTree(builder);
    };
}

You are trying to define multiple copies of BuildRenderTree, which you can't do within the razor page setting.  The child BuildRenderTree method built by the Razor pre-compiler overrides that of the parent.

Your SearchPage is a component which you then use in a page

<SearchPage>
    <Columns>
        <CustomColumn FieldName="@nameof(Factory.Id)" Width="75px"/>
        <CustomColumn FieldName="@nameof(Factory.BusinessName)"/>
        <CustomColumn FieldName="@nameof(Factory.Address)"/>
    </Columns>
    <EditFormTemplate>
        <CustomEditForm Entity="editModel"/>
    </EditFormTemplate>
</SearchPage>

You can do inheritance in components, but your parent components need to be classes, not Razor components, and build out any markup directly in code.