问:
How to test error get api request react query useInfiniteQuery with react testing library and jest?
I have a function component that used react query useInfiniteQuery to get list data, now I try to test the useInfiniteQuery with error test case get API but still did not cover the onError object function. Does anyone know how to reach onError test with RTL and jest?

useFetchListUsers.ts

```<code>export const useFetchListUsers = (params) => {
    const { users,
        error,
        isLoading,
        isFetching,
        fetchNextPage,
        hasNextPage } = useInfiniteQuery(['users', ...params], getAllUsers, {
            getNextPageParam: (lastPage) => {
                return ...lastPage;
            },
            onError: (error: AxiosError) => {
                return "Error get data Users from API"
            },
        });

    return { users, error, isLoading, isFetching, fetchNextPage, hasNextPage }
}
</code>```

usersAPI.ts

```<code>export const getAllUsers = async () => {
   const {data} = await axios.get('/v1/users');
   return data;
}
</code>```

displayUsers.test.tsx

```<code>describe('test display list users', () => {
      it("should handle failed get list users", () => {
        (useFetchListUsers as any).mockRejectedValueOnce({
            users: undefined,
        });

            render(
                <QueryClientProvider client={queryClient}>
                    <ListUSers />
                </QueryClientProvider>,
                { store }
            );
            expect(await screen.findByTestId("noUsersAlert")).toBeTruthy();
      })
    })
</code>```

答:
if you mock the whole useFetchListUsers function, you cannot expect the onError callback defined inside of that function to be called, because you have mocked said function :)

Further, the onError callback is a callback to execute side-effects; things returned from that function have no meaning. In fact, the signature of onError is: (err: TError) => void, so it doesn't return anything.

I always advice to stub out the network layer with things like mock-service-worker instead of mocking complete hooks. This will ensure your tests are as close as possible to the real application.

If your queryFn returns a rejected Promise, the error property should be filled with that Error. If your UI reads the error property, you don't need onError at all - as I said, it's only for side effects.

In that case, making your mock so that it actually returns an error next to users: undefined might also do the trick.

Body:
I have a function component that used react query useInfiniteQuery to get list data, now I try to test the useInfiniteQuery with error test case get API but still did not cover the onError object function. Does anyone know how to reach onError test with RTL and jest?

useFetchListUsers.ts

export const useFetchListUsers = (params) => {
    const { users,
        error,
        isLoading,
        isFetching,
        fetchNextPage,
        hasNextPage } = useInfiniteQuery(['users', ...params], getAllUsers, {
            getNextPageParam: (lastPage) => {
                return ...lastPage;
            },
            onError: (error: AxiosError) => {
                return "Error get data Users from API"
            },
        });

    return { users, error, isLoading, isFetching, fetchNextPage, hasNextPage }
}

usersAPI.ts

export const getAllUsers = async () => {
   const {data} = await axios.get('/v1/users');
   return data;
}

displayUsers.test.tsx

describe('test display list users', () => {
      it("should handle failed get list users", () => {
        (useFetchListUsers as any).mockRejectedValueOnce({
            users: undefined,
        });

            render(
                <QueryClientProvider client={queryClient}>
                    <ListUSers />
                </QueryClientProvider>,
                { store }
            );
            expect(await screen.findByTestId("noUsersAlert")).toBeTruthy();
      })
    })


来源: stackexchange

问:
How to add an existing GitHub repository into PHP project in Eclipse?
I worked with class mates on a project to build a static website using CSS and HTML. Then we used visual studios and our work was synchronized with GitHub. Now we are asked to continue our work adding PHP files using Eclipse IDE. My question is how can I add the existing repo on eclipse and share it with my friends?</p>

答: You would add it to the list of Git Repositories that Eclipse knows of, and then import the interesting part (or whole) of the working directory as a project. Check the online User Guide: https://wiki.eclipse.org/EGit/User_Guide#Starting_from_existing_Git_Repositories</p>

ContentLicense: CC BY-SA 4.0


问:
Toggling the CD (RLSD) signal line on a serial port in Windows C
I am trying to set the Carrier Detect (Receive Line Signal Detect) pin on a serial port being controlled by my Windows application. I am already able to set the RTS line high using this function:

```<code>EscapeCommFunction(handle, SETRTS);
</code>```

and then subsequently clear it by using:

```<code>EscapeCommFunction(handle, CLRRTS);
</code>```

I want to be able to do this exact same thing with the CD line, but no such SET/CLR flags exist for the EscapeCommFunction.

答:
RS232 devices can be either a DTE (Data Terminal Equipment) or DCE (Data Communications Equipment).  Examples of DCEs are modems, multiplexors and some line drivers (technically a modem), everything else including your computer is a DTE.

The DCD (RLSD) is an output from a DCE to indicate that has detected the carrier on the comms link i.e. can see the remote modem.

I know of no way to convert a DTE into a DCE with a standard serial port.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set the Carrier Detect (Receive Line Signal Detect) pin on a serial port being controlled by my Windows application. I am already able to set the RTS line high using this function:

EscapeCommFunction(handle, SETRTS);

and then subsequently clear it by using:

EscapeCommFunction(handle, CLRRTS);

I want to be able to do this exact same thing with the CD line, but no such SET/CLR flags exist for the EscapeCommFunction.


问:
How to import CSS modules with Typescript, React and Webpack
How to import CSS modules in Typescript with Webpack?

Generate (or auto-generate) .d.ts files for CSS? And use classic Typescript import statement? With ./styles.css.d.ts:

```<code>import * as styles from './styles.css'
</code>```

Import using require Webpack function?

```<code>let styles = require("./styles.css");
</code>```

But for the last approach I must define the require function.

What is the best approach or best option and one that can also handle IntelliSense for the CSS file definitions and classes?

答:
In 2022, all I needed to do it to add Globals.d.ts file under the src folder

with

```<code>declare module "*.module.css";
declare module "*.module.scss";
</code>```

Then I can import CSS modules in my typescript files as usual for css or scss files:

```<code>import styles from "./Team.module.scss";
</code>```

Body:
How to import CSS modules in Typescript with Webpack?

Generate (or auto-generate) .d.ts files for CSS? And use classic Typescript import statement? With ./styles.css.d.ts:

import * as styles from './styles.css'

Import using require Webpack function?

let styles = require("./styles.css");

But for the last approach I must define the require function.

What is the best approach or best option and one that can also handle IntelliSense for the CSS file definitions and classes?

Body:
In 2022, all I needed to do it to add Globals.d.ts file under the src folder

with

declare module "*.module.css";
declare module "*.module.scss";

Then I can import CSS modules in my typescript files as usual for css or scss files:

import styles from "./Team.module.scss";


问:
how do i make my code start at the same point the user was already on once they go through a valueerror exception?
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.

CODE:

while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            again = str(input("Again? (Y or N) "))
            again = again.upper()
            if again == "Y":
                continue
            elif again == "N":
                break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")
```
<p>EDIT:
So I have made some progress but I have one last problem</p>
<p>CODE:</p>
``` while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            while True:
                again = input("again? (Y or N)")
                if again not in "yYnN":
                    continue
                break
        if again == "Y":
            continue
        elif again == "N":
            break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")
```

The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?

答: You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.</p>

Body:
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.

CODE:

while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            again = str(input("Again? (Y or N) "))
            again = again.upper()
            if again == "Y":
                continue
            elif again == "N":
                break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")

EDIT:
So I have made some progress but I have one last problem

CODE:

 while True:
    try:
        choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
        assert choice == 1
        if choice == (1):
            userInp = input("TYPE: ")

            words = userInp.split()

            start_count = 0
            for word in words:
                word = word.lower()
                if word.startswith("u"):
                    start_count += 1

            print(f"You wrote {len(words)} words.")
            print(f"You wrote {start_count} words that start with u.")
            while True:
                again = input("again? (Y or N)")
                if again not in "yYnN":
                    continue
                break
        if again == "Y":
            continue
        elif again == "N":
            break
    except AssertionError:
        print("Please type a given option.")
    except ValueError:
        print("Please type a given option.")

The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?


问:
Remove duplicates in an object array Javascript
I have an array of objects

```<code>list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]
</code>```

And I'm looking for an efficient way (if possible O(log(n))) to remove duplicates and to end up with

```<code>list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]
</code>```

I've tried _.uniq or even _.contains but couldn't find a satisfying solution.

Thanks!

Edit : The question has been identified as a duplicate of another one. I saw this question before posting but it didn't answer my question since it's an array of object (and not a 2-dim array, thanks Aaron), or at least the solutions on the other question weren't working in my case.

答:
No libraries, and works with any depth

Limitation:

You must provide only string or Number properties as hash objects otherwise you'll get inconsistent results

/**
 * Implementation, you can convert this function to the prototype pattern to allow
 * usage like `myArray.unique(...)`
 */
function unique(array, f) {
  return Object.values(
    array.reduce((acc, item) => ({ ...acc, [f(item).join(``)]: item }), {})
  );
}

const list = [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}, { x: 1, y: 2}];

// Usage
const result = unique(list, item => [item.x, item.y]);

// Output: [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}]
console.log(result);
```
<h2>Snippet Sample</h2>
<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>// Implementation
function unique(array, f) {
  return Object.values(
    array.reduce((acc, item) => ({ ...acc, [f(item).join(``)]: item }), {})
  );
}

// Your object list
const list = [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}, { x: 1, y: 2}];

// Usage
const result = unique(list, item => [item.x, item.y]);

// Add result to DOM
document.querySelector(`p`).textContent = JSON.stringify(result, null, 2);</code>```

```

Body:
I have an array of objects

list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}, {x:1,y:2}]

And I'm looking for an efficient way (if possible O(log(n))) to remove duplicates and to end up with

list = [{x:1,y:2}, {x:3,y:4}, {x:5,y:6}]

I've tried _.uniq or even _.contains but couldn't find a satisfying solution.

Thanks!

Edit : The question has been identified as a duplicate of another one. I saw this question before posting but it didn't answer my question since it's an array of object (and not a 2-dim array, thanks Aaron), or at least the solutions on the other question weren't working in my case.

Body:
No libraries, and works with any depth

Limitation:

You must provide only string or Number properties as hash objects otherwise you'll get inconsistent results

/**
 * Implementation, you can convert this function to the prototype pattern to allow
 * usage like `myArray.unique(...)`
 */
function unique(array, f) {
  return Object.values(
    array.reduce((acc, item) => ({ ...acc, [f(item).join(``)]: item }), {})
  );
}

const list = [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}, { x: 1, y: 2}];

// Usage
const result = unique(list, item => [item.x, item.y]);

// Output: [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}]
console.log(result);

Snippet Sample

// Implementation
function unique(array, f) {
  return Object.values(
    array.reduce((acc, item) => ({ ...acc, [f(item).join(``)]: item }), {})
  );
}

// Your object list
const list = [{ x: 1, y: 2}, {x: 3, y: 4}, { x: 5, y: 6}, { x: 1, y: 2}];

// Usage
const result = unique(list, item => [item.x, item.y]);

// Add result to DOM
document.querySelector(`p`).textContent = JSON.stringify(result, null, 2);

<p></p>


问:
Brush down stroke Lilypond
I'm trying to write a guitar tablature in which there must be a brush down stroke, and I can't find the way to do this with Lilypond. Here is my chord:

```<code>
\score {
  \layout {  }
  <<
    \new TabStaff {
      <e a c'>
    }
  >>
}
</code>```

Below is the result of that code. So I'd like to add an up arrow at the left of that chord.

Does anyone know how to do it?

答:
I'm not sure exactly what symbol you want for a brush downstroke – but I am assuming it is just a low note to high note arpeggio.  (The default direction for an arpeggio is low to high, so musically speaking the arrow is unnecessary.)

In LilyPond the way to mark an arpeggio is by placing the command \arpeggio directly after the chord.

To get arrows on the arpeggio symbols you need to write \arpeggioArrowUp (or \arpeggioArrowDown) beforehand. See 1.3.3 Expressive marks as lines - arpeggio.

Unfortunately, the normal TabStaff doesn't display a lot of normal musical notation, including the arpeggio symbols.

However if you use the command \tabFullNotation inside of the TabStaff, a hybrid of tab notation and regular staff notation is displayed.

NB This will also mean that time signature and note stems etc. will also be printed.

Putting all of this together you should get something like this:

```<code>\score {
    <<
        \new TabStaff {
            \tabFullNotation
            \arpeggioArrowUp
                <e a c'> \arpeggio
        }
    >>
    \layout {  }
}
</code>```

Title: Brush down stroke Lilypond

Body:
I'm trying to write a guitar tablature in which there must be a brush down stroke, and I can't find the way to do this with Lilypond. Here is my chord:

\score {
  \layout {  }
  <<
    \new TabStaff {
      <e a c'>
    }
  >>
}

Below is the result of that code. So I'd like to add an up arrow at the left of that chord.

Does anyone know how to do it?

Body:
I'm not sure exactly what symbol you want for a brush downstroke – but I am assuming it is just a low note to high note arpeggio.  (The default direction for an arpeggio is low to high, so musically speaking the arrow is unnecessary.)

In LilyPond the way to mark an arpeggio is by placing the command \arpeggio directly after the chord.

To get arrows on the arpeggio symbols you need to write \arpeggioArrowUp (or \arpeggioArrowDown) beforehand. See 1.3.3 Expressive marks as lines - arpeggio.

Unfortunately, the normal TabStaff doesn't display a lot of normal musical notation, including the arpeggio symbols.

However if you use the command \tabFullNotation inside of the TabStaff, a hybrid of tab notation and regular staff notation is displayed.

NB This will also mean that time signature and note stems etc. will also be printed.

Putting all of this together you should get something like this:

\score {
    <<
        \new TabStaff {
            \tabFullNotation
            \arpeggioArrowUp
                <e a c'> \arpeggio
        }
    >>
    \layout {  }
}


问:
Test a specific exception type is thrown AND the exception has the right properties
I want to test that MyException is thrown in a certain case. EXPECT_THROW is good here. But I also want to check the exception has a specific state e.g e.msg() == "Cucumber overflow".

How is this best implemented in GTest?

答:
The above answers were helpful, but I wanted to share a solution I am using that keeps each test short while still testing both the exception type and the 'what' value. It works for any function that throws an exception that is derived from std::exception, but could be modified (or templated) to catch other types if needed.

I originally tried using a perfect forwarding type wrapper function, but ended up just using a lambda as a wrapper. Using a lambda is really flexible for re-use, allows all the expected implicit type conversions that happen when calling functions directly, avoids passing pointer-to-member functions, etc..

The important point is to have the wrapper template function throw a custom exception for a 'what-mismatch' that has a type that would not be thrown from the function being tested. This causes EXPECT_THROW to print a nice error about the mismatch. I derived from std::runtime_error since that class has a constructor that accepts a std::string.

```<code>class WhatMismatch : public std::runtime_error {
public:
  WhatMismatch(const std::string& expectedWhat, const std::exception& e)
    : std::runtime_error(std::string("expected: '") + expectedWhat +
                         "', actual: '" + e.what() + '\'') {}
};

template<typename F> auto call(const F& f, const std::string& expectedWhat) {
  try {
    return f();
  } catch (const std::exception& e) {
    if (expectedWhat != e.what()) throw WhatMismatch(expectedWhat, e);
    throw;
  }
}
</code>```

A test for a function foo that should throw a std::domain_error would look like:

```<code>EXPECT_THROW(call([] { foo(); }, "some error message"), std::domain_error);
</code>```

If the function takes parameters, just capture them in the lambda like this:

```<code>EXPECT_THROW(call([p1] { foo(p1); }, "some error message"), std::domain_error);
</code>```

Body:
The above answers were helpful, but I wanted to share a solution I am using that keeps each test short while still testing both the exception type and the 'what' value. It works for any function that throws an exception that is derived from std::exception, but could be modified (or templated) to catch other types if needed.

I originally tried using a perfect forwarding type wrapper function, but ended up just using a lambda as a wrapper. Using a lambda is really flexible for re-use, allows all the expected implicit type conversions that happen when calling functions directly, avoids passing pointer-to-member functions, etc..

The important point is to have the wrapper template function throw a custom exception for a 'what-mismatch' that has a type that would not be thrown from the function being tested. This causes EXPECT_THROW to print a nice error about the mismatch. I derived from std::runtime_error since that class has a constructor that accepts a std::string.

class WhatMismatch : public std::runtime_error {
public:
  WhatMismatch(const std::string& expectedWhat, const std::exception& e)
    : std::runtime_error(std::string("expected: '") + expectedWhat +
                         "', actual: '" + e.what() + '\'') {}
};

template<typename F> auto call(const F& f, const std::string& expectedWhat) {
  try {
    return f();
  } catch (const std::exception& e) {
    if (expectedWhat != e.what()) throw WhatMismatch(expectedWhat, e);
    throw;
  }
}

A test for a function foo that should throw a std::domain_error would look like:

EXPECT_THROW(call([] { foo(); }, "some error message"), std::domain_error);

If the function takes parameters, just capture them in the lambda like this:

EXPECT_THROW(call([p1] { foo(p1); }, "some error message"), std::domain_error);


问:
How to prevent content from re-sizing a flex item?
I'm using CSS flexbox to build a scalable, responsive grid. When applying a Google chart to one of the flexbox items, the item changes size ever so slightly. It's enough to throw the grid out of alignment. I put together the following images to help illustrate the issue.

Flexbox grid before applying Google chart to item 6:

Flexbox grid after applying Google chart to item 6:

The Flexbox grid loads faster than the Google chart, so the grid originally loads correctly. However when the chart loads, item 6 expands slightly, causing image 2 above.

The middle column flex container and item 6 div are setup in css as follows:

```<code>#middlecolumn {
    width: 75%;
    height: 100%;
    display: flex;
    flex-flow: column;
    margin: 0.25%;
}

#item6_div {
    flex: 3;
    margin-top: 0.8vh;
}
</code>```

Note that items 5 and 7 are setup the same way in css, with flex values of 1. I.e. item 6 is 3 times the height of items 5 and 7. As such, when item 6 resizes, the 3:1 ratio is maintained.

Is there something I'm missing in css to prevent the Google chart from resizing its flexbox container item?

答:
Apply this css to the part you want to stretch:</p>
```<code>flex: 1
</code>```

Body:
I'm using CSS flexbox to build a scalable, responsive grid. When applying a Google chart to one of the flexbox items, the item changes size ever so slightly. It's enough to throw the grid out of alignment. I put together the following images to help illustrate the issue.

Flexbox grid before applying Google chart to item 6:

Flexbox grid after applying Google chart to item 6:

The Flexbox grid loads faster than the Google chart, so the grid originally loads correctly. However when the chart loads, item 6 expands slightly, causing image 2 above.

The middle column flex container and item 6 div are setup in css as follows:

#middlecolumn {
    width: 75%;
    height: 100%;
    display: flex;
    flex-flow: column;
    margin: 0.25%;
}

#item6_div {
    flex: 3;
    margin-top: 0.8vh;
}

Note that items 5 and 7 are setup the same way in css, with flex values of 1. I.e. item 6 is 3 times the height of items 5 and 7. As such, when item 6 resizes, the 3:1 ratio is maintained.

Is there something I'm missing in css to prevent the Google chart from resizing its flexbox container item?

Body:
Apply this css to the part you want to stretch:

flex: 1


问:
How to use one AJAX handler for multiple purposes with callbacks?
I have a piece of code written in an object. You can see there is a customers object with a function for adding a new customer and a method for making AJAX calls

var sys = {
  customers: {
    addNew: function(ref, cb = null) {
      if (!cb) { // so it can check if the call to this method was for requesting ajax request or handling its response . note i am sending the callback function reference same as the current
        core.request({
          d: $('form').serialize()
        }, 'sys.customers.addNew', ref);
      } else {
        if (ref.status) {
          $('.customers-list').append('
' + ref.customer.name + '
');
          alert('success')
        }
      }
    },
    updateRowAfterAdd: function() {
      // or i could use this for handling callback by passing its reference instead of the upper same function
    }
  },
  request: function(p = {}, c = null, e = false) {
    $.ajax({
      url: "/to/my/server",
      data: {
        p: p
      },
      type: 'post',
      dataType: 'json',
      beforeSend: function() {

      },
      success: function(r) {
        if (c != null)
          (e ? eval("(" + c + "(r,e));") : eval("(" + c + "(r));"));
      }
    });
  }
}

$(document).on('click', '.addNew', function() {
  sys.customers.addNew($(this));
});```

The idea in this example is to call the AJAX method by passing a callback function reference for handling the success response.

If you look at the addNew() method it is working in two ways. With the help of the second parameter, cb, it is determining that the call to this function was for sending an AJAX request or handling its response back.

I'm using eval() in the success callback which I know is evil, so I want to understand how I can do this without using eval()?

I have multiple things running on my page which need AJAX calls and I don't want to rewrite each of them.

I also need this for AJAX's beforeSuccess() method as well.

答:
The design pattern you're using seems to be a needless abstraction which is causing more problems that it solves.

A better idea would be to have a central 'service' layer which makes the requests to your server side and handles the responses. If you wanted to abstract this further you could have other domain logic abstractions to handle AJAX requests and responses through a single class, however at that stage I would argue you're far better off using an existing framework to do this for you.

A strong recommendation would be to use Angular, given that its MVC pattern is where you're heading anyway.

If you did want to roll your own simplistic version, then a simple example would look something like this:

$(document).on('click', '.addNew', function() {
  services.customers.save($('form').serialize());
});

// in a service layer JS file, far away from UI logic...
let services = {
  customers: {
    save: requestData => {
      $.ajax({
        url: '/to/my/server',
        type: 'post',
        dataType: 'json',
        data: $('form').serialize(),
        success: services.customers.renderUi
      });
    },
    renderCustomerUi: customerData => {
      // optional: extract the UI update logic to your UI layer and pass in the callback as an argument
      if (customerData.status) {
        $('.customers-list').append('
' + customerData.customer.name + '
');
      }
    }
  }
}```

Body:
I have a piece of code written in an object. You can see there is a customers object with a function for adding a new customer and a method for making AJAX calls

var sys = {
  customers: {
    addNew: function(ref, cb = null) {
      if (!cb) { // so it can check if the call to this method was for requesting ajax request or handling its response . note i am sending the callback function reference same as the current
        core.request({
          d: $('form').serialize()
        }, 'sys.customers.addNew', ref);
      } else {
        if (ref.status) {
          $('.customers-list').append('
' + ref.customer.name + '
');
          alert('success')
        }
      }
    },
    updateRowAfterAdd: function() {
      // or i could use this for handling callback by passing its reference instead of the upper same function
    }
  },
  request: function(p = {}, c = null, e = false) {
    $.ajax({
      url: "/to/my/server",
      data: {
        p: p
      },
      type: 'post',
      dataType: 'json',
      beforeSend: function() {

      },
      success: function(r) {
        if (c != null)
          (e ? eval("(" + c + "(r,e));") : eval("(" + c + "(r));"));
      }
    });
  }
}

$(document).on('click', '.addNew', function() {
  sys.customers.addNew($(this));
});

The idea in this example is to call the AJAX method by passing a callback function reference for handling the success response.

If you look at the addNew() method it is working in two ways. With the help of the second parameter, cb, it is determining that the call to this function was for sending an AJAX request or handling its response back.

I'm using eval() in the success callback which I know is evil, so I want to understand how I can do this without using eval()?

I have multiple things running on my page which need AJAX calls and I don't want to rewrite each of them.

I also need this for AJAX's beforeSuccess() method as well.

Body:
The design pattern you're using seems to be a needless abstraction which is causing more problems that it solves.

A better idea would be to have a central 'service' layer which makes the requests to your server side and handles the responses. If you wanted to abstract this further you could have other domain logic abstractions to handle AJAX requests and responses through a single class, however at that stage I would argue you're far better off using an existing framework to do this for you.

A strong recommendation would be to use Angular, given that its MVC pattern is where you're heading anyway.

If you did want to roll your own simplistic version, then a simple example would look something like this:

$(document).on('click', '.addNew', function() {
  services.customers.save($('form').serialize());
});

// in a service layer JS file, far away from UI logic...
let services = {
  customers: {
    save: requestData => {
      $.ajax({
        url: '/to/my/server',
        type: 'post',
        dataType: 'json',
        data: $('form').serialize(),
        success: services.customers.renderUi
      });
    },
    renderCustomerUi: customerData => {
      // optional: extract the UI update logic to your UI layer and pass in the callback as an argument
      if (customerData.status) {
        $('.customers-list').append('<li>' + customerData.customer.name + '</li>');
      }
    }
  }
}


问:
How to use the same random number generator among different C++ files
I am running EDAC algorithms in my main.cpp file. So I linked it with hamming.cpp, hadamard.cpp and reedsolomon.cpp. To test the performance of these algorithms, I am generating random numbers in each file separately. So in each file, this code is at the top:

```<code>/**
 * Random number generator functionality
 **/
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);

std::uniform_int_distribution<> dist{1, 2000000};
</code>```

Of course, we get a duplicate symbol error. So I wanted to dirty fix this at first by just changing the names of all the variables slighty, but essentially I'd have a lot of duplicate code.

I'm aware of header files and I am using them for all my .cpp files. However as far as I understand, you only use header files to declare functions and classes so the compiler knows what it is going to come across beforehand.

I also tried putting this piece of code in a randomnrgen.cpp file and then adding

```<code>#include randomnrgen.cpp
</code>```

above each of the files that needed it, but that gave me the same duplicate errors. I am using the header guard trick by the way:

```<code>#ifndef INCLUDE_GUARD_H
#define INCLUDE_GUARD_H

#include "hamming.h"

#endif
</code>```

So I was wondering if there is an elegant alternative solution to my dirty fix proposal? I need to access the "dist()" function with input "eng" in all of my files, so I need access to them but only want to declare them somewhere once.

答:
It is okay to have global random number generator.

See:

Using same random number generator across multiple functions,

RNGs and global variable avoidance.

And if you are looking for how to do it:

How do I use extern to share variables between source files?

Body:
I am running EDAC algorithms in my main.cpp file. So I linked it with hamming.cpp, hadamard.cpp and reedsolomon.cpp. To test the performance of these algorithms, I am generating random numbers in each file separately. So in each file, this code is at the top:

/**
 * Random number generator functionality
 **/
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);

std::uniform_int_distribution<> dist{1, 2000000};

Of course, we get a duplicate symbol error. So I wanted to dirty fix this at first by just changing the names of all the variables slighty, but essentially I'd have a lot of duplicate code.

I'm aware of header files and I am using them for all my .cpp files. However as far as I understand, you only use header files to declare functions and classes so the compiler knows what it is going to come across beforehand.

I also tried putting this piece of code in a randomnrgen.cpp file and then adding

#include randomnrgen.cpp

above each of the files that needed it, but that gave me the same duplicate errors. I am using the header guard trick by the way:

#ifndef INCLUDE_GUARD_H
#define INCLUDE_GUARD_H

#include "hamming.h"

#endif

So I was wondering if there is an elegant alternative solution to my dirty fix proposal? I need to access the "dist()" function with input "eng" in all of my files, so I need access to them but only want to declare them somewhere once.


问:
cant start react native project using npm/expo start
following react-native docs to make an android app after using

```<code>npm install -g expo-cli
</code>```

command and in the same project file using

```<code>expo init first-proj

cd first-proj
</code>```

everything is good until I do npm start it's going to give me an error

```<code>> first-proj@1.0.0 start
> expo start

Starting project at D:\react\react projects\reacttest\first-proj
Unable to find expo in this project - have you run yarn / npm install yet?
</code>```

and so I downloaded npm by using npm install but now it's giving another problem.
when I type npm start it shows this in the terminal of vs code

```<code>> first-proj@1.0.0 start
> expo start

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module './util/resolveCommand'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\lib\parse.js
- D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\expo\bin\cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\lib\parse.js:5:24)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\cross-spawn\\lib\\parse.js',
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\cross-spawn\\index.js',
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\expo\\bin\\cli.js'
  ]
}
</code>```

And if I do expo start instead it gives

```<code>Starting project at D:\react\react projects\reacttest\first-proj
Developer tools running on http://localhost:19002
Cannot find module './lib/source-map-generator'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\utils.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\compiler.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\lib\braces.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\micromatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\sane\src\common.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\lib\WatchmanWatcher.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\node-haste\DependencyGraph.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\Bundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\IncrementalBundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\metro\importMetroFromProject.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\HermesBundler.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\MetroDevServer.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\start\startDevServerAsync.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\internal.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\build\exp.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
Error: Cannot find module './lib/source-map-generator'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\utils.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\compiler.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\lib\braces.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\micromatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\sane\src\common.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\lib\WatchmanWatcher.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\node-haste\DependencyGraph.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\Bundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\IncrementalBundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\metro\importMetroFromProject.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\HermesBundler.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\MetroDevServer.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\start\startDevServerAsync.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\internal.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\build\exp.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js:6:30)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
</code>```

I need to use npm start so I can test the app on my real phone with the expo app. so what to do?

答:
Check to see if there is a node_modules/ folder in your project.
The modules might not have been installed.

You need to run

cd first-proj
npm install
```
<p>and then run</p>
```expo start
```

in the same folder (first-proj).

It should work after this.

Body:
following react-native docs to make an android app after using

npm install -g expo-cli

command and in the same project file using

expo init first-proj

cd first-proj

everything is good until I do npm start it's going to give me an error

> first-proj@1.0.0 start
> expo start

Starting project at D:\react\react projects\reacttest\first-proj
Unable to find expo in this project - have you run yarn / npm install yet?

and so I downloaded npm by using npm install but now it's giving another problem.
when I type npm start it shows this in the terminal of vs code

> first-proj@1.0.0 start
> expo start

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module './util/resolveCommand'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\lib\parse.js
- D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\expo\bin\cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\react\react projects\reacttest\first-proj\node_modules\cross-spawn\lib\parse.js:5:24)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\cross-spawn\\lib\\parse.js',
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\cross-spawn\\index.js',
    'D:\\react\\react projects\\reacttest\\first-proj\\node_modules\\expo\\bin\\cli.js'
  ]
}

And if I do expo start instead it gives

Starting project at D:\react\react projects\reacttest\first-proj
Developer tools running on http://localhost:19002
Cannot find module './lib/source-map-generator'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\utils.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\compiler.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\lib\braces.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\micromatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\sane\src\common.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\lib\WatchmanWatcher.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\node-haste\DependencyGraph.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\Bundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\IncrementalBundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\metro\importMetroFromProject.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\HermesBundler.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\MetroDevServer.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\start\startDevServerAsync.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\internal.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\build\exp.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
Error: Cannot find module './lib/source-map-generator'
Require stack:
- D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\utils.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\lib\compiler.js
- D:\react\react projects\reacttest\first-proj\node_modules\snapdragon\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\lib\braces.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\braces\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\node_modules\micromatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\anymatch\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\sane\src\common.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\lib\WatchmanWatcher.js
- D:\react\react projects\reacttest\first-proj\node_modules\jest-haste-map\build\index.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\node-haste\DependencyGraph.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\Bundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\IncrementalBundler.js
- D:\react\react projects\reacttest\first-proj\node_modules\metro\src\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\metro\importMetroFromProject.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\HermesBundler.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\@expo\dev-server\build\MetroDevServer.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\start\startDevServerAsync.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\internal.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\node_modules\xdl\build\index.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\build\exp.js
- C:\Users\abdal\AppData\Roaming\npm\node_modules\expo-cli\bin\expo.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\react\react projects\reacttest\first-proj\node_modules\source-map\source-map.js:6:30)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)

I need to use npm start so I can test the app on my real phone with the expo app. so what to do?

Body:
Check to see if there is a node_modules/ folder in your project.
The modules might not have been installed.

You need to run

cd first-proj
npm install

and then run

expo start

in the same folder (first-proj).

It should work after this.


问:
Use a different fixed type for interfaces defined in the base class for subclasses
I have a BaseList container that takes BaseItem's as items. I then derive a new list CustomList and I want it to hold CustomItem's.

How to I type methods in BaseList many methods to accept BaseItem. And also tell it to use CustomItem the derived list CustomList?

Here is the code I have so far:

from __future__ import annotations
from typing import List, Union, Iterator, overload

class BaseItem:
    pass

class BaseList:
    def __init__(self) -> None:
        self.items: List[BaseItem] = []

    def add_item(self, item: BaseItem) -> None:
        self.items.append(item)

    def __iter__(self) -> Iterator[BaseItem]:
        return iter(self.items)

class CustomItem(BaseItem):
    def __init__(self, value: int) -> None:
        self.value: int = value

class CustomList(BaseList):
    def sum(self) -> int:
        # mypy error: "BaseItem" has no attribute "value"
        return sum(item.value for item in self)
```
<pre class="lang-py prettyprint-override"><code>
# no error, but it should say: incompatible type; expected "CustomItem".
CustomList().add_item(BaseItem())

container = CustomList()
container.add_item(CustomItem(10))
for item in container:
    # mypy error: `"BaseItem" has no attribute "value"`
    print(item.value)
</code>```

Question

How can I define a type A and say in BaseList it should resolve to BaseItem and in CustomList it should resolve to CustomItem?

Tried so far

I tried using TypeVar with the bounds attribute, but I didn't seem to get it work.

Constraints

I have more than just one subclass so I don't want to re-implement all these methods with different types. Also there are many more of these methods with similar problems, like __contains__, __getitem__, class specific items, etc.

The type hints should be also resolved by PyCharm, as the goal is to get correct code-complete there.

答:
Make BaseList class Generic:</p>
```<code>class BaseItem:
    pass

T = TypeVar('T', bound=BaseItem)

class BaseList(Generic[T]):

    def __init__(self) -> None:
        self.items: List[T] = []

    def add_item(self, item: T) -> None:
        self.items.append(item)

    def __iter__(self) -> Iterator[T]:
        return iter(self.items)

class CustomItem(BaseItem):

    def __init__(self, value: int) -> None:
        self.value: int = value

class CustomList(BaseList[CustomItem]):

    def sum(self) -> int:
        reveal_type(self.items)  # Mypy: Revealed type is "builtins.list[CustomItem*]"
        return sum(item.value for item in self)
</code>```

Body:
I have a BaseList container that takes BaseItem's as items. I then derive a new list CustomList and I want it to hold CustomItem's.

How to I type methods in BaseList many methods to accept BaseItem. And also tell it to use CustomItem the derived list CustomList?

Here is the code I have so far:

from __future__ import annotations
from typing import List, Union, Iterator, overload

class BaseItem:
    pass

class BaseList:
    def __init__(self) -> None:
        self.items: List[BaseItem] = []

    def add_item(self, item: BaseItem) -> None:
        self.items.append(item)

    def __iter__(self) -> Iterator[BaseItem]:
        return iter(self.items)

class CustomItem(BaseItem):
    def __init__(self, value: int) -> None:
        self.value: int = value

class CustomList(BaseList):
    def sum(self) -> int:
        # mypy error: "BaseItem" has no attribute "value"
        return sum(item.value for item in self)

# no error, but it should say: incompatible type; expected "CustomItem".
CustomList().add_item(BaseItem())

container = CustomList()
container.add_item(CustomItem(10))
for item in container:
    # mypy error: `"BaseItem" has no attribute "value"`
    print(item.value)

Question

How can I define a type A and say in BaseList it should resolve to BaseItem and in CustomList it should resolve to CustomItem?

Tried so far

I tried using TypeVar with the bounds attribute, but I didn't seem to get it work.

Constraints

I have more than just one subclass so I don't want to re-implement all these methods with different types. Also there are many more of these methods with similar problems, like __contains__, __getitem__, class specific items, etc.

The type hints should be also resolved by PyCharm, as the goal is to get correct code-complete there.

Body:
Make BaseList class Generic:

class BaseItem:
    pass

T = TypeVar('T', bound=BaseItem)

class BaseList(Generic[T]):

    def __init__(self) -> None:
        self.items: List[T] = []

    def add_item(self, item: T) -> None:
        self.items.append(item)

    def __iter__(self) -> Iterator[T]:
        return iter(self.items)

class CustomItem(BaseItem):

    def __init__(self, value: int) -> None:
        self.value: int = value

class CustomList(BaseList[CustomItem]):

    def sum(self) -> int:
        reveal_type(self.items)  # Mypy: Revealed type is "builtins.list[CustomItem*]"
        return sum(item.value for item in self)


问:
Are there limits on the reasonable amount of HTML that browsers can handle before they start to slow down in regards to page rendering?
I am working to troubleshoot an issue with my Django formsets implementation.  After working with a consultant for a couple hours today...we think it might be related to the amount of HTML that gets generated based on the number of records the formset is processing.  Based on 18,000 lines of HTML...the page takes about 15 seconds to load.  The same page with fewer records loads much more quickly.

We've explored the query thing...and have exhaustively looked at performance metrics on the server side and can't seen anything glaringly sticking out that would be contributing to the perceived slow rendering of the page in the browser.

Has anyone else come to this conclusion with their formsets?  If so, what potential alternatives are there to resolving the slow page rendering issue?  Formsets are great...but it would seem that the browsers have trouble rendering the records when they hit a certain amount?

Thanks in advance for any thoughts.

答: How many HTML elements can "modern" browsers "handle" at once? Well think  you need to read this post that i found on stack, this might give you a better understanding and answer to your question! Hope it helps ! How many HTML elements can "modern" browsers "handle" at once?</p>


问:
How to limit resources known to SLURM?
Say I have a cluster with 1 node and 36 CPU cores, but I want SLURM to manage and allocate only 20 of these cores. Is there a way to configure SLURM so it's 'world' only consists of this subset of the total CPUs?

Note this is different from setting limits to a particular job. I want a situation where in the example above if job1 requests 20 cpus, and job2 requests 5, SLURM waits for job1 to finish before allocating job2 (as opposed to just starting job2 right away because there are 36 cpus total).

答:
So after messing around a bit, this seemed to work. Posting here in case anyone else ever has the same question.

Happy know if there are any downsides to this approach.

I edited slrum.conf to specify a lower CPU count for my node, and adjusted the Sockets : CoresPerSocket : ThreadsPerCore accordingly.

NodeName=myNode CPUs=20 RealMemory=450000 Sockets=2 CoresPerSocket=5 ThreadsPerCore=2 State=UNKNOWN

Title: How to limit resources known to SLURM?


问:
Zend framework module routes - accessing actions
I have modules as follow:

```<code>modules
    default
        controllers
            IndexController

    user
        controllers
            IndexController
</code>```

If I put an action in the default IndexController called testAction() I can run that action at /index/test or default/index/test as expected.

If I put the same action in user IndexController and try and access it at user/index/test this fails to run testAction(). Instead it run indexAction() that is in the same controller. Why does it do that?

Extra info: I have an ini file located at application/configs/application.ini and the contents of it are:

```<code>[production]
phpSettings.date.timezone = 'Europe/Belfast'
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"

;;namespaces

;site-wide namespaces
autoloaderNamespaces[] = "Plugin_"
autoloaderNamespaces[] = "Helper_"

;form validators
autoloaderNamespaces[] = "Validate_"

;modules
autoloaderNamespaces[] = "Users_"
autoloaderNamespaces[] = "Admin_"

;storage adapters
resources.db.adapter = mysqli
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = vi

;modules
;resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules = ""

;layouts
resources.layout.layoutPath = APPLICATION_PATH "/layouts"
resources.layout.layout = master

;routes

; /home route
resources.router.routes.home.route = /home
resources.router.routes.home.defaults.module = default
resources.router.routes.home.defaults.controller = index
resources.router.routes.home.defaults.action = index

; /content route
resources.router.routes.static-content.route = /content/:page
resources.router.routes.static-content.defaults.module = default
resources.router.routes.static-content.defaults.controller = static-content
resources.router.routes.static-content.defaults.action = display

;resources.frontController.plugins.CheckHasAccess = "Plugin_AccessCheck"

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1

[development : testing]
</code>```

I am running the application in development environment.

答:
```<code>resources.modules = ""
</code>```

<p>should be </p>

```<code>resources.modules = []
</code>```

Body:
I have modules as follow:

modules
    default
        controllers
            IndexController

    user
        controllers
            IndexController

If I put an action in the default IndexController called testAction() I can run that action at /index/test or default/index/test as expected.

If I put the same action in user IndexController and try and access it at user/index/test this fails to run testAction(). Instead it run indexAction() that is in the same controller. Why does it do that?

Extra info: I have an ini file located at application/configs/application.ini and the contents of it are:

[production]
phpSettings.date.timezone = 'Europe/Belfast'
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"

;;namespaces

;site-wide namespaces
autoloaderNamespaces[] = "Plugin_"
autoloaderNamespaces[] = "Helper_"

;form validators
autoloaderNamespaces[] = "Validate_"

;modules
autoloaderNamespaces[] = "Users_"
autoloaderNamespaces[] = "Admin_"

;storage adapters
resources.db.adapter = mysqli
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = vi

;modules
;resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.modules = ""

;layouts
resources.layout.layoutPath = APPLICATION_PATH "/layouts"
resources.layout.layout = master

;routes

; /home route
resources.router.routes.home.route = /home
resources.router.routes.home.defaults.module = default
resources.router.routes.home.defaults.controller = index
resources.router.routes.home.defaults.action = index

; /content route
resources.router.routes.static-content.route = /content/:page
resources.router.routes.static-content.defaults.module = default
resources.router.routes.static-content.defaults.controller = static-content
resources.router.routes.static-content.defaults.action = display

;resources.frontController.plugins.CheckHasAccess = "Plugin_AccessCheck"

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1

[development : testing]

I am running the application in development environment.

Body:
resources.modules = ""

should be

resources.modules = []


Title: svg path image Colour

Body:
What you have there is a mask or "stencil" path. Just create a filled rect and place it under (in z-order) the mask.

<svg xmlns="http://www.w3.org/2000/svg" width="110" height="110" viewBox="0 0 105 105">
    <rect x="0.2" y="0.2" width="104.5" height="105" style="fill: #21b296;"/>
    <path style="fill: white;" d="M473.85,66a1.29,1.29,0,0,1-.05-.24c0-.18,0-.36,0-.53V24a2.08,2.08,0,0,1,.06-.74,1.54,1.54,0,0,1,.3,0H578a2.79,2.79,0,0,1,.75.05c0,.1,0,.19,0,.28s0,.29,0,.44V81.33c0,.23,0,.45,0,.7a2.37,2.37,0,0,1-.31.06h-5.31l-.24,0-.22-.48Q569.49,74,566.3,66.5c-.07-.17-.15-.33-.22-.47-.53-.06-7.43-.06-7.88,0-.42.91-.8,1.86-1.2,2.81s-.8,1.89-1.2,2.83l-1.2,2.84-1.2,2.84c-.39.94-.8,1.89-1.2,2.83S551.41,82.08,551,83s-.78,1.89-1.24,2.9c-.61-1.4-1.16-2.72-1.71-4l-1.68-4-1.67-4L543,70l-1.68-4A2.09,2.09,0,0,0,541,66h-7.34l-.15,0c-.19.1-.21.29-.28.45L531.5,70.6l-7.2,17.07c0,.12-.11.23-.15.34s-.11-.09-.11-.14,0-.29,0-.43V66.66A1.6,1.6,0,0,0,524,66l-.47,0c-3.52,0-6.33,0-6.7.05-.13.16-.08.34-.08.52l.06,4.69.09,8.62a5.45,5.45,0,0,1,0,.56,1,1,0,0,1-.36-.39l-4.34-5.92-5.63-7.68-.15-.2a.5.5,0,0,0-.51-.26,4.51,4.51,0,0,1-.52,0H474.53A2.64,2.64,0,0,1,473.85,66Zm0,6.3q0,24.19,0,48.38a1.16,1.16,0,0,0,0,.18,1.52,1.52,0,0,0,.73.07H578c.15,0,.31,0,.47,0s.19,0,.31-.07V88.35c0-.15,0-.29,0-.44a1.64,1.64,0,0,0-.07-.28h-3.25a.7.7,0,0,0-.17.06c.06.14.1.27.16.41.41,1,.83,2,1.25,3,.05.13.15.25.09.42a1.81,1.81,0,0,1-.61.06H569.7a2.24,2.24,0,0,1-.31-.05l-.06-.07a.36.36,0,0,1,0-.09l-.06-.13q-3.4-8.86-6.83-17.72l-.12-.32a.08.08,0,0,0,0,0l0-.09s0,0,0,0h0s-.07,0-.07.06q-1.67,4.38-3.31,8.76a.38.38,0,0,0,0,.15,1.18,1.18,0,0,0,.56,0c1,0,1.94,0,2.91,0l.56,0a1.73,1.73,0,0,1,.12.2c.59,1.68,1.17,3.37,1.76,5.06a1.23,1.23,0,0,1,0,.19,1,1,0,0,1-.57.06H556.5c-.56,1.32-1,2.65-1.58,4a1.7,1.7,0,0,1-.28,0H544.9a1.7,1.7,0,0,1-.28,0c-.07-.16-.15-.32-.21-.48-.39-1-.78-2-1.18-3-.06-.16-.08-.35-.25-.45-.7,0-10.8,0-11.24,0-.07.16-.15.33-.22.51-.38,1-.76,2-1.15,3-.07.16-.09.35-.29.48l-.65,0H517.87c-.88,0-.68.07-1.16-.59l-8.28-11.27-1.68-2.28c-.05-.07-.09-.18-.25-.15a9.26,9.26,0,0,0,0,1.29c0,.42,0,.84,0,1.26s0,.87,0,1.31,0,.87,0,1.31,0,.87,0,1.3,0,.84,0,1.26,0,.87,0,1.31l0,1.31c0,.43,0,.87,0,1.3s0,.84,0,1.26a8.5,8.5,0,0,1,0,1.33,4.07,4.07,0,0,1-.47,0h-6.3a.75.75,0,0,1-.48-.09,2.45,2.45,0,0,1,0-.61V72.93c0-.16,0-.32,0-.49s0-.21,0-.32a1.5,1.5,0,0,0-.69-.06H474.11a1.87,1.87,0,0,0-.25,0A.65.65,0,0,0,473.81,72.25Zm9.64,19.3-.54,0c0-.11,0-.2-.05-.3s0-.22,0-.33c0-5.33,0-10.65,0-16a1.5,1.5,0,0,1,0-.56,1,1,0,0,1,.53-.07c2.06,0,4.13,0,6.19,0a.91.91,0,0,1,.53.08c0,.11,0,.24,0,.36.07,4.11,0,16.25-.05,16.76C489.66,91.57,487.27,91.59,483.45,91.55Zm28.94,32.08H474.13a2.3,2.3,0,0,0-.28.06,11,11,0,0,0,0,2.56l.71,0h38.2a2.3,2.3,0,0,0,.28-.06,16.83,16.83,0,0,0,0-2.56Zm24.79-50.24c-.54,1.41-1.07,2.82-1.6,4.24s-1,2.62-1.48,3.92c-.05.13-.14.26-.07.41.4.05,5.51.09,6.51,0a2.11,2.11,0,0,0,.28,0c-.05-.15-.09-.29-.14-.43-1.39-3.81-3.1-8.25-3.3-8.58A3.46,3.46,0,0,0,537.18,73.39Zm35.06,54c-.14-.2-.3-.39-.43-.6a1.77,1.77,0,0,1-.36-.59l.38-.27a1.9,1.9,0,0,0,.63-.75,2.08,2.08,0,0,0-1.39-2.9,4.21,4.21,0,0,0-1.17-.19c-.89,0-1.77,0-2.66,0a1.43,1.43,0,0,0-.28.07c0,.09,0,.15,0,.21,0,1.79,0,3.59,0,5.38a2.07,2.07,0,0,0,0,.3c.3,0,.57,0,.85,0a1.56,1.56,0,0,0,.8-.08c.09-.49,0-1,.08-1.44.85-.17.95-.13,1.39.48l.38.52.4.52h1.52l.28,0Zm-3.52-4a2,2,0,0,1,.28,0,7.22,7.22,0,0,1,.93,0,.93.93,0,0,1,.9.6.87.87,0,0,1-.73,1.17,3.69,3.69,0,0,1-1.37,0A6,6,0,0,1,568.72,123.47Zm-50.33.88a3.07,3.07,0,0,1-.85.06h-.78a2.69,2.69,0,0,1-.84-.06,5.42,5.42,0,0,1,0-1.06,5.76,5.76,0,0,0,0-1.1,4.36,4.36,0,0,0-1.69,0c0,.46,0,1,0,1.43s0,1,0,1.45,0,1,0,1.5a13.61,13.61,0,0,0,0,1.43,4.15,4.15,0,0,0,1.69,0c0-.35,0-.72,0-1.09a5.9,5.9,0,0,1,0-1.11,2.76,2.76,0,0,1,.85,0q.39,0,.78,0a2.28,2.28,0,0,1,.82.06,6,6,0,0,1,0,1.11,6.71,6.71,0,0,0,0,1.1,4,4,0,0,0,1.66,0,2.4,2.4,0,0,0,0-.28c0-1.75,0-3.51,0-5.27a2.19,2.19,0,0,0,0-.27,4.92,4.92,0,0,0-1.67,0C518.38,122.92,518.46,123.63,518.39,124.35Zm29,3.66c0-.14,0-.3,0-.46v-1.4c0-.13,0-.26.1-.36a11.68,11.68,0,0,1,2.38,0,.76.76,0,0,1,.06.47c0,.48,0,1,0,1.45a1.61,1.61,0,0,0,.06.35,9.72,9.72,0,0,0,1.62,0,1.07,1.07,0,0,0,0-.21c0-1.83,0-3.65,0-5.47a.59.59,0,0,0-.05-.19,1.24,1.24,0,0,0-.57-.06,4.51,4.51,0,0,0-.52,0c-.18,0-.38-.05-.57.1,0,.13,0,.27,0,.41,0,.47,0,.94,0,1.41a2.21,2.21,0,0,1-.05.33,7.2,7.2,0,0,1-1.22,0,3.54,3.54,0,0,1-1.25-.08c0-.17,0-.33,0-.49v-1.35c0-.11,0-.21,0-.34-.48,0-.93,0-1.38,0a1.07,1.07,0,0,0-.27.07c-.07.62-.05,5.46,0,5.86A5.23,5.23,0,0,0,547.4,128Zm-22-3.54c-.57,0-1.14,0-1.71,0-.16,0-.32,0-.46-.11a2.07,2.07,0,0,1,.06-1l.52,0h2.08a.81.81,0,0,0,.52-.09,4,4,0,0,0,0-1.14,1.6,1.6,0,0,0-.27,0h-4.32a1.59,1.59,0,0,0-.3.06c0,.09,0,.15,0,.21,0,1.81,0,3.62,0,5.42a1,1,0,0,0,0,.24,1.6,1.6,0,0,0,.27,0h4.43a1.77,1.77,0,0,0,.3-.06,3.35,3.35,0,0,0-.05-1.18h-2.83l-.41,0a2.91,2.91,0,0,1,0-1.1l.53,0h1.82a.47.47,0,0,0,.41-.12,5,5,0,0,0,0-1A1.94,1.94,0,0,0,525.44,124.47Zm50,1.3a.81.81,0,0,1,.52-.1c.61,0,1.22,0,1.82,0,.14,0,.27,0,.42,0a2.17,2.17,0,0,0,0-1.13l-.53,0H576a.89.89,0,0,1-.51-.07,1.8,1.8,0,0,1,0-1,1,1,0,0,1,.5-.06h2.19a.57.57,0,0,0,.47-.12c0-.16,0-.35,0-.55a1.4,1.4,0,0,0,0-.57l-.38,0h-4.06c-.15,0-.32,0-.44.11s0,.09,0,.13v5.47a.79.79,0,0,0,.06.22c.42,0,3.57.08,4.65,0a2,2,0,0,0,.32,0,3.34,3.34,0,0,0,0-1.18c-.55,0-1.09,0-1.62,0a13,13,0,0,1-1.64,0A3.23,3.23,0,0,1,575.47,125.77Zm-41.35,2c-.15-.33-.3-.65-.46-1-.66-1.4-1.31-2.8-2-4.21a.86.86,0,0,0-.29-.45h-1.63c-.06.12-.14.23-.19.34-.17.36-.34.71-.5,1.07-.63,1.34-1.27,2.68-1.89,4-.07.15-.2.3-.14.48a5.62,5.62,0,0,0,1.67,0,12,12,0,0,1,.55-1.07l.22,0c.71,0,1.42,0,2.13,0a.46.46,0,0,1,.5.33c.1.27.23.53.34.79a7.32,7.32,0,0,0,1.75,0A2.13,2.13,0,0,0,534.12,127.77Zm-2.74-2.12a.65.65,0,0,1-.17.08,6.8,6.8,0,0,1-1.42,0,8.52,8.52,0,0,1,.57-1.46c0-.13.06-.29.23-.36A8.33,8.33,0,0,1,531.38,125.65Zm34.83,2.2c-.35-.85-2.52-5.39-2.73-5.69a6.19,6.19,0,0,0-1.73,0l-2.63,5.61a1.42,1.42,0,0,0-.07.22,4.91,4.91,0,0,0,1.71,0c.23-.33.28-.75.54-1.06a19.91,19.91,0,0,1,2.68,0c.27.32.29.77.57,1.09a6.6,6.6,0,0,0,1.69,0A1.13,1.13,0,0,0,566.21,127.85Zm-2.79-2.21c-.13.15-.32.09-.48.1a5.42,5.42,0,0,1-.57,0,.85.85,0,0,1-.53-.09,3.88,3.88,0,0,1,.34-.89c.12-.29.25-.59.41-.94A7.06,7.06,0,0,1,563.42,125.64ZM558,122.4a4,4,0,0,0-2.32-.36,3.52,3.52,0,0,0-1.59.55,2.89,2.89,0,0,0-1.37,2.62,3,3,0,0,0,2.24,2.84,4.38,4.38,0,0,0,2.46,0,2.92,2.92,0,0,0,1.27-.72,1.35,1.35,0,0,0,.18-.25l-.51-.44c-.18-.14-.32-.34-.54-.4l-.08,0-.2.15a1.94,1.94,0,0,1-1.49.42,1.62,1.62,0,0,1-1.38-.89,1.75,1.75,0,0,1-.16-1.23,1.69,1.69,0,0,1,1.65-1.37,1.94,1.94,0,0,1,1.3.38l.37.27a7,7,0,0,0,1-.91A2.24,2.24,0,0,0,558,122.4ZM541.23,124v3.49a.81.81,0,0,0,.1.55,3.44,3.44,0,0,0,.79,0,1.64,1.64,0,0,0,.84-.1c0-.18,0-.37,0-.57,0-1.13,0-2.25,0-3.38a.89.89,0,0,1,.09-.59c.12,0,.26,0,.39,0h1.09a2.71,2.71,0,0,0,.37,0c0-.29,0-.57,0-.84a3.16,3.16,0,0,0,0-.32.71.71,0,0,0-.47-.08,47.82,47.82,0,0,0-5.1.07,2.79,2.79,0,0,0,0,1,.48.48,0,0,0,.09.21c.6,0,1.19,0,1.84,0C541.22,123.68,541.23,123.86,541.23,124Zm-2.1,2.79h-2.29a.21.21,0,0,1-.21-.18,3.24,3.24,0,0,1,0-.44v-3.48a1.14,1.14,0,0,0-.07-.56,9.66,9.66,0,0,0-1.32,0,2,2,0,0,0-.28,0c-.09.41-.11,2.83-.07,5.48,0,.13,0,.25,0,.39a1.31,1.31,0,0,0,.22.05h4.37a.46.46,0,0,0,.16-.06,1.13,1.13,0,0,0,0-.18v-.94A1.17,1.17,0,0,0,539.13,126.82Z" transform="translate(-473.79 -23.23)">
    </path>
</svg>

Note that the rect is offset by 0.2 and the width is slightly smaller than the full 105. This is to avoid a thin "frame" appearing at the perimeter. You may want to play with these values to achieve the look you want.


问:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
I am getting this error when I try to send mail using the JavaMail API:

```<code>javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted
</code>```

How can I fix this?

答: Change the settings in Google like this:

Body:
I am getting this error when I try to send mail using the JavaMail API:

javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted

How can I fix this?


问:
javascript : css file path problem using nunjucks
enter image description here

I set the path appropriately, but there is an error.
It comes out well when you proceed with normal html, not nunjucks.

答:
Put your stylesheet in block

```<code>{% block css %}
<link rel="stylesheet" href="app.css" />
{% endblock %}
</code>```

for more information check the documentation  block section

Body:
Put your stylesheet in block

{% block css %}
<link rel="stylesheet" href="app.css" />
{% endblock %}

for more information check the documentation  block section


问:
hide chromeDriver console in python
I'm using chrome driver in Selenium to open chrome , log into a router, press some buttons ,upload configuration etc. all code is written in Python.

here is the part of the code to obtain the driver:

```<code>chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory":  self.user_local}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.experimental_options.
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)

return driver
</code>```

when i fire up my app, i get a chromedriver.exe console (a black window) followed by a chrome window opened and all my requests are done.

My question: is there a way in python to hide the console window ?

(as you can see i'm also re-sizing the chrome window ,my preference would be doing things in a way the user wont notice anything happening on screen)

thanks
Sivan

答:
New easy solution! (in selenium4)

I needed that too, so I implemented and commited this feature on GitHub as part of selenium4 release.
We no longer need to edit the selenium library for this.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows

# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
chrome_service.creationflags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)
</code>```

Now, command-prompt window does not open up. This is especially useful when you have a GUI desktop app which is responsible for opening selenium browser.

Also, note that we only need to do this in Windows.

Title: hide chromeDriver console in python

Body:
I'm using chrome driver in Selenium to open chrome , log into a router, press some buttons ,upload configuration etc. all code is written in Python.

here is the part of the code to obtain the driver:

chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory":  self.user_local}
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.experimental_options.
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
driver.set_window_position(0, 0)
driver.set_window_size(0, 0)

return driver

when i fire up my app, i get a chromedriver.exe console (a black window) followed by a chrome window opened and all my requests are done.

My question: is there a way in python to hide the console window ?

(as you can see i'm also re-sizing the chrome window ,my preference would be doing things in a way the user wont notice anything happening on screen)

thanks
Sivan

Body:
New easy solution! (in selenium4)

I needed that too, so I implemented and commited this feature on GitHub as part of selenium4 release.
We no longer need to edit the selenium library for this.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows

# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
chrome_service.creationflags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)

Now, command-prompt window does not open up. This is especially useful when you have a GUI desktop app which is responsible for opening selenium browser.

Also, note that we only need to do this in Windows.


问:
Where should I put the complex queries using the Repository Pattern?
I have an application in which I use Entity Framework, and I have a class called BaseRepository<T> with a few basic CRUD methods, such as (Get, GetAll, Update, Delete, Insert), and from this class I generate my specific repositories, such like BaseRepository <Products>, BaseRepository<People>, BaseRepository<Countries> and many more.

The problem is that, when I have a complex logic in the service, that involves making joins of several tables and that does not return an entity, but an object that is handled in the service (it is neither a DB entity nor a DTO), I find that repositories don't help me much with just basic CRUD operations.

Where should I put this query complex? in which of the repositories should it be? How do I join these repositories? The problem is that I see that the repositories handle a single entity, what should I do in this case? I've been doing some research and read that returning IQueryable<T> is bad practice, so I rule out that possibility of sending IQueryable<T> of the tables I'm going to join the service and do it there.

I've researched and found no clear answer. I would like to know how and where these complex queries are organized, since I also want to respect the responsibility of each repository with its respective entity.

答:
I would like to know how and where these complex queries are organized, since I also want to respect the responsibility of each repository with its respective entity.

The complex queries are the responsibility of the code that is requesting the data, not the responsibility of the repository.  The single responsibility of the repository is to provide access to the data, not to provide every possible request shape that may be needed in any use case. You really want to write methods in your repositories like:

```<code>customerRepo.GetCustomerWithLastTenOrdersAndSupportCasesAsDTO()
</code>```

or

```<code>customerRepo.GetCustomerForCustomerSupportHomePage()
</code>```

Of course not. So  your repository provides a property of type IQueryable<T> or DbSet<T> which can be used as a starting point for consumers to add whatever queries they need.

I've been doing some research and read that returning IQueryable is bad practice

Don't beleive everything you read.  There's really not a good alternative to exposing IQueryable<T> from your repository.  And once you digest that, there's not much of a reason to have any repository type other than your DbContext subtype.

Body:
I would like to know how and where these complex queries are organized, since I also want to respect the responsibility of each repository with its respective entity.

The complex queries are the responsibility of the code that is requesting the data, not the responsibility of the repository.  The single responsibility of the repository is to provide access to the data, not to provide every possible request shape that may be needed in any use case. You really want to write methods in your repositories like:

customerRepo.GetCustomerWithLastTenOrdersAndSupportCasesAsDTO()

or

customerRepo.GetCustomerForCustomerSupportHomePage()

Of course not. So  your repository provides a property of type IQueryable<T> or DbSet<T> which can be used as a starting point for consumers to add whatever queries they need.

I've been doing some research and read that returning IQueryable is bad practice

Don't beleive everything you read.  There's really not a good alternative to exposing IQueryable<T> from your repository.  And once you digest that, there's not much of a reason to have any repository type other than your DbContext subtype.


问:
I am using react-query and I have 5 tabs I want to hit different url while navigating different tabs?
I used Tabs and each tab have different url to be hit so I created a different component and passed the value as props and in react-query I used it as query keys but it is no working please help me to debug this code as I am very new to react-query and http request is new to me as well.</p>
```<code><div className='card-body py-3'>
                <ul className='nav nav-tabs nav-line-tabs mb-5 fs-6'>
                  <li className='nav-item'>
                    <a className='nav-link active' data-bs-toggle='tab' href='#kt_tab_pane_1'>
                      Pending
                    </a>
                  </li>
                  <li className='nav-item'>
                    <a className='nav-link' data-bs-toggle='tab' href='#kt_tab_pane_2'>
                      Verified
                    </a>
                  <li className='nav-item'>
                    <a className='nav-link' data-bs-toggle='tab' href='#kt_tab_pane_3'>
                      Update_rejected
                    </a>
                  </li>
                </ul>
                <div className='tab-content' id='myTabContent'>
                  <div className='tab-pane fade active show' id='kt_tab_pane_1' role='tabpanel'>
                    <TravelItem name='pending' />
                  </div>
                  <div className='tab-pane fade' id='kt_tab_pane_6' role='tabpanel'>
                    <TravelItem name='Update_rejected' />
                  </div>
                </div>
              </div>

in Travel item Component I used the query key which passes my name in query Params to the function on api request

      const {data, isLoading, isError, isSuccess, isFetching} = useQuery(
        ['Pending', name],
        travelVerified,
        {
          refetchOnMount: true,
        }
      )
This is my api request where I used dynamic key every time I fetch the data with different name
    export const travelVerified = async ({queryKey}: any) => {
      const [_key, name] = queryKey
      const {data} = await axios.get(`${process.env.REACT_APP_API_URL}/${name}`)
      return data
    }
</code>```

答:
Your react-query code looks fine, I think the problem you are having is that your tabs are only "visually hidden", which means they are always mounted in the DOM. Since react-query relies on mounting components to perform background refetches, you won't get refetches when you change tabs.

To make this work, your tabs need to only mount the current tab via conditional rendering, and when you switch between tabs, the new tab has to be mounted.

A good example is the lazy tabs from Chakra UI: https://chakra-ui.com/docs/disclosure/tabs#lazily-mounting-tab-panels

Body:
I used Tabs and each tab have different url to be hit so I created a different component and passed the value as props and in react-query I used it as query keys but it is no working please help me to debug this code as I am very new to react-query and http request is new to me as well.

                      Pending

                      Verified

                      Update_rejected

                    <TravelItem name='pending' />

                    <TravelItem name='Update_rejected' />

in Travel item Component I used the query key which passes my name in query Params to the function on api request

      const {data, isLoading, isError, isSuccess, isFetching} = useQuery(
        ['Pending', name],
        travelVerified,
        {
          refetchOnMount: true,
        }
      )
This is my api request where I used dynamic key every time I fetch the data with different name
    export const travelVerified = async ({queryKey}: any) => {
      const [_key, name] = queryKey
      const {data} = await axios.get(`${process.env.REACT_APP_API_URL}/${name}`)
      return data
    }


问:
Generate UUID via Envoy Proxy
I am trying to use the following envoy extension to associate an uuid in the x-request-id HTTP header

```<code>type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig
</code>```

This is my working yaml , there is just one api that I have exposed via envoy

```<code>static_resources:
  listeners:
  - name: listener_0
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 10001
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: edge
          http_filters:
          - name: envoy.filters.http.router
          route_config:
            virtual_hosts:
            - name: direct_response_service
              domains: ["*"]
              routes:
              - match:
                  prefix: "/v1/hello"
                route:
                  cluster: cluster1
  clusters:
  - name: cluster1
    connect_timeout: 5s
    load_assignment:
      cluster_name: cluster1
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 8080
</code>```

My question is in the above yaml where do I add the extension of uuid generation

```<code>        typed_config:
          "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig
          pack_trace_reason: false
</code>```

答:
You have to put this extension in the HttpConnectionManager config (under request_id_extension) :

static_resources:
  listeners:
  - address:
      socket_address:
        address: 0.0.0.0
        port_value: 8080
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: AUTO
          stat_prefix: ingress_http
          request_id_extension:
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig
              pack_trace_reason: false
...
```

I have found the information in the documentation here : https://www.envoyproxy.io/docs/envoy/v1.21.0/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#extensions-filters-network-http-connection-manager-v3-httpconnectionmanager (search request_id_extension in the page).

This attribute is defined in the proto file here : https://github.com/envoyproxy/envoy/blob/v1.21.0/api/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#L626-L642.

Title: Generate UUID via Envoy Proxy

Body:
I am trying to use the following envoy extension to associate an uuid in the x-request-id HTTP header

type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig

This is my working yaml , there is just one api that I have exposed via envoy

static_resources:
  listeners:
  - name: listener_0
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 10001
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: edge
          http_filters:
          - name: envoy.filters.http.router
          route_config:
            virtual_hosts:
            - name: direct_response_service
              domains: ["*"]
              routes:
              - match:
                  prefix: "/v1/hello"
                route:
                  cluster: cluster1
  clusters:
  - name: cluster1
    connect_timeout: 5s
    load_assignment:
      cluster_name: cluster1
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 127.0.0.1
                port_value: 8080

My question is in the above yaml where do I add the extension of uuid generation

        typed_config:
          "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig
          pack_trace_reason: false

Body:
You have to put this extension in the HttpConnectionManager config (under request_id_extension) :

static_resources:
  listeners:
  - address:
      socket_address:
        address: 0.0.0.0
        port_value: 8080
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: AUTO
          stat_prefix: ingress_http
          request_id_extension:
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig
              pack_trace_reason: false
...

I have found the information in the documentation here : https://www.envoyproxy.io/docs/envoy/v1.21.0/api-v3/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#extensions-filters-network-http-connection-manager-v3-httpconnectionmanager (search request_id_extension in the page).

This attribute is defined in the proto file here : https://github.com/envoyproxy/envoy/blob/v1.21.0/api/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.proto#L626-L642.


问:
How can I call R script with passing parameters from Python?
I call R script from Python as follows:

```<code> import rpy2.robjects as robjects
 robjects.r.source("C:\\Users\Name\Documents\compbdt.R", encoding="utf-8")
</code>```

And my R script is below:

```<code>main <- function(N) {
  require(data.table)
  data <- fread("C:\\compbdt.csv", sep=",")
  for (i in 1:N) {
    s11 <- data[i, s11]
    s10 <- data[i, s10]
    s01 <- data[i, s01]
    s00 <- data[i, s00]
    r11 <- data[i, r11]
    r10 <- data[i, r10]
    r01 <- data[i, r01]
    r00 <- data[i, r00]

    compbdt(s11, s10, s01, s00, r11, r10, r01, r00)
  }
}

main(N)
</code>```

compbdt is a function as well, I just haven't shown it there.

I need main function to loop N times. N is defined during Python code.

How can I pass N as an argument to call R script properly?

答:
Use the reticulate package. Run your Python code in either an R Markdown file or source it using reticulate::source_python(). This creates a Python object in your R session called py. Access objects created in Python using the extract operator: py$N, for example, would correspond with an object named N created by your Python script.

```<code>library(reticulate)
</code>```
```<code># This is a python block
N = 2
</code>```
```<code># This is an R block
r_N <- py$N
main(r_N)
</code>```

Body:
I call R script from Python as follows:

 import rpy2.robjects as robjects
 robjects.r.source("C:\\Users\Name\Documents\compbdt.R", encoding="utf-8")

And my R script is below:

main <- function(N) {
  require(data.table)
  data <- fread("C:\\compbdt.csv", sep=",")
  for (i in 1:N) {
    s11 <- data[i, s11]
    s10 <- data[i, s10]
    s01 <- data[i, s01]
    s00 <- data[i, s00]
    r11 <- data[i, r11]
    r10 <- data[i, r10]
    r01 <- data[i, r01]
    r00 <- data[i, r00]

    compbdt(s11, s10, s01, s00, r11, r10, r01, r00)
  }
}

main(N)

compbdt is a function as well, I just haven't shown it there.

I need main function to loop N times. N is defined during Python code.

How can I pass N as an argument to call R script properly?

Body:
Use the reticulate package. Run your Python code in either an R Markdown file or source it using reticulate::source_python(). This creates a Python object in your R session called py. Access objects created in Python using the extract operator: py$N, for example, would correspond with an object named N created by your Python script.

library(reticulate)

# This is a python block
N = 2

# This is an R block
r_N <- py$N
main(r_N)


问:
React defaultValue for Select with Dynamically Generated Options
Use the defaultValue or value props on  instead of setting selected on .

```<code><select defaultValue="react">
 <option value="react">React</option>
 <option value="angular">Angular</option>
</select>
</code>```

defaultValue would work with the above select tag. However, it does not seem to work with options generated by loop.

```<code><select defaultValue={selectedOptionId}>
{option_id.map(id =>
  <option key={id} value={id}>{options[id].name}</option>
)}
</select>
</code>```

Probably options not fully been set when defaultValue was declared?

I could do manual assigning in componentDidUpdate() and onChange event.

But my question is - Is there any cleaner(better) way to solve it?

Thanks.

答:
The best solution that I could find is to set key attribute the same as defaultValue so it will be a different element.

Aftermaths are not researched by me but I believe it should be okay.

Body:
Use the defaultValue or value props on  instead of setting selected on .

<select defaultValue="react">
 <option value="react">React</option>
 <option value="angular">Angular</option>
</select>

defaultValue would work with the above select tag. However, it does not seem to work with options generated by loop.

<select defaultValue={selectedOptionId}>
{option_id.map(id =>
  <option key={id} value={id}>{options[id].name}</option>
)}
</select>

Probably options not fully been set when defaultValue was declared?

I could do manual assigning in componentDidUpdate() and onChange event.

But my question is - Is there any cleaner(better) way to solve it?

Thanks.


问:
Add blank option to top of select and make it the selected option in IE
HTML:

```<code><select id="dropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
</code>```

jQuery:

```<code>$("#dropdown").prepend("<option value='' selected='selected'></option>");
</code>```

When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?

http://jsfiddle.net/YFu2h/

答:
Try:

```<code>$("#dropdown").prepend(new Option('', '', true, true));
$("#dropdown option:first").attr("selected", "selected");
</code>```

Or, if you prefer:

```<code>$("#dropdown").prepend("<option value=''></option>");
$("#dropdown option:first").attr("selected", "selected");
</code>```

Using the first option is marginally quicker. The blank quotes mean blank value and blank text, so fill them in as you need. You don't need the selected attribute in the prepend now we are adding them afterwards. It's something to do with internet explorer not recognizing it being marked as selected as it has only just been created.

Body:
HTML:

<select id="dropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

jQuery:

$("#dropdown").prepend("<option value='' selected='selected'></option>");

When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?

http://jsfiddle.net/YFu2h/

Body:
Try:

$("#dropdown").prepend(new Option('', '', true, true));
$("#dropdown option:first").attr("selected", "selected");

Or, if you prefer:

$("#dropdown").prepend("<option value=''></option>");
$("#dropdown option:first").attr("selected", "selected");

Using the first option is marginally quicker. The blank quotes mean blank value and blank text, so fill them in as you need. You don't need the selected attribute in the prepend now we are adding them afterwards. It's something to do with internet explorer not recognizing it being marked as selected as it has only just been created.


问:
TypeError: command() takes 0 positional arguments but 1 was given
I tried to code in bot class like this:

```<code>class Bot(commands.Bot):
    def __init__(self):
      super().__init__(super().__init__(token='[Your Token]', nick='Hangman', prefix='!', initial_channels=['[Your Channel Name]']))

    async def event_ready(self):
        # We are logged in and ready to chat and use commands...
        print(f'Logged in as | {self.nick}')

    @commands.command
    async def guess(self, ctx: commands.Context):
        print(commands.Context)
        game.check_guess(self, guess)
</code>```

but it displayed like this when I run:

```<code>Traceback (most recent call last):
  File "c:\Users\Humenoid\Hangman-for-chatbox\main.py", line 42, in <module>
    class Bot(commands.Bot):
  File "c:\Users\Humenoid\Hangman-for-chatbox\main.py", line 51, in Bot
    async def guess(self, ctx: commands.Context):
TypeError: command() takes 0 positional arguments but 1 was given
</code>```

Is there any error?

答:
I guess you should add parentheses (round brackets):</p>
```<code>@commands.command()
async def guess(self, ctx: commands.Context):
    print(commands.Context)
    game.check_guess(self, guess)
</code>```

Body:
I tried to code in bot class like this:

class Bot(commands.Bot):
    def __init__(self):
      super().__init__(super().__init__(token='[Your Token]', nick='Hangman', prefix='!', initial_channels=['[Your Channel Name]']))

    async def event_ready(self):
        # We are logged in and ready to chat and use commands...
        print(f'Logged in as | {self.nick}')

    @commands.command
    async def guess(self, ctx: commands.Context):
        print(commands.Context)
        game.check_guess(self, guess)

but it displayed like this when I run:

Traceback (most recent call last):
  File "c:\Users\Humenoid\Hangman-for-chatbox\main.py", line 42, in <module>
    class Bot(commands.Bot):
  File "c:\Users\Humenoid\Hangman-for-chatbox\main.py", line 51, in Bot
    async def guess(self, ctx: commands.Context):
TypeError: command() takes 0 positional arguments but 1 was given

Is there any error?

Body:
I guess you should add parentheses (round brackets):

@commands.command()
async def guess(self, ctx: commands.Context):
    print(commands.Context)
    game.check_guess(self, guess)