问:
AttributeError at /Test/ 'tuple' object has no attribute 'get'
I am currently seeing the following error when I try to open a django crispy-reports form.
All the info Í can find online about this is, that i persumably added a comma where ther shouldn't be one. But I really can't find any.

My PlaylistForm class

```<code>from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class PlaylistForm(forms.Form):
    name = forms.CharField(
        label='Name',
        max_length= 64,
        required = True)

    comment = forms.CharField(
        label='Kommentar',
        max_length= 256,
        required = False)

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id_playlist_form'
        self.helper.form_class = 'forms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'test'

        self.helper.add_input(Submit('submit', 'Absenden'))
</code>```

the edit.html template

```<code>{% load crispy_forms_tags %}
{% crispy playlist_form playlist_form.helper %}
</code>```

the urlpatterns entry

```<code>path('Test/', views.test, name='test')
</code>```

excerpt from the views.py

```<code>from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from trackmanager.Forms.PlaylistForm import PlaylistForm

def test(request: HttpRequest)->HttpResponse:
    context = {'playlist_form': PlaylistForm()}
    return render(request, 'trackmanager/edit.html', context)
</code>```

The stacktrace

```<code>AttributeError at /Test/
'tuple' object has no attribute 'get'
Request Method: GET
Request URL:
Django Version: 4.0.2
Exception Type: AttributeError
Exception Value:
'tuple' object has no attribute 'get'
Exception Location: /usr/local/lib/python3.8/dist-packages/django/forms/widgets.py, line 263, in value_from_datadict
Python Executable:  /usr/bin/python3
Python Version: 3.8.10
Python Path:
['/var/trackmania',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Sun, 13 Feb 2022 23:26:03 +0000

[...]

25          {% if not field|is_checkbox %}
26              **{% crispy_field field %}**
27          {% endif %}

[...]

def value_from_datadict(self, data, files, name):
    """
    Given a dictionary of data and this widget's name, return the value
    of this widget or None if it's not provided.
    """
    **return data.get(name)**
</code>```

答:
I found the solution.
In my case it was a faulty super call

How not to do it

```<code>    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
</code>```

How to do it

```<code>    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
</code>```

Body:
I am currently seeing the following error when I try to open a django crispy-reports form.
All the info Í can find online about this is, that i persumably added a comma where ther shouldn't be one. But I really can't find any.

My PlaylistForm class

from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class PlaylistForm(forms.Form):
    name = forms.CharField(
        label='Name',
        max_length= 64,
        required = True)

    comment = forms.CharField(
        label='Kommentar',
        max_length= 256,
        required = False)

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id_playlist_form'
        self.helper.form_class = 'forms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'test'

        self.helper.add_input(Submit('submit', 'Absenden'))

the edit.html template

{% load crispy_forms_tags %}
{% crispy playlist_form playlist_form.helper %}

the urlpatterns entry

path('Test/', views.test, name='test')

excerpt from the views.py

from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from trackmanager.Forms.PlaylistForm import PlaylistForm

def test(request: HttpRequest)->HttpResponse:
    context = {'playlist_form': PlaylistForm()}
    return render(request, 'trackmanager/edit.html', context)

The stacktrace

AttributeError at /Test/
'tuple' object has no attribute 'get'
Request Method: GET
Request URL:
Django Version: 4.0.2
Exception Type: AttributeError
Exception Value:
'tuple' object has no attribute 'get'
Exception Location: /usr/local/lib/python3.8/dist-packages/django/forms/widgets.py, line 263, in value_from_datadict
Python Executable:  /usr/bin/python3
Python Version: 3.8.10
Python Path:
['/var/trackmania',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Sun, 13 Feb 2022 23:26:03 +0000

[...]

25          {% if not field|is_checkbox %}
26              **{% crispy_field field %}**
27          {% endif %}

[...]

def value_from_datadict(self, data, files, name):
    """
    Given a dictionary of data and this widget's name, return the value
    of this widget or None if it's not provided.
    """
    **return data.get(name)**

Body:
I found the solution.
In my case it was a faulty super call

How not to do it

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)

How to do it

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


来源: stackexchange

问:
Are there good reasons to wrap a single property in a #region in c#?
I recently inherited some C# code where nearly every item in a file was wrapped in an individual #region/#endregion block -- every class, every function, every property, every enum, but not the fields.  Each of these was in turn wrapped in a "grouping" #region (e.g. "Properties", "Constructor", "Methods", etc.).  There are multiple overloads of a single function with different argument lists, but they're each wrapped in individual regions with the same name, rather than a single region for all three overloads.  The person who wrote this code is no longer with the company, and from the history in source control, it appears that these were present in the initial submission, and the practice continues through successive versions of the code as new properties and methods are added.

Any idea why this might be done?  Some thoughts:

An overzealous VS feature (or code-cleanup tool) automatically inserted the #region/#endregion blocks, and the author didn't remove them.

There's an IDE that folds regions but not functions, so this was necessary to get syntax folding.

This is a method of stubbing out the structure of your code prior to implementing it.

EDIT: I chose Jonathan's answer because it contributed a new reason why someone might have chosen to do this.  Thanks for the discussion!

答: I would say that is over-zealous and fails to take account of the concept of regions.  </p>

ContentLicense: CC BY-SA 3.0


问:
Where is the position of the child element? - jquery
how can i get child element position in JQuery?
I want to get the number 2 in the alert, because it is the second child!

function where_am_i(element) {
  alert("your position is:" + $(element).position_element());
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>one</li>
  <li onclick="where_am_i(this)">two</li>
  <li>three</li>
</ul></code>```

答:
Use jQuery's .index() method. Note that it returns a zero-based index so you'll need to add one to get the value you want.

$("ul li").on("click", function() {
  alert(`your position is: ${$(this).index() + 1}`)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }</code>```

one

two

three

```
</div>
</div>
</p>
<hr />
<p>As always, you might not need jQuery</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector("ul").addEventListener("click", e => {
  const target = e.target.closest("li")
  if (target) { // clicked on an <li>
    const siblings = Array.from(target.parentElement.children)
    const position = siblings.indexOf(target) + 1
    alert(`your position is: ${position}`)
  }
})</code>```

li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
how can i get child element position in JQuery?
I want to get the number 2 in the alert, because it is the second child!

function where_am_i(element) {
  alert("your position is:" + $(element).position_element());
}

one

two

three

Body:
Use jQuery's .index() method. Note that it returns a zero-based index so you'll need to add one to get the value you want.

$("ul li").on("click", function() {
  alert(`your position is: ${$(this).index() + 1}`)
})

li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

As always, you might not need jQuery

document.querySelector("ul").addEventListener("click", e => {
  const target = e.target.closest("li")
  if (target) { // clicked on an <li>
    const siblings = Array.from(target.parentElement.children)
    const position = siblings.indexOf(target) + 1
    alert(`your position is: ${position}`)
  }
})

li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>


问:
React/Jest Select element onChange values not updating
I have the following code to test the value of the Select element after changing:

```<code>it("changes value after selecting another field", () => {
  doSetupWork();
  let field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("");

  fireEvent.change(field, { target: { value: "1" } });

  // Insert one of two options from below
});
</code>```

However, when I insert the following at the bottom, it does not work:

```<code>field = screen.getByLabelText("MySelectField");
expect(field).toHaveValue("1");
</code>```

and gives the following error message:

```<code>Expected the element to have value: 1
Received:
</code>```

But, when I wrap it in a setTimeout with just 1ms delay, it does work:

```<code>setTimeout(() => {
  field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("1");
}, 1);
</code>```

It feels like there should be a more elegant way of writing this without setTimeout. Any advice?

答:
When I am using react-testing-library I tend to use render when I have events to interact with.
For instance:

In my App.js I have this code on the return method

```<code>  const handleChoice = () => {};

  const attributes = [
    { label: "One", value: "1" },
    { label: "Two", value: "2" },
    { label: "Three", value: "3" }
  ];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      <select onChange={handleChoice} data-testid="MySelectField">
        <option value="0">Zero</option>
        {attributes.map((item) => {
          return (
            <option key={item.value} value={item.value}>
              {item.label}
            </option>
          );
        })}
      </select>
    </div>
  );
</code>```

then my test would be something like this:

```<code>import { fireEvent, render } from "@testing-library/react";
import "@testing-library/jest-dom";

import App from "./App";

it("changes value after selecting another field", () => {
  const { getByTestId } = render(<App />);
  let field = getByTestId("MySelectField");
  expect(field).toHaveValue("0");

  fireEvent.change(field, { target: { value: "1" } });
  expect(field.value).toBe("1");

  fireEvent.change(field, { target: { value: "3" } });
  expect(field.value).toBe("3");
  // Insert one of two options from below
});
</code>```

Take a look in this sandbox to see it working.
https://codesandbox.io/s/ecstatic-https-hzi5n?file=/src/App.spec.js

Body:
I have the following code to test the value of the Select element after changing:

it("changes value after selecting another field", () => {
  doSetupWork();
  let field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("");

  fireEvent.change(field, { target: { value: "1" } });

  // Insert one of two options from below
});

However, when I insert the following at the bottom, it does not work:

field = screen.getByLabelText("MySelectField");
expect(field).toHaveValue("1");

and gives the following error message:

Expected the element to have value: 1
Received:

But, when I wrap it in a setTimeout with just 1ms delay, it does work:

setTimeout(() => {
  field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("1");
}, 1);

It feels like there should be a more elegant way of writing this without setTimeout. Any advice?

Body:
When I am using react-testing-library I tend to use render when I have events to interact with.
For instance:

In my App.js I have this code on the return method

  const handleChoice = () => {};

  const attributes = [
    { label: "One", value: "1" },
    { label: "Two", value: "2" },
    { label: "Three", value: "3" }
  ];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      <select onChange={handleChoice} data-testid="MySelectField">
        <option value="0">Zero</option>
        {attributes.map((item) => {
          return (
            <option key={item.value} value={item.value}>
              {item.label}
            </option>
          );
        })}
      </select>
    </div>
  );

then my test would be something like this:

import { fireEvent, render } from "@testing-library/react";
import "@testing-library/jest-dom";

import App from "./App";

it("changes value after selecting another field", () => {
  const { getByTestId } = render(<App />);
  let field = getByTestId("MySelectField");
  expect(field).toHaveValue("0");

  fireEvent.change(field, { target: { value: "1" } });
  expect(field.value).toBe("1");

  fireEvent.change(field, { target: { value: "3" } });
  expect(field.value).toBe("3");
  // Insert one of two options from below
});

Take a look in this sandbox to see it working.
https://codesandbox.io/s/ecstatic-https-hzi5n?file=/src/App.spec.js


问:
Activerecord has_many :through through multiple models
I'm trying to access all comments from a given user with user.comments. The query is to go through two different models, which likely both return results. My relations are set up as follow:

```<code>class User < ActiveRecord::Base
  has_many :organisers
  has_many :participants
  has_many :comments, through: :participants / :organisers (see explenation below)
end

class Organiser < ActiveRecord::Base
  belongs_to :user
end

class Participant  < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :organiser
  belongs_to :participant
end
</code>```

A comment is validated to belong to either a participant, or an organiser.

I'm not sure how to go about this. I've tried

```<code>has_many :comments, through: :participants
has_many :comments, through: :organisers
</code>```

and

```<code>has_many :comments, through: [:organisers, :participants]
</code>```

But that last one isn't rails. Is there a proper way to do this? Thanks!

答:
For anyone coming across this using polymorphic associations, the following worked for me inspired by magni- and Carlos Jimenez' answers:

```<code>has_many :comments, -> (user) {
  unscope(where: :user_id).
  where(commentable: [user.organizers, user.participants])
}
</code>```

Body:
I'm trying to access all comments from a given user with user.comments. The query is to go through two different models, which likely both return results. My relations are set up as follow:

class User < ActiveRecord::Base
  has_many :organisers
  has_many :participants
  has_many :comments, through: :participants / :organisers (see explenation below)
end

class Organiser < ActiveRecord::Base
  belongs_to :user
end

class Participant  < ActiveRecord::Base
  belongs_to :user
end

class Comment < ActiveRecord::Base
  belongs_to :organiser
  belongs_to :participant
end

A comment is validated to belong to either a participant, or an organiser.

I'm not sure how to go about this. I've tried

has_many :comments, through: :participants
has_many :comments, through: :organisers

and

has_many :comments, through: [:organisers, :participants]

But that last one isn't rails. Is there a proper way to do this? Thanks!

Body:
For anyone coming across this using polymorphic associations, the following worked for me inspired by magni- and Carlos Jimenez' answers:

has_many :comments, -> (user) {
  unscope(where: :user_id).
  where(commentable: [user.organizers, user.participants])
}


问:
Why is jQuery animation getting messed up when it is not the active tab?
You can see whats happening here..
http://jsfiddle.net/gregguida/36SEZ/4/

Switch tabs for about 30 seconds and then come back, the animation gets totally out of hand.

I think this has something to do with the way the browser treats setInteval() when the window doesn't have focus but I'm not sure if that's the case. I also don't know what to do about it. Any insight is appreciated.

Update: also tried using setTimeout instead of setInterval but I'm experiancing similar results

Thanks!

答:
I ran into the same when creating an animation for my site. The way I got around it was by removing the call to setInterval and setting a new timeout each time the animation is completed.

Here is your code updated to use that approach: http://jsfiddle.net/36SEZ/5/

Note that the call to setTimeout should be called only once after all of the animation is finished. In order to make sure that happens I've put it in the complete function of the last animation on the last div.


问:
CRM Online RetrieveMultiple with OptionSetValueCollection condition
I'm trying to retrieve records that contain some optionsetvalue from multi option set pick list.

This line make my code fail:

```<code>int[] values = GetValues();
query.Criteria.AddCondition(new ConditionExpression(fieldName,
ConditionOperator.ContainValues, values);
</code>```

When I put the values with a comma separator the code works:

```<code>query.Criteria.AddCondition(new ConditionExpression(fieldName,
ConditionOperator.ContainValues, 1,2,3);
</code>```

Only problem is that the values are dyanamic so I can't do that.
The only way I found so far to overcome it was this:

```<code>FilterExpression filter = new FilterExpression(LogicalOperator.Or);
foreach (int value in values)
{
    filter.AddCondition(new ConditionExpression(fieldName,
        ConditionOperator.ContainValues, value));
}
query.Criteria.AddFilter(filter);
</code>```

Just wondering if there is a better solution than this one?

答:
The documentation obviously needs to be updated. The method definition takes an object array:

```<code>public void AddCondition(string attributeName, ConditionOperator conditionOperator, params object[] values)
</code>```

so it should work if you change your values array to:

```<code>object[] values = GetValues();
</code>```

This works in my code:

```<code>object[] roleValues = new object[] { (int)optionset_value };
</code>```

Body:
I'm trying to retrieve records that contain some optionsetvalue from multi option set pick list.

This line make my code fail:

int[] values = GetValues();
query.Criteria.AddCondition(new ConditionExpression(fieldName,
ConditionOperator.ContainValues, values);

When I put the values with a comma separator the code works:

query.Criteria.AddCondition(new ConditionExpression(fieldName,
ConditionOperator.ContainValues, 1,2,3);

Only problem is that the values are dyanamic so I can't do that.
The only way I found so far to overcome it was this:

FilterExpression filter = new FilterExpression(LogicalOperator.Or);
foreach (int value in values)
{
    filter.AddCondition(new ConditionExpression(fieldName,
        ConditionOperator.ContainValues, value));
}
query.Criteria.AddFilter(filter);

Just wondering if there is a better solution than this one?

Body:
The documentation obviously needs to be updated. The method definition takes an object array:

public void AddCondition(string attributeName, ConditionOperator conditionOperator, params object[] values)

so it should work if you change your values array to:

object[] values = GetValues();

This works in my code:

object[] roleValues = new object[] { (int)optionset_value };


问:
How to load images from data array using Vue js?
I'm using Quasar and Vue js to practice building Web and Mobile Apps using a single codebase.
I'm having a strange issue. I created a meals array in the data property and I'm trying to display the data and an image inside a List component. I'm able to see the data, except I only see the apple.png image and not the two others. I have no idea why this would be. I put the images directly in the public directory and the filenames of the images are correct. And when I inspect the two images that aren't displaying, it is showing the name of the photo from the photo property correctly just like apple.png.

PageMeals.vue:

```<code><template>
  <q-page>
    <q-list bordered padding>
      <q-item
      v-for="meal in meals"
      :key="meal.id"
      >
        <q-item-section top avatar>
          <q-avatar rounded>
            <img :src="`img/${meal.photo}`" alt="">
          </q-avatar>
        </q-item-section>

        <q-item-section>
          <q-item-label>{{meal.name}}</q-item-label>
          <q-item-label caption>{{meal.description}}</q-item-label>
        </q-item-section>
      </q-item>
    </q-list>
  </q-page>
</template>

<script>
export default {
  name: 'PageMeals',
  data () {
    return {
      meals: [
        {
          id: '1',
          name: 'Apple',
          description: 'Juicy red Granny Smith apples.',
          photo: 'apple.png',
          grams: '25',
          calories: '120',
          added: false
        },
        {
          id: '2',
          name: 'Sandwich',
          description: 'Fresh white Tuna sandwich with tomatoes, lettuce, swiss cheese and apple wood smoked bacon.',
          photo: 'sandwich.png',
          grams: '45',
          calories: '240',
          added: false
        },
        {
          id: '3',
          name: 'Salad with chicken',
          description: 'Caesar salad, with parmesan cheese, croutons and tender juicy grilled chicken strips.',
          photo: 'salad-with-chicken.png',
          grams: '35',
          calories: '190',
          added: false
        }
      ]
    }
  }
}
</script>
</code>```

What am I doing wrong?

Is it better to store images in the public folder or assets folder?

答:
A little late, but in case somebody need it, when you need to load some dynamics media, the best way inside a v-for loop is with require:</p>
```<code><img :src="require(`../assets/display/${your_image_name}.svg`)"/>
</code>```

Body:
I'm using Quasar and Vue js to practice building Web and Mobile Apps using a single codebase.
I'm having a strange issue. I created a meals array in the data property and I'm trying to display the data and an image inside a List component. I'm able to see the data, except I only see the apple.png image and not the two others. I have no idea why this would be. I put the images directly in the public directory and the filenames of the images are correct. And when I inspect the two images that aren't displaying, it is showing the name of the photo from the photo property correctly just like apple.png.

PageMeals.vue:

<template>
  <q-page>
    <q-list bordered padding>
      <q-item
      v-for="meal in meals"
      :key="meal.id"
      >
        <q-item-section top avatar>
          <q-avatar rounded>
            <img :src="`img/${meal.photo}`" alt="">
          </q-avatar>
        </q-item-section>

        <q-item-section>
          <q-item-label>{{meal.name}}</q-item-label>
          <q-item-label caption>{{meal.description}}</q-item-label>
        </q-item-section>
      </q-item>
    </q-list>
  </q-page>
</template>

What am I doing wrong?

Is it better to store images in the public folder or assets folder?

Body:
A little late, but in case somebody need it, when you need to load some dynamics media, the best way inside a v-for loop is with require:

<img :src="require(`../assets/display/${your_image_name}.svg`)"/>


问:
Configure reducers of connected-react-router and Redux Toolkit Query properly
I am trying to setup reducers of both connected-react-router and RTK Query.

(The old code base has connected-react-router already)

Then I received this error.

fail to setup connectRouter

```<code>Type 'Reducer<RouterState<unknown>, AnyAction>' is not assignable to type 'Reducer<unknown, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'unknown' is not assignable to type 'RouterState<unknown>'.
</code>```

My "mockApi" is quite simple. "orderApi" is somewhat the same.

```<code>export const mockApi = createApi({
  reducerPath: "mockupPath",
  baseQuery: fetchBaseQuery({ baseUrl: "http://jsonplaceholder.typicode.com" }),
  endpoints: (builder) => ({
    getPost: builder.query<MockResonse, number>({
      query: (id) => `/posts/${id}`,
    }),
  }),
})
interface MockResonse { userId: number, id: number, title: string, body: string, }
</code>```

While using combineReducers produces no type error,

```<code>reducer: combineReducers({
  router: connectRouter(history),
  [mockApi.reducerPath]: mockApi.reducer,
}),
</code>```

but I lose the type of the store.

Knowing the type of the store is a huge advantage in development, so I'm trying to figure out how to solve the error.

May I know if I'm wrong somewhere?

答:
This TypeScript error occurs when using connected-react-router with newer versions of history and react-router.

The type for the connectRouter function looks like this:

```<code>export function connectRouter<S = LocationState>(history: History<S>)
    : Reducer<RouterState<S>>
</code>```

(source)

You can see that it is a generic function where the generic type parameter S refers to the type of the state that is stored in your history.

If you have a new version of history (5.2+), then History<S> is now a TypeScript error because the History interface is no longer generic.  This is a recent change which was released in history version 5.2.0.

You can fix the error by explicitly setting the generic type parameter for the connectRouter function call to unknown:

```<code>router: connectRouter<unknown>(history)
</code>```
```<code>const store = configureStore({
  reducer: {
    [mockApi.reducerPath]: mockApi.reducer,
    router: connectRouter<unknown>(history)
  }
})
</code>```

The inferred type of the router reducer is now Reducer<RouterState<unknown>, AnyAction>.

Body:
I am trying to setup reducers of both connected-react-router and RTK Query.

(The old code base has connected-react-router already)

Then I received this error.

fail to setup connectRouter

Type 'Reducer<RouterState<unknown>, AnyAction>' is not assignable to type 'Reducer<unknown, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'unknown' is not assignable to type 'RouterState<unknown>'.

My "mockApi" is quite simple. "orderApi" is somewhat the same.

export const mockApi = createApi({
  reducerPath: "mockupPath",
  baseQuery: fetchBaseQuery({ baseUrl: "http://jsonplaceholder.typicode.com" }),
  endpoints: (builder) => ({
    getPost: builder.query<MockResonse, number>({
      query: (id) => `/posts/${id}`,
    }),
  }),
})
interface MockResonse { userId: number, id: number, title: string, body: string, }

While using combineReducers produces no type error,

reducer: combineReducers({
  router: connectRouter(history),
  [mockApi.reducerPath]: mockApi.reducer,
}),

but I lose the type of the store.

Knowing the type of the store is a huge advantage in development, so I'm trying to figure out how to solve the error.

May I know if I'm wrong somewhere?

Body:
This TypeScript error occurs when using connected-react-router with newer versions of history and react-router.

The type for the connectRouter function looks like this:

export function connectRouter<S = LocationState>(history: History<S>)
    : Reducer<RouterState<S>>

(source)

You can see that it is a generic function where the generic type parameter S refers to the type of the state that is stored in your history.

If you have a new version of history (5.2+), then History<S> is now a TypeScript error because the History interface is no longer generic.  This is a recent change which was released in history version 5.2.0.

You can fix the error by explicitly setting the generic type parameter for the connectRouter function call to unknown:

router: connectRouter<unknown>(history)

const store = configureStore({
  reducer: {
    [mockApi.reducerPath]: mockApi.reducer,
    router: connectRouter<unknown>(history)
  }
})

The inferred type of the router reducer is now Reducer<RouterState<unknown>, AnyAction>.


问:
How to approximate the size of a text file containing a matrix, written by Fortran?
I have written an N*N matrix to a formatted text file using Fortran. The Fortran output format was N(3X,E17.8), where N is the matrix size.

Example of one matrix element:    0.19860753E-08 i.e. "(three spaces)0.19860753E-08".

A 558x558 Matrix has a file size of 5.294.302 Bytes.

How could I approximate the file size for an N*N matrix for any value of N?

答:
I am not sure if you have the lines separate or just all numbers in sequence.

If I read your description correctly you have N(3X,E17.8) per line. In that case every character is one byte. 3 spaces + 17 characters = 20 bytes. One line is 20 * N + 1 (or + 2 on Windows).  The +1 or +2 is the line end marker (LF or CR + LF). (This distinction is what the unix2dos and dos2unix utilities convert.)

Then you have N lines, so it should be N*(20 * N + 1).

That does not correspond to the numbers you show.

But the example you show is not consistent with the format you show. The number    0.19860753E-08 is actually just 17 characters (3X,E14.8). In that case it is N*(17 * N +1 ) + 1 or eventually N*(17 * N + 2) with CR + LF. Which corresponds to the file size you quoted much better. 558 * (17 * 558 + 2) = 5 294 304.


问:
Menu bug with Jquery
I'm having a bug with the menu I'm developing, it all goes well until you mouse over a child of the menu fast.

The bug is also different on Firefox and Chrome, I think its because one render faster than the other, in Firefox it becomes an infinite bug, in Chrome it last for a few seconds, then it disappears.

Here's my html code:

```<code><div id="menu" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
            <label class="formatText" id="lblIndicators">Primer Menu</label>
            <span class="ui-icon ui-icon-triangle-1-e menuIcon" style="float:right"></span>
            <div id="subMenu" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
            <ul class="options">
                <li>
                    <label class="formatText">Sub Menu Uno</label>
                    <span class="ui-icon ui-icon-triangle-1-s" style="float:right"></span>
                    <div id="subMenuRight" class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all">
                        <ul class=options>
                            <li>Sub-Sub Menu Uno</li>
                            <li>Sub-Sub Menu Dos</li>
                        </ul>
                    </div>
                </li>
                <li>Sub Menu Dos</li>
            </ul>
        </div>
        </div>
</code>```

Here's my JQuery:

```<code>$(document).ready(initialize);

function initialize(){

    $("#menu").hover(mouseIn,mouseOut);
    $(".options li").hover(overOption,outOption);
    $("#subMenu").hover(openRightMenu,closeRightMenu);
}

function mouseIn(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-s');
    $("#subMenu").slideDown(100);
}

function mouseOut(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-e');
    $("#subMenu").fadeOut(100);
}

function overOption(){
    $(this).attr('class','ui-state-hover ui-corner-all');
}

function outOption(){
    $(this).attr('class','');
}

function openRightMenu(){
    $("#subMenuRight").slideDown(100);
}

function closeRightMenu(){
    $("#subMenuRight").slideUp(100);
}
</code>```

Here's a video of the bug

Here's a live demo on jsFiddle

Any help would be appreciated!

答:
You need to stop all animations before creating new ones so they don't go over each other. I added some .stop(true, true) methods for your to clear your queue. Have a look if that sorted your problem

```<code>    $(document).ready(initialize);

function initialize(){

    $("#menu").hover(mouseIn,mouseOut);
    $(".options li").hover(overOption,outOption);
    $("#subMenu").hover(openRightMenu,closeRightMenu);
}

function mouseIn(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-s');
    $("#subMenu").stop(true, true).slideDown(100);
}

function mouseOut(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-e');
    $("#subMenu").stop(true, true).fadeOut(100);
}

function overOption(){
    $(this).attr('class','ui-state-hover ui-corner-all');
}

function outOption(){
    $(this).attr('class','');
}

function openRightMenu(){
    $("#subMenuRight").stop(true, true).slideDown(100);
}

function closeRightMenu(){
    $("#subMenuRight").stop(true, true).slideUp(100);
}
</code>```

Title: Menu bug with Jquery

Body:
I'm having a bug with the menu I'm developing, it all goes well until you mouse over a child of the menu fast.

The bug is also different on Firefox and Chrome, I think its because one render faster than the other, in Firefox it becomes an infinite bug, in Chrome it last for a few seconds, then it disappears.

Here's my html code:

            Primer Menu

                    Sub Menu Uno

Sub-Sub Menu Uno

Sub-Sub Menu Dos

Sub Menu Dos

Here's my JQuery:

$(document).ready(initialize);

function initialize(){

    $("#menu").hover(mouseIn,mouseOut);
    $(".options li").hover(overOption,outOption);
    $("#subMenu").hover(openRightMenu,closeRightMenu);
}

function mouseIn(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-s');
    $("#subMenu").slideDown(100);
}

function mouseOut(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-e');
    $("#subMenu").fadeOut(100);
}

function overOption(){
    $(this).attr('class','ui-state-hover ui-corner-all');
}

function outOption(){
    $(this).attr('class','');
}

function openRightMenu(){
    $("#subMenuRight").slideDown(100);
}

function closeRightMenu(){
    $("#subMenuRight").slideUp(100);
}

Here's a video of the bug

Here's a live demo on jsFiddle

Any help would be appreciated!

Body:
You need to stop all animations before creating new ones so they don't go over each other. I added some .stop(true, true) methods for your to clear your queue. Have a look if that sorted your problem

    $(document).ready(initialize);

function initialize(){

    $("#menu").hover(mouseIn,mouseOut);
    $(".options li").hover(overOption,outOption);
    $("#subMenu").hover(openRightMenu,closeRightMenu);
}

function mouseIn(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-s');
    $("#subMenu").stop(true, true).slideDown(100);
}

function mouseOut(){
    $(this).find('span').attr('class','');
    $(this).find('span').attr('class','ui-icon ui-icon-triangle-1-e');
    $("#subMenu").stop(true, true).fadeOut(100);
}

function overOption(){
    $(this).attr('class','ui-state-hover ui-corner-all');
}

function outOption(){
    $(this).attr('class','');
}

function openRightMenu(){
    $("#subMenuRight").stop(true, true).slideDown(100);
}

function closeRightMenu(){
    $("#subMenuRight").stop(true, true).slideUp(100);
}


问:
Select shortest and longest string
Is it possible to select the shortest and longest strings by characters in a table?

I have a CITY column of type VARCHAR(20) and I want to select the shortest and longest city names in alphabetical order by length.

I did like this

SELECT CITY,LENGTH(CITY) FROM STATION WHERE LENGTH(CITY) IN ( SELECT MAX(LENGTH(CITY)) FROM STATION UNION SELECT MIN(LENGTH(CITY)) FROM STATION ) ORDER BY CITY ASC;

When ordered alphabetically, Let the CITY names be listed as ABC, DEF, PQRS, and WXY, with the respective lengths 3,3,4, and 3. The longest-named city is obviously PQRS, but there are options for the shortest-named city; I have to select ABC because it comes first alphabetically.

My query ended up with all three CITY having length 3.

ABC 3 DEF 3 PQRS 4 WXY 3

The result of SELECT must be

ABC 3 PQRS 4

答:
The following code works in Oracle SQL. All the above solutions did not work for Oracle SQL btw! You may add Union in between. But this runs fine as well!

SELECT * FROM
          (SELECT city,LENGTH(city)
          from station
          order by Length(city), city)
WHERE rownum <= 1;
SELECT * FROM
          (SELECT city,LENGTH(city)
          from station
          order by Length(city) desc)
WHERE rownum <= 1;```

Title: Select shortest and longest string


问:
How do I clone git.ignore?
If I make the git.ignore in my local file then the some of public file in gihub will disappear.

And if I do git clone (my url) then the file from git.ignore will not be cloned.

How can I clone it?
(I am starting git and aws. I am tring to clone git file to aws server)

答:
There are many ways to make git ignore certain files. See the git documentation. Out of the three ways described there only one puts the information about what files to ignore in the versioned content, so you get the information back out when cloning the repo. This is the usage of .gitignore-files.

So make sure you have file called .gitignore (preferably in the top level folder of your repo) and make sure it is checked in like a normal source file. That way when you clone the repo you also get the .gitignore file and git automagically knows what files to ignore even on the clone.

Title: How do I clone git.ignore?


答:
EDIT: Phil's solution is much better

Get the parent, get all the parent's children, then find the index of the inputted element within the array of child nodes.

one

two

three

```

Title: Where is the position of the child element? - jquery

Body:
EDIT: Phil's solution is much better

Get the parent, get all the parent's children, then find the index of the inputted element within the array of child nodes.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>one</li>
    <li onclick="findElem(this)">two</li>
    <li>three</li>
</ul>

<script>
    const findElem = (elem) => {
        // Grab the parent element
        const parent = $(elem).parent();

        // Get array of all its children
        const allChildren = $(parent).children();

        // Turn it into a regular array, find the index of our elem, add 1 to it
        const position = [...allChildren].indexOf(elem) + 1;

        console.log(`The clicked element's position is ${position}`);
    };
</script>


问:
How to load images from memory to numpy using file system
I want to store my image directory in memory, then load the images into a numpy array.

The normative way to load images that are not in memory is as follows:

```<code>import PIL.Image
import numpy as np

image = PIL.Image.open("./image_dir/my_image_1.jpg")
image = np.array(image)
</code>```

However, I am not sure how to do this when the images are in memory. So far, I have been able to setup the following starter code:

```<code>import fs
import fs.memoryfs
import fs.osfs

image_dir = "./image_dir"

mem_fs = fs.memoryfs.MemoryFS()
drv_fs = fs.osfs.OSFS(image_path)

fs.copy.copy_fs(drv_fs, mem_fs)

print(mem_fs.listdir('.'))
</code>```

Returns:

```<code>['my_image_1.jpg', 'my_image_2.jpg']
</code>```

How do I load images that are in memory into numpy?

I am also open to alternatives to the fs package.

答:
As per the documentation, Pillow's Image.open accepts a file object instead of a file name, so as long as your in-memory file package provides Python file objects (which it most likely does), you can just use them. If it doesn't, you could even just wrap them in a class that provides the required methods. Assuming you are using PyFilesystem, according to its documentation you should be fine.

So, you want something like:

```<code>import numpy as np
import PIL.Image
import fs.memoryfs
import fs.osfs
import fs.copy

mem_fs = fs.memoryfs.MemoryFS()
drv_fs = fs.osfs.OSFS("./image_dir")

fs.copy.copy_file(drv_fs, './my_image_1.jpg', mem_fs, 'test.jpg')

with mem_fs.openbin('test.jpg') as f:
    image = PIL.Image.open(f)
    image = np.array(image)
</code>```

(note I just used copy_file because I tested with a single file, you can use copy_fs if you need to copy the entire tree - it's the same principle)

Body:
I want to store my image directory in memory, then load the images into a numpy array.

The normative way to load images that are not in memory is as follows:

import PIL.Image
import numpy as np

image = PIL.Image.open("./image_dir/my_image_1.jpg")
image = np.array(image)

However, I am not sure how to do this when the images are in memory. So far, I have been able to setup the following starter code:

import fs
import fs.memoryfs
import fs.osfs

image_dir = "./image_dir"

mem_fs = fs.memoryfs.MemoryFS()
drv_fs = fs.osfs.OSFS(image_path)

fs.copy.copy_fs(drv_fs, mem_fs)

print(mem_fs.listdir('.'))

Returns:

['my_image_1.jpg', 'my_image_2.jpg']

How do I load images that are in memory into numpy?

I am also open to alternatives to the fs package.

Body:
As per the documentation, Pillow's Image.open accepts a file object instead of a file name, so as long as your in-memory file package provides Python file objects (which it most likely does), you can just use them. If it doesn't, you could even just wrap them in a class that provides the required methods. Assuming you are using PyFilesystem, according to its documentation you should be fine.

So, you want something like:

import numpy as np
import PIL.Image
import fs.memoryfs
import fs.osfs
import fs.copy

mem_fs = fs.memoryfs.MemoryFS()
drv_fs = fs.osfs.OSFS("./image_dir")

fs.copy.copy_file(drv_fs, './my_image_1.jpg', mem_fs, 'test.jpg')

with mem_fs.openbin('test.jpg') as f:
    image = PIL.Image.open(f)
    image = np.array(image)

(note I just used copy_file because I tested with a single file, you can use copy_fs if you need to copy the entire tree - it's the same principle)


问:
How to compare a remote host fingerprint to the fingerprint of a different host?
I have two ways of accessing my remote host ssh server:

using its local IP addres

using its public IP address

Yesterday, I reinstalled my SSH server on the remote host and I updated my known hosts file for the local IP address. I am now off of my local network and trying to connect to my server using its public IP address and I realized I forgot to update my known hosts file after reinstalling the SSH service. This is giving me the common error below.

```<code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
MD5:FINGERPRINT.
Please contact your system administrator.
Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /Users/user/.ssh/known_hosts:25
ECDSA host key for [PUBLIC IP]:PORT has changed and you have requested strict checking.
Host key verification failed.
</code>```

I'm 99% sure this is because I changed the SSH server, however, if I wanted to double check and verify, how would I do this?

My question is

How can I verify the new fingerprint of the remote host against the fingerprint saved for the local IP address of the server?

What I've Done

I ran the following command: ssh-keygen -lv -f ~/.ssh/known_hosts and found the SHA256 fingerprint saved for the local ip address of my server.

I compared this to the SHA256 fingerprint being sent to me from my remote host, and they appear to be identical.

How can I be 100% sure? Did I do this properly?

答:
When you say "updated" your known_hosts file, does that also mean you removed the old entry?

You can run this quick oneliner to quickly get the current fingerprint via local ip and public ip.

ssh-keyscan -t rsa <Local IP of host> <Remote IP of host> | ssh-keygen -l -f -

Here is a usage example scanning one of my Linux systems using the loopback interface as the second scan address.

```<code>$ ssh-keyscan -t rsa 127.0.0.1 10.10.40.20  | ssh-keygen -l -f -
# 127.0.0.1:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.5
# 10.10.40.20:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.5
2048 SHA256:538+RXBboFrYZDfYBdRpZs8EymGVe9SzznL7dA1jW9g 127.0.0.1 (RSA)
2048 SHA256:538+RXBboFrYZDfYBdRpZs8EymGVe9SzznL7dA1jW9g 10.10.40.20 (RSA)
</code>```

Body:
I have two ways of accessing my remote host ssh server:

using its local IP addres

using its public IP address

Yesterday, I reinstalled my SSH server on the remote host and I updated my known hosts file for the local IP address. I am now off of my local network and trying to connect to my server using its public IP address and I realized I forgot to update my known hosts file after reinstalling the SSH service. This is giving me the common error below.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
MD5:FINGERPRINT.
Please contact your system administrator.
Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /Users/user/.ssh/known_hosts:25
ECDSA host key for [PUBLIC IP]:PORT has changed and you have requested strict checking.
Host key verification failed.

I'm 99% sure this is because I changed the SSH server, however, if I wanted to double check and verify, how would I do this?

My question is

How can I verify the new fingerprint of the remote host against the fingerprint saved for the local IP address of the server?

What I've Done

I ran the following command: ssh-keygen -lv -f ~/.ssh/known_hosts and found the SHA256 fingerprint saved for the local ip address of my server.

I compared this to the SHA256 fingerprint being sent to me from my remote host, and they appear to be identical.

How can I be 100% sure? Did I do this properly?

Body:
When you say "updated" your known_hosts file, does that also mean you removed the old entry?

You can run this quick oneliner to quickly get the current fingerprint via local ip and public ip.

ssh-keyscan -t rsa <Local IP of host> <Remote IP of host> | ssh-keygen -l -f -

Here is a usage example scanning one of my Linux systems using the loopback interface as the second scan address.

$ ssh-keyscan -t rsa 127.0.0.1 10.10.40.20  | ssh-keygen -l -f -
# 127.0.0.1:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.5
# 10.10.40.20:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.5
2048 SHA256:538+RXBboFrYZDfYBdRpZs8EymGVe9SzznL7dA1jW9g 127.0.0.1 (RSA)
2048 SHA256:538+RXBboFrYZDfYBdRpZs8EymGVe9SzznL7dA1jW9g 10.10.40.20 (RSA)


问:
Can the By strategy tagName be replaced with cssSelector for the same value?
I replaced the locator tagName with cssselector without changing the arguments and the code still worked perfectly.
The previous script was:

```<code>Driver.findElement(By.tagName("*enter tagName*");
</code>```

Replacement code is:

```<code>Driver.findElement(By.cssSelector("*enter tagName*");
</code>```

The code worked despite the fact that I did not use any cssSelector combination.

How is that possible?

答:
By.TAG_NAME is always equivalent to By.CSS_SELECTOR

As per the definition of find_element():

```<code>elif by == By.TAG_NAME:
    by = By.CSS_SELECTOR

</code>```

Hence the previous line of code:

```<code>Driver.findElement(By.tagName("enter tagName");
</code>```

and the replacement line of code:

```<code>Driver.findElement(By.cssSelector("enter tagName");
</code>```

was equivalent.

Body:
I replaced the locator tagName with cssselector without changing the arguments and the code still worked perfectly.
The previous script was:

Driver.findElement(By.tagName("*enter tagName*");

Replacement code is:

Driver.findElement(By.cssSelector("*enter tagName*");

The code worked despite the fact that I did not use any cssSelector combination.

How is that possible?

Body:
By.TAG_NAME is always equivalent to By.CSS_SELECTOR

As per the definition of find_element():

elif by == By.TAG_NAME:
    by = By.CSS_SELECTOR

Hence the previous line of code:

Driver.findElement(By.tagName("enter tagName");

and the replacement line of code:

Driver.findElement(By.cssSelector("enter tagName");

was equivalent.


问:
In Flutter, Getx package unknownRoute not working
I'm starting to learn Getx in flutter, and using navigation.

I want to set unknownRoute, in case that there is a typo etc in the namedroute, so the app should  go to a default page.

I do like this:

```<code> return GetMaterialApp(
        title: 'Named navigation',
        unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
        initialRoute: '/', // this defines with route will be opened first

        getPages: [
          GetPage(name: '/', page: () => MyNavigationNamed()),
          GetPage(name: '/second', page: () => SecondScreenNamed()),
          GetPage(name: '/third', page: () => ThirdParametersScreenNamed()),
          GetPage(
              name: '/third_with_built_param/:someValue',
              page: () => ThirdParametersScreenNamed()),
        ],
</code>```

I have the widget:

```<code>class UnknownRoutePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(child: Text('UNKNOWN ROUTE')));
  }

}
</code>```

However, then when I try to test it by making a mistake in the route name, like this:

```<code> ElevatedButton(
                  onPressed: () {
                    Get.toNamed(
                      '/s');     //THIS IS A DUMMY INCORRECT NAME TO TESTING
                  },
                  child: Text('Error in route name, goes to defalt set above.'),
                ),
</code>```

I expect my UnknownRoutePage() to open.

However I get this message:

```<code>The following assertion was thrown building Directionality(textDirection: ltr):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 5033 pos 14: '_dependents.isEmpty': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md

The relevant error-causing widget was:
  Directionality file:///Users/reuvenberman/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.3.8/lib/get_navigation/src/root/get_material_app.dart:217:12
When the exception was thrown, this was the stack:
#2      InheritedElement.debugDeactivated.<anonymous closure> (package:flutter/src/widgets/framework.dart:5033:14)
#3      InheritedElement.debugDeactivated (package:flutter/src/widgets/framework.dart:5035:6)
#4      _InactiveElements._deactivateRecursively.<anonymous closure> (package:flutter/src/widgets/framework.dart:1869:15)
#5      _InactiveElements._deactivateRecursively (package:flutter/src/widgets/framework.dart:1871:6)
#6      ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4628:14)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in widget tree.

The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [LabeledGlobalKey<NavigatorState>#56deb Key Created by default]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- Directionality(textDirection: ltr)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack:
#0      BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2900:15)
#1      BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2925:8)
#2      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:877:19)
#3      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:328:5)
#4      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
...
</code>```

Why isn't this working?

Thanks

答:
I am facing the same problem and also could not find any information surrounding the subject. after doing some testing and reviewing the actual package code I came to the conclusion that GetX only cares if it can match the route at the start of the URI. So if you have a route for "/" then anything after the "/" such as "/non-existent-route/1/2/3/" will still match "/" because it starts with "/". Similarly, if you have a route like "/admin-area" and another for "/admin-area/home" then "/admin-area/non-existent-route/1/2/3/" would still get matched with "/admin-area" and a URI like "/admin-area/home/non-existent-route/1/2/3/" would still match with "/admin-area/home". As this is not the expected behaviour for the web, it can cause problems when using the currentRoute to highlight the current page in your navigation, and considering the documentation for GetX is so poor, I can only assume this is a bug.

The only way I could properly get around this issue is by not using the GetMaterialApp getPages property at all and using onGenerateRoute instead. Get.toNamed still works and the router will only route to exact matches, like this:

```<code>  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: "/",
      onGenerateRoute: (RouteSettings route) {
        var uri = Uri.parse(route.name!);
        switch (uri.path) {
          case "/":
            return MaterialPageRoute(
              settings: route,
              builder: (context) => const RootPage(),
            );
          default:
            return MaterialPageRoute(
              settings: route,
              builder: (context) => const UnkownPage(),
            );
        }
      },
    );
  }
</code>```

if you wish, you can also move this logic out of the GetMaterialApp like this:

```<code>@override
Widget build(BuildContext context) {
  return GetMaterialApp(
    initialRoute: "/",
    onGenerateRoute: generateRoutes
    },
  );
}

//another file
Route<dynamic> generateRoutes(RouteSettings route) {
  var uri = Uri.parse(route.name!);
  switch (uri.path) {
    case "/":
      return MaterialPageRoute(
        settings: route,
        builder: (context) => const UnimplementedPage('Unkown'),
      );
    default:
      return MaterialPageRoute(
        settings: route,
        builder: (context) => const UnimplementedPage('Unkown'),
      );
  }
}
</code>```

Body:
I'm starting to learn Getx in flutter, and using navigation.

I want to set unknownRoute, in case that there is a typo etc in the namedroute, so the app should  go to a default page.

I do like this:

 return GetMaterialApp(
        title: 'Named navigation',
        unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
        initialRoute: '/', // this defines with route will be opened first

        getPages: [
          GetPage(name: '/', page: () => MyNavigationNamed()),
          GetPage(name: '/second', page: () => SecondScreenNamed()),
          GetPage(name: '/third', page: () => ThirdParametersScreenNamed()),
          GetPage(
              name: '/third_with_built_param/:someValue',
              page: () => ThirdParametersScreenNamed()),
        ],

I have the widget:

class UnknownRoutePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(child: Text('UNKNOWN ROUTE')));
  }

}

However, then when I try to test it by making a mistake in the route name, like this:

 ElevatedButton(
                  onPressed: () {
                    Get.toNamed(
                      '/s');     //THIS IS A DUMMY INCORRECT NAME TO TESTING
                  },
                  child: Text('Error in route name, goes to defalt set above.'),
                ),

I expect my UnknownRoutePage() to open.

However I get this message:

The following assertion was thrown building Directionality(textDirection: ltr):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 5033 pos 14: '_dependents.isEmpty': is not true.

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md

The relevant error-causing widget was:
  Directionality file:///Users/reuvenberman/Developer/flutter/.pub-cache/hosted/pub.dartlang.org/get-4.3.8/lib/get_navigation/src/root/get_material_app.dart:217:12
When the exception was thrown, this was the stack:
#2      InheritedElement.debugDeactivated.<anonymous closure> (package:flutter/src/widgets/framework.dart:5033:14)
#3      InheritedElement.debugDeactivated (package:flutter/src/widgets/framework.dart:5035:6)
#4      _InactiveElements._deactivateRecursively.<anonymous closure> (package:flutter/src/widgets/framework.dart:1869:15)
#5      _InactiveElements._deactivateRecursively (package:flutter/src/widgets/framework.dart:1871:6)
#6      ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4628:14)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in widget tree.

The following GlobalKey was specified multiple times in the widget tree. This will lead to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the previous instance is moved to the new location. The key was:
- [LabeledGlobalKey<NavigatorState>#56deb Key Created by default]
This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.
The specific parent that did not update after having one or more children forcibly removed due to GlobalKey reparenting is:
- Directionality(textDirection: ltr)
A GlobalKey can only be specified on one widget at a time in the widget tree.
When the exception was thrown, this was the stack:
#0      BuildOwner.finalizeTree.<anonymous closure> (package:flutter/src/widgets/framework.dart:2900:15)
#1      BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:2925:8)
#2      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:877:19)
#3      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:328:5)
#4      SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
...

Why isn't this working?

Thanks

Body:
I am facing the same problem and also could not find any information surrounding the subject. after doing some testing and reviewing the actual package code I came to the conclusion that GetX only cares if it can match the route at the start of the URI. So if you have a route for "/" then anything after the "/" such as "/non-existent-route/1/2/3/" will still match "/" because it starts with "/". Similarly, if you have a route like "/admin-area" and another for "/admin-area/home" then "/admin-area/non-existent-route/1/2/3/" would still get matched with "/admin-area" and a URI like "/admin-area/home/non-existent-route/1/2/3/" would still match with "/admin-area/home". As this is not the expected behaviour for the web, it can cause problems when using the currentRoute to highlight the current page in your navigation, and considering the documentation for GetX is so poor, I can only assume this is a bug.

The only way I could properly get around this issue is by not using the GetMaterialApp getPages property at all and using onGenerateRoute instead. Get.toNamed still works and the router will only route to exact matches, like this:

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialRoute: "/",
      onGenerateRoute: (RouteSettings route) {
        var uri = Uri.parse(route.name!);
        switch (uri.path) {
          case "/":
            return MaterialPageRoute(
              settings: route,
              builder: (context) => const RootPage(),
            );
          default:
            return MaterialPageRoute(
              settings: route,
              builder: (context) => const UnkownPage(),
            );
        }
      },
    );
  }

if you wish, you can also move this logic out of the GetMaterialApp like this:

@override
Widget build(BuildContext context) {
  return GetMaterialApp(
    initialRoute: "/",
    onGenerateRoute: generateRoutes
    },
  );
}

//another file
Route<dynamic> generateRoutes(RouteSettings route) {
  var uri = Uri.parse(route.name!);
  switch (uri.path) {
    case "/":
      return MaterialPageRoute(
        settings: route,
        builder: (context) => const UnimplementedPage('Unkown'),
      );
    default:
      return MaterialPageRoute(
        settings: route,
        builder: (context) => const UnimplementedPage('Unkown'),
      );
  }
}


答:
For a single record written by a format like

```<code>write (*, '(999(3X,E17.8)') a
</code>```

we can determine how many characters would be written.  For each element there will be three spaces followed by a field of width 17: a total of 20 characters for each element. There will then be a number of characters to end the record (depending on filesystem, operating system, etc., usually one or two).

Knowing how large each record is, and how many records are written, you have the size. Depending again on system settings, you may also see a separate end-of-file marker of some size.

We can answer this question because we know how large each field is going to be. We don't always know that from a format. For example, with some edit descriptors the field width is determined later on: A, I0, G0.6, etc., are such.

Finally, note also that without colon editing we may get extra output for an element. X is a special case, if we instead had

```<code>write (*, '(999("   ",E17.8)') a
</code>```

then there would be three spaces additional spaces after the final element written out before the end of the record. This can be prevented in

```<code>write (*, '(999("   ":,,E17.8)') a
</code>```

X is a position edit descriptor: it doesn't actually transfer data so doesn't add to the transfer count unless further data are written.

Title: How to approximate the size of a text file containing a matrix, written by Fortran?

Body:
I have written an N*N matrix to a formatted text file using Fortran. The Fortran output format was N(3X,E17.8), where N is the matrix size.

Example of one matrix element:    0.19860753E-08 i.e. "(three spaces)0.19860753E-08".

A 558x558 Matrix has a file size of 5.294.302 Bytes.

How could I approximate the file size for an N*N matrix for any value of N?

Body:
For a single record written by a format like

write (*, '(999(3X,E17.8)') a

we can determine how many characters would be written.  For each element there will be three spaces followed by a field of width 17: a total of 20 characters for each element. There will then be a number of characters to end the record (depending on filesystem, operating system, etc., usually one or two).

Knowing how large each record is, and how many records are written, you have the size. Depending again on system settings, you may also see a separate end-of-file marker of some size.

We can answer this question because we know how large each field is going to be. We don't always know that from a format. For example, with some edit descriptors the field width is determined later on: A, I0, G0.6, etc., are such.

Finally, note also that without colon editing we may get extra output for an element. X is a special case, if we instead had

write (*, '(999("   ",E17.8)') a

then there would be three spaces additional spaces after the final element written out before the end of the record. This can be prevented in

write (*, '(999("   ":,,E17.8)') a

X is a position edit descriptor: it doesn't actually transfer data so doesn't add to the transfer count unless further data are written.


问:
How to set only vertical padding?
Sometimes I would like to set top and bottom padding explicitly on an element but leave left and right padding to the unchanged browser default. I know I can write

```<code>.myElement { padding-top: 20px; }
.myElement { padding-bottom: 20px; }
</code>```

but this way I need to repeat both the selector .myElement and the length value twice - or rather copy and paste the whole line and switch left with right.
I was hoping to find something less redundant, so I tried to use padding with two values and replace the second length with inherit. That's not good CSS, I know, it was an attempt, but it doesn't work either (sets horizontal padding to 0):

```<code>.myElement { padding: 20px inherit; }
</code>```

See here: http://jsfiddle.net/185ty3yp/

Any advice how to do it better?

答:
I understand one of the reasons for finding vertical padding might be wanting just to change one place in future modification.  If so, we can try:</p>
```<code>.element{
    --title-vertical-padding: 20px;
    padding-top: var(--title-vertical-padding);
    padding-bottom: var(--title-vertical-padding);
}
</code>```

Title: How to set only vertical padding?

Body:
Sometimes I would like to set top and bottom padding explicitly on an element but leave left and right padding to the unchanged browser default. I know I can write

.myElement { padding-top: 20px; }
.myElement { padding-bottom: 20px; }

but this way I need to repeat both the selector .myElement and the length value twice - or rather copy and paste the whole line and switch left with right.
I was hoping to find something less redundant, so I tried to use padding with two values and replace the second length with inherit. That's not good CSS, I know, it was an attempt, but it doesn't work either (sets horizontal padding to 0):

.myElement { padding: 20px inherit; }

See here: http://jsfiddle.net/185ty3yp/

Any advice how to do it better?

Body:
I understand one of the reasons for finding vertical padding might be wanting just to change one place in future modification.  If so, we can try:

.element{
    --title-vertical-padding: 20px;
    padding-top: var(--title-vertical-padding);
    padding-bottom: var(--title-vertical-padding);
}


问:
Strange edge behaviour of surface plot in matplotlib
I would like to make surface plot of a function which is discontinuous at certain values in parameter space. It is near these discontinuities that the plot's coloring becomes incorrect, as shown in the picture below. How can I fix this?

My code is given below:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

def phase(mu_a, mu_b, t, gamma):
    theta = 0.5*np.arctan2(2*gamma, mu_b-mu_a)
    epsilon = 2*gamma**2/np.sqrt((mu_a-mu_b)**2+4*gamma**2)
    y1 = np.arccos(0.5/t*(-mu_a*np.sin(theta)**2 -mu_b*np.cos(theta)**2 - epsilon))
    y2 = np.arccos(0.5/t*(-mu_a*np.cos(theta)**2 -mu_b*np.sin(theta)**2 + epsilon))
    return y1+y2

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-2.5, 2.5, 0.01)
Y = np.arange(-2.5, 2.5, 0.01)
X, Y = np.meshgrid(X, Y)
Z = phase(X, Y, 1, 0.6)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

surf.set_clim(1, 5)
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()
</code>```

答:
An idea is to make all the arrays 1D, filter out the NaN values and then call ax.plot_trisurf:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

def phase(mu_a, mu_b, t, gamma):
    theta = 0.5 * np.arctan2(2 * gamma, mu_b - mu_a)
    epsilon = 2 * gamma ** 2 / np.sqrt((mu_a - mu_b) ** 2 + 4 * gamma ** 2)
    with np.errstate(divide='ignore', invalid='ignore'):
        y1 = np.arccos(0.5 / t * (-mu_a * np.sin(theta) ** 2 - mu_b * np.cos(theta) ** 2 - epsilon))
        y2 = np.arccos(0.5 / t * (-mu_a * np.cos(theta) ** 2 - mu_b * np.sin(theta) ** 2 + epsilon))
    return y1 + y2

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

# Make data.
X = np.linspace(-2.5, 2.5, 200)
Y = np.linspace(-2.5, 2.5, 200)
X, Y = np.meshgrid(X, Y)
X = X.ravel() # make the array 1D
Y = Y.ravel()
Z = phase(X, Y, 1, 0.6)
mask = ~np.isnan(Z) # select the indices of the valid values

# Plot the surface.
surf = ax.plot_trisurf(X[mask], Y[mask], Z[mask], cmap=cm.coolwarm, linewidth=0, antialiased=False)

surf.set_clim(1, 5)
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()
```

Some remarks:

plot_trisurf will join the XY-values via triangles; this only works well if the domain is convex

to make things draw quicker, less points could be used (the original used 500x500 points, the code here reduces that to 200x200

calling fig.gca(projection='3d') has been deprecated; instead, you could call fig.add_subplot(projection='3d')

the warnings for dividing by zero or using arccos out of range can be temporarily suppressed; that way the warning will still be visible for situations when such isn't expected behavior

Body:
I would like to make surface plot of a function which is discontinuous at certain values in parameter space. It is near these discontinuities that the plot's coloring becomes incorrect, as shown in the picture below. How can I fix this?

My code is given below:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

def phase(mu_a, mu_b, t, gamma):
    theta = 0.5*np.arctan2(2*gamma, mu_b-mu_a)
    epsilon = 2*gamma**2/np.sqrt((mu_a-mu_b)**2+4*gamma**2)
    y1 = np.arccos(0.5/t*(-mu_a*np.sin(theta)**2 -mu_b*np.cos(theta)**2 - epsilon))
    y2 = np.arccos(0.5/t*(-mu_a*np.cos(theta)**2 -mu_b*np.sin(theta)**2 + epsilon))
    return y1+y2

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.arange(-2.5, 2.5, 0.01)
Y = np.arange(-2.5, 2.5, 0.01)
X, Y = np.meshgrid(X, Y)
Z = phase(X, Y, 1, 0.6)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

surf.set_clim(1, 5)
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

Body:
An idea is to make all the arrays 1D, filter out the NaN values and then call ax.plot_trisurf:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

def phase(mu_a, mu_b, t, gamma):
    theta = 0.5 * np.arctan2(2 * gamma, mu_b - mu_a)
    epsilon = 2 * gamma ** 2 / np.sqrt((mu_a - mu_b) ** 2 + 4 * gamma ** 2)
    with np.errstate(divide='ignore', invalid='ignore'):
        y1 = np.arccos(0.5 / t * (-mu_a * np.sin(theta) ** 2 - mu_b * np.cos(theta) ** 2 - epsilon))
        y2 = np.arccos(0.5 / t * (-mu_a * np.cos(theta) ** 2 - mu_b * np.sin(theta) ** 2 + epsilon))
    return y1 + y2

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

# Make data.
X = np.linspace(-2.5, 2.5, 200)
Y = np.linspace(-2.5, 2.5, 200)
X, Y = np.meshgrid(X, Y)
X = X.ravel() # make the array 1D
Y = Y.ravel()
Z = phase(X, Y, 1, 0.6)
mask = ~np.isnan(Z) # select the indices of the valid values

# Plot the surface.
surf = ax.plot_trisurf(X[mask], Y[mask], Z[mask], cmap=cm.coolwarm, linewidth=0, antialiased=False)

surf.set_clim(1, 5)
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

Some remarks:

plot_trisurf will join the XY-values via triangles; this only works well if the domain is convex

to make things draw quicker, less points could be used (the original used 500x500 points, the code here reduces that to 200x200

calling fig.gca(projection='3d') has been deprecated; instead, you could call fig.add_subplot(projection='3d')

the warnings for dividing by zero or using arccos out of range can be temporarily suppressed; that way the warning will still be visible for situations when such isn't expected behavior


问:
CreateMutex and ActiveX
I'm developing an Internet Explorer ActiveX plugin using Qt, and trying to make the installer ensure the plugin is not running before continuing. A standard approach to this is to create a named mutex in the application and try to open it in the installer.

This works fine when built as a standalone .exe, but when the plugin DLL is loaded by either idc.exe (to register the server or handle the type library) or IE itself (after adding a test against argv[0] to skip CreateMutex for the idc runs), the CreateMutex call crashes.

Here's how I'm calling it:

CreateMutex((LPSECURITY_ATTRIBUTES)MUTEX_ALL_ACCESS, FALSE, "mutex_name_here");

Is there a reason this should fail when run within the context of an ActiveX server, but work correctly when running standalone? Is there something else I'm missing here?

答:
The first parameter to CreateMutex() is a pointer to a SECURITY_ATTRIBUTES structure (which contains a pointer to a security descriptor); it's not a set of requested access rights bits, which is what you're passing in. I'm not sure why that would work any better in a standalone application.

You probably want to pass in NULL for the first parameters so the mutex gets created with a default security descriptor.

The Desired Access bits would get passed to OpenMutex().

Title: CreateMutex and ActiveX


问:
Dispatch type for custom middleware in redux
I'm using redux toolkit, and have created a thunk using createAsyncThunk that gets called from a middleware (code below). What is the correct dispatch type? Right now it only works if I specify "any".</p>
```<code>
import { Action, Dispatch } from "redux";
import { updateTerm } from "../slices/explore";

const middleWare = ({ dispatch }: { dispatch: Dispatch<Action> }) => {
  return (next: (action: Action) => void) => {
    return (action: Action) => {
      next(action);
      if (updateTerm.match(action)) {
          dispatch<any>(getShows(action.payload));
      }
    };
  };
};

const getShows = createAsyncThunk<
  Show[],
  string,
  { rejectValue: SearchError }
>("explore/getShows", async (term: string, { rejectWithValue }) => {
 //do async stuff
});

</code>```

答:
The short answer is that you would need to use the ThunkDispatch type from the redux-thunk library.

Ideally, you wouldn't reference that at all, and instead use [the AppDispatchtype inferred fromstore.dispatch](https://redux.js.org/tutorials/typescript-quick-start#define-root-state-and-dispatch-types).  However, because this is a middleware, and middleware themselves alter the type of store.dispatch`, you'd end up with a circular type definition problem.

Having said that, I'd actually recommend not writing a custom middleware here, especially for just dispatching one action.

Instead, I'd recommend using the new "listener middleware" that will be out in the next version of Redux Toolkit.  It's currently available as a standalone @rtk-incubator/action-listener-middleware package.

Body:
I'm using redux toolkit, and have created a thunk using createAsyncThunk that gets called from a middleware (code below). What is the correct dispatch type? Right now it only works if I specify "any".

import { Action, Dispatch } from "redux";
import { updateTerm } from "../slices/explore";

const middleWare = ({ dispatch }: { dispatch: Dispatch<Action> }) => {
  return (next: (action: Action) => void) => {
    return (action: Action) => {
      next(action);
      if (updateTerm.match(action)) {
          dispatch<any>(getShows(action.payload));
      }
    };
  };
};

const getShows = createAsyncThunk<
  Show[],
  string,
  { rejectValue: SearchError }
>("explore/getShows", async (term: string, { rejectWithValue }) => {
 //do async stuff
});


问:
dynamic lazy loading in blazor
In a Blazor wasm project I would like to dynamically load a second project without knowing the project at compile time (.Net5).
Therefore the normal 'lazy loading' does not work for me.
Are there libraries for such purposes? Or an example solution</p>

答:
I am also looking for this capability.
The static compile time referance in .net 6 is not great.

Have a look at oqtane they were doing some work in lazy loading at runtime back in .net 3.1, unfortunatly it seems that they went more into a nuget direction instead of just dll's
https://docs.oqtane.org/index.html
https://github.com/oqtane/oqtane.framework/discussions/1076

Title: dynamic lazy loading in blazor


问:
Issues removing words from a list in Python
I'm building a Wordle solver. Basically removing words from a list, if they don't have specific characters, or don't have them at specific locations. I'm not concerned about the statistics for optimal choices yet.

When I run the below code (I think all relevant sections are included), my output is clear that it found a letter matching position to the 'word of the day'. But then the next iteration, it will choose a word that doesn't have that letter, when it should only select from remaining words.

Are words not actually being removed? Or is there something shadowing a scope I can't find?
I've rewritten whole sections, with the exact same problem happening.

```<code>#Some imports and reading the word list here.

def word_compare(word_of_the_day, choice_word):
    results = []
    index = 0
    letters[:] = choice_word
    for letter in letters:
        if letter is word_of_the_day[index]:
            results.append((letter, 2, index))
        elif letter in word_of_the_day:
            results.append((letter, 1, index))
        else:
            results.append((letter, 0, index))
        index += 1
    print("\nIteration %s\nWord of the Day: %s,\nChoice Word: %s,\nResults: %s" % (
        iteration, word_of_the_day, choice_word, results))
    return results

def remove_wrong_words():
    for item in results:
        if item[1] == 0:
            for word in words:
                if item[0] in word:
                    words.remove(word)
    for item in results:
        if item[1] == 2:
            for word in words:
                if word[item[2]] != item[0]:
                    words.remove(word)
    print("Words Remaining: %s" % len(words))
    return words

words, letters = prep([])
# choice_word = best_word_choice()
choice_word = "crane"
iteration = 1
word_of_the_day = random.choice(words)

while True:
    if choice_word == word_of_the_day:
        break
    else:
        words.remove(choice_word)
        results = word_compare(word_of_the_day, choice_word)
        words = remove_wrong_words()
        if len(words) < 10:
            print(words)
        choice_word = random.choice(words)
        iteration += 1
</code>```

Output I'm getting:

```<code>Iteration 1
Word of the Day: stake,
Choice Word: crane,
Results: [('c', 0, 0), ('r', 0, 1), ('a', 2, 2), ('n', 0, 3), ('e', 2, 4)]
Words Remaining: 386

Iteration 2
Word of the Day: stake,
Choice Word: lease,
Results: [('l', 0, 0), ('e', 1, 1), ('a', 2, 2), ('s', 1, 3), ('e', 2, 4)]
Words Remaining: 112

Iteration 3
Word of the Day: stake,
Choice Word: paste,
Results: [('p', 0, 0), ('a', 1, 1), ('s', 1, 2), ('t', 1, 3), ('e', 2, 4)]
Words Remaining: 81

Iteration 4
Word of the Day: stake,
Choice Word: spite,
</code>```

... This continues for a while until solved. In this output, 'a' is found to be in the correct place (value of 2 in the tuple) on the second iteration. This should remove all words from the list that don't have 'a' as the third character. Instead 'paste' and 'spite' are chosen for later iterations from that same list, instead of having been removed.

答:
Your issue has to do with removing an item from a list while you iterate over it. This often results in skipping later values, as the list iteration is being handled by index, under the covers.

Specifically, the problem is here (and probably in the other loop too):

```<code>for word in words:
    if item[0] in word:
        words.remove(word)
</code>```

If the if condition is true for the first word in the words list, the second word will not be checked. That's because when the for loop asks the list iterator for the next value, it's going to yield the second value of the list as it now stands, which is going to be the third value from the original list (since the first one is gone).

There are a few ways you could avoid this problem.

One approach is to iterate on a copy of the list you're going to modify. This means that the iterator won't ever skip over anything, since the copied list is not having anything removed from it as you go (only the original list is changing). A common way to make the copy is with a slice:

```<code>for word in words[:]:       # iterate on a copy of the list
    if item[0] in word:
        words.remove(word)  # modify the original list here
</code>```

Another option is to build a new list full of the valid values from the original list, rather than removing the invalid ones. A list comprehension is often good enough for this:

```<code>words = [word for word in words if item[0] not in word]
</code>```

This may be slightly complicated in your example because you're using global variables. You would either need to change that design (and e.g. accept a list as an argument and return the new version), or add global words statement to let the function's code rebind the global variable (rather than modifying it in place).

Body:
I'm building a Wordle solver. Basically removing words from a list, if they don't have specific characters, or don't have them at specific locations. I'm not concerned about the statistics for optimal choices yet.

When I run the below code (I think all relevant sections are included), my output is clear that it found a letter matching position to the 'word of the day'. But then the next iteration, it will choose a word that doesn't have that letter, when it should only select from remaining words.

Are words not actually being removed? Or is there something shadowing a scope I can't find?
I've rewritten whole sections, with the exact same problem happening.

#Some imports and reading the word list here.

def word_compare(word_of_the_day, choice_word):
    results = []
    index = 0
    letters[:] = choice_word
    for letter in letters:
        if letter is word_of_the_day[index]:
            results.append((letter, 2, index))
        elif letter in word_of_the_day:
            results.append((letter, 1, index))
        else:
            results.append((letter, 0, index))
        index += 1
    print("\nIteration %s\nWord of the Day: %s,\nChoice Word: %s,\nResults: %s" % (
        iteration, word_of_the_day, choice_word, results))
    return results

def remove_wrong_words():
    for item in results:
        if item[1] == 0:
            for word in words:
                if item[0] in word:
                    words.remove(word)
    for item in results:
        if item[1] == 2:
            for word in words:
                if word[item[2]] != item[0]:
                    words.remove(word)
    print("Words Remaining: %s" % len(words))
    return words

words, letters = prep([])
# choice_word = best_word_choice()
choice_word = "crane"
iteration = 1
word_of_the_day = random.choice(words)

while True:
    if choice_word == word_of_the_day:
        break
    else:
        words.remove(choice_word)
        results = word_compare(word_of_the_day, choice_word)
        words = remove_wrong_words()
        if len(words) < 10:
            print(words)
        choice_word = random.choice(words)
        iteration += 1

Output I'm getting:

Iteration 1
Word of the Day: stake,
Choice Word: crane,
Results: [('c', 0, 0), ('r', 0, 1), ('a', 2, 2), ('n', 0, 3), ('e', 2, 4)]
Words Remaining: 386

Iteration 2
Word of the Day: stake,
Choice Word: lease,
Results: [('l', 0, 0), ('e', 1, 1), ('a', 2, 2), ('s', 1, 3), ('e', 2, 4)]
Words Remaining: 112

Iteration 3
Word of the Day: stake,
Choice Word: paste,
Results: [('p', 0, 0), ('a', 1, 1), ('s', 1, 2), ('t', 1, 3), ('e', 2, 4)]
Words Remaining: 81

Iteration 4
Word of the Day: stake,
Choice Word: spite,

... This continues for a while until solved. In this output, 'a' is found to be in the correct place (value of 2 in the tuple) on the second iteration. This should remove all words from the list that don't have 'a' as the third character. Instead 'paste' and 'spite' are chosen for later iterations from that same list, instead of having been removed.

Body:
Your issue has to do with removing an item from a list while you iterate over it. This often results in skipping later values, as the list iteration is being handled by index, under the covers.

Specifically, the problem is here (and probably in the other loop too):

for word in words:
    if item[0] in word:
        words.remove(word)

If the if condition is true for the first word in the words list, the second word will not be checked. That's because when the for loop asks the list iterator for the next value, it's going to yield the second value of the list as it now stands, which is going to be the third value from the original list (since the first one is gone).

There are a few ways you could avoid this problem.

One approach is to iterate on a copy of the list you're going to modify. This means that the iterator won't ever skip over anything, since the copied list is not having anything removed from it as you go (only the original list is changing). A common way to make the copy is with a slice:

for word in words[:]:       # iterate on a copy of the list
    if item[0] in word:
        words.remove(word)  # modify the original list here

Another option is to build a new list full of the valid values from the original list, rather than removing the invalid ones. A list comprehension is often good enough for this:

words = [word for word in words if item[0] not in word]

This may be slightly complicated in your example because you're using global variables. You would either need to change that design (and e.g. accept a list as an argument and return the new version), or add global words statement to let the function's code rebind the global variable (rather than modifying it in place).


问:
Custom React Router Prompt: A history supports only one prompt at a time
I have created a custom React Router Prompt to show when the user wants to navigate to other page and have not saved the data yet.

Everything seems to be working as it should, but I have an annoying warning:

```<code>Warning: A history supports only one prompt at a time
</code>```

The component looks like this:

```<code>export function RouterPrompt(props) {
    const {when, onOK, onCancel, title} = props;

    const history = useHistory();

    const [showPrompt, setShowPrompt] = useState(false);
    const [currentPath, setCurrentPath] = useState("");

    useEffect(() => {
        if (when) {
            history.block((prompt) => {
                setCurrentPath(prompt.pathname);
                setShowPrompt(true);
                return "true";
            });
        } else {
            history.block(() => {
            });
        }
    }, [when]);

    const handleOK = useCallback(async () => {
        if (onOK) {
            const canRoute = await Promise.resolve(onOK());
            if (canRoute) {
                history.block(() => {
                });
                history.push(currentPath);
            }
        }
    }, [currentPath, history, onOK]);

    const handleCancel = useCallback(async () => {
        if (onCancel) {
            const canRoute = await Promise.resolve(onCancel());
            if (canRoute) {
                history.block(() => {
                });
                history.push(currentPath);
            }
        }
        setShowPrompt(false);
    }, [currentPath, history, onCancel]);

    return showPrompt ? (
        <Dialog
            open={showPrompt}
            onClose={handleCancel}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                {title}
            </DialogTitle>
            <DialogContent>
                <DialogContentText id="alert-dialog-description">
                    There are unsaved changes. Are you sure want to leave this page?
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={handleCancel}>Stay on page</Button>
                <Button onClick={handleOK} autoFocus>
                    Leave
                </Button>
            </DialogActions>
        </Dialog>
    ) : null;
}
</code>```

As far as I was able to do some research on this, this comes from the class lifecycle methods (useEffect runs before unmouting the current history.block), but in reality only one Prompt is rendered in the DOM.

Edit

I have discovered another bug, that this will change the path regardless of the actual push or not. So in the URL the path changes but the view don't, so next time when you press back and Confirm, instaed of staying on the page, you will be 2 steps back in history.

答:
I have completely restructured/refactored my code (original code was from a blog post), this seems to be working perfectly (without warnings) and as expected:</p>
```<code>export function RouterPrompt(props) {
    const {when, title} = props;

    const history = useHistory();

    const [showPrompt, setShowPrompt] = useState(false);
    const [currentPath, setCurrentPath] = useState("");

    const unblockRef = useRef();

    function handleShowModal() {
        setShowPrompt(true);
    }

    function onCancel() {
        setShowPrompt(false);
    }

    useEffect(() => {
        unblockRef.current = history.block((location) => {
            if (when) {
                setCurrentPath(location.pathname);
                handleShowModal();
                return false;
            }
            return true;
        });
        return () => {
            unblockRef.current && unblockRef.current();
        };
    }, [when]);

    function handleConfirm() {
        if (unblockRef) {
            unblockRef.current();
        }
        setShowPrompt(false);
        history.push(currentPath);
    }

    return (
        <Dialog
            open={showPrompt}
            onClose={onCancel}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                {title}
            </DialogTitle>
            <DialogContent>
                <DialogContentText id="alert-dialog-description">
                    There are unsaved changes. Are you sure want to leave this page?
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={onCancel}>Stay on page</Button>
                <Button onClick={handleConfirm} autoFocus>
                    Leave
                </Button>
            </DialogActions>
        </Dialog>
    );
}
</code>```

Body:
I have created a custom React Router Prompt to show when the user wants to navigate to other page and have not saved the data yet.

Everything seems to be working as it should, but I have an annoying warning:

Warning: A history supports only one prompt at a time

The component looks like this:

export function RouterPrompt(props) {
    const {when, onOK, onCancel, title} = props;

    const history = useHistory();

    const [showPrompt, setShowPrompt] = useState(false);
    const [currentPath, setCurrentPath] = useState("");

    useEffect(() => {
        if (when) {
            history.block((prompt) => {
                setCurrentPath(prompt.pathname);
                setShowPrompt(true);
                return "true";
            });
        } else {
            history.block(() => {
            });
        }
    }, [when]);

    const handleOK = useCallback(async () => {
        if (onOK) {
            const canRoute = await Promise.resolve(onOK());
            if (canRoute) {
                history.block(() => {
                });
                history.push(currentPath);
            }
        }
    }, [currentPath, history, onOK]);

    const handleCancel = useCallback(async () => {
        if (onCancel) {
            const canRoute = await Promise.resolve(onCancel());
            if (canRoute) {
                history.block(() => {
                });
                history.push(currentPath);
            }
        }
        setShowPrompt(false);
    }, [currentPath, history, onCancel]);

    return showPrompt ? (
        <Dialog
            open={showPrompt}
            onClose={handleCancel}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                {title}
            </DialogTitle>
            <DialogContent>
                <DialogContentText id="alert-dialog-description">
                    There are unsaved changes. Are you sure want to leave this page?
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={handleCancel}>Stay on page</Button>
                <Button onClick={handleOK} autoFocus>
                    Leave
                </Button>
            </DialogActions>
        </Dialog>
    ) : null;
}

As far as I was able to do some research on this, this comes from the class lifecycle methods (useEffect runs before unmouting the current history.block), but in reality only one Prompt is rendered in the DOM.

Edit

I have discovered another bug, that this will change the path regardless of the actual push or not. So in the URL the path changes but the view don't, so next time when you press back and Confirm, instaed of staying on the page, you will be 2 steps back in history.

Body:
I have completely restructured/refactored my code (original code was from a blog post), this seems to be working perfectly (without warnings) and as expected:

export function RouterPrompt(props) {
    const {when, title} = props;

    const history = useHistory();

    const [showPrompt, setShowPrompt] = useState(false);
    const [currentPath, setCurrentPath] = useState("");

    const unblockRef = useRef();

    function handleShowModal() {
        setShowPrompt(true);
    }

    function onCancel() {
        setShowPrompt(false);
    }

    useEffect(() => {
        unblockRef.current = history.block((location) => {
            if (when) {
                setCurrentPath(location.pathname);
                handleShowModal();
                return false;
            }
            return true;
        });
        return () => {
            unblockRef.current && unblockRef.current();
        };
    }, [when]);

    function handleConfirm() {
        if (unblockRef) {
            unblockRef.current();
        }
        setShowPrompt(false);
        history.push(currentPath);
    }

    return (
        <Dialog
            open={showPrompt}
            onClose={onCancel}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                {title}
            </DialogTitle>
            <DialogContent>
                <DialogContentText id="alert-dialog-description">
                    There are unsaved changes. Are you sure want to leave this page?
                </DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={onCancel}>Stay on page</Button>
                <Button onClick={handleConfirm} autoFocus>
                    Leave
                </Button>
            </DialogActions>
        </Dialog>
    );
}


问:
How can a text file be converted from ANSI to UTF-8 with Delphi 7?
I written a program with Delphi 7 which searches *.srt files on a hard drive. This program lists the path and name of these files in a memo. Now I need convert these files from ANSI to UTF-8, but I haven't succeeded.

答:
Did you mean ASCII?

ASCII is backwards compatible with UTF-8.
http://en.wikipedia.org/wiki/UTF-8

OwnerDisplayName: Yilmaz Ekici

LastEditorDisplayName: Eddie

OwnerDisplayName: jms

ContentLicense: CC BY-SA 2.5