问:
Spring boot validation not working how it should be
I've been trying to validate some fields in my entity class, but have not had any success. When I try to submit the form I get Whitelabel exception page, and on debut my postMapping "/create" does not even trigger. The only thing I get in my logs is :

```<code>2023-01-07 23:42:39.539 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : POST "/cars/create", parameters={masked}
2023-01-07 23:42:39.539 DEBUG 14784 --- [nio-8081-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.carshop.web.view.controllers.CarController#createCars(CreateCarViewModel, User, BindingResult)
2023-01-07 23:42:39.540 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.method.HandlerMethod             : Could not resolve parameter [0] in public java.lang.String com.example.carshop.web.view.controllers.CarController.createCars(com.example.carshop.web.view.model.CreateCarViewModel,com.example.carshop.data.entity.User,org.springframework.validation.BindingResult): org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'car' on field 'manufactureYear': rejected value [0]; codes [Min.car.manufactureYear,Min.manufactureYear,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [car.manufactureYear,manufactureYear]; arguments []; default message [manufactureYear],1950]; default message [Min 1950]
2023-01-07 23:42:39.541  WARN 14784 --- [nio-8081-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'car' on field 'manufactureYear': rejected value [0]; codes [Min.car.manufactureYear,Min.manufactureYear,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [car.manufactureYear,manufactureYear]; arguments []; default message [manufactureYear],1950]; default message [Min 1950]]
2023-01-07 23:42:39.541 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : Completed 400 BAD_REQUEST
2023-01-07 23:42:39.542 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={masked}
2023-01-07 23:42:39.542 DEBUG 14784 --- [nio-8081-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2023-01-07 23:42:39.543 DEBUG 14784 --- [nio-8081-exec-5] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2023-01-07 23:42:39.544 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 400
</code>```

Controller: have been trying to debug here

```<code>@PostMapping("/create")
public String createCars(@Valid @ModelAttribute("car") CreateCarViewModel car, @AuthenticationPrincipal User user, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "/cars/create-car";
    }
    car.setUser(Set.of(user));
    carService.create(modelMapper.map(car, CreateCarDTO.class));
    return "redirect:/cars";
}
</code>```

create-car.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments :: head"></head>
<body class="standart">
<header th:replace="fragments :: header"></header>
<div class="col-6">
    <h2 class="def-text">Add car:</h2>
    <form action="#" th:action="@{/cars/create}" th:object="${car}" method="post">
        <div class="form-group">
            <div class="form-group">
                <input class="form-control" type="text" th:field="*{brand}" placeholder="Brand" id="brand">
                <span class="text-danger" th:if="${#fields.hasErrors('brand')}"
                      th:errors="*{brand}">Brand Error</span>
            </div>

            <div class="form-group">
                <input class="form-control" type="text" th:field="*{model}" placeholder="Model" id="model">
                <span class="text-danger" th:if="${#fields.hasErrors('model')}"
                      th:errors="*{model}">Brand Error</span>
            </div>

            <div class="form-group">
                <input class="form-control" type="text" th:field="*{color}" placeholder="Color" id="color">
                <span class="text-danger" th:if="${#fields.hasErrors('color')}"
                      th:errors="*{color}">Color Error</span>
            </div>

            <div class="form-group">
                <input class="form-control" type="text" th:field="*{registrationNumber}"
                       placeholder="Registration Number"
                       id="registrationNumber">
                <span class="text-danger" th:if="${#fields.hasErrors('registrationNumber')}"
                      th:errors="*{registrationNumber}">Registration Number Error</span>
            </div>

            <div class="form-group">
                <label for="manufactureYear">Manufacture Year: </label>
                <input class="form-control" type="text" th:field="*{manufactureYear}"
                       placeholder="Manufacture Year"
                       id="manufactureYear">
                <span class="text-danger" th:if="${#fields.hasErrors('manufactureYear')}"
                      th:errors="*{manufactureYear}">Manufacture Year Error</span>
            </div>
        </div>
        <button type="submit" class="button">Submit</button>
    </form>
</div>
</body>
</html>
</code>```

Body:
I've been trying to validate some fields in my entity class, but have not had any success. When I try to submit the form I get Whitelabel exception page, and on debut my postMapping "/create" does not even trigger. The only thing I get in my logs is :

2023-01-07 23:42:39.539 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : POST "/cars/create", parameters={masked}
2023-01-07 23:42:39.539 DEBUG 14784 --- [nio-8081-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.carshop.web.view.controllers.CarController#createCars(CreateCarViewModel, User, BindingResult)
2023-01-07 23:42:39.540 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.method.HandlerMethod             : Could not resolve parameter [0] in public java.lang.String com.example.carshop.web.view.controllers.CarController.createCars(com.example.carshop.web.view.model.CreateCarViewModel,com.example.carshop.data.entity.User,org.springframework.validation.BindingResult): org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'car' on field 'manufactureYear': rejected value [0]; codes [Min.car.manufactureYear,Min.manufactureYear,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [car.manufactureYear,manufactureYear]; arguments []; default message [manufactureYear],1950]; default message [Min 1950]
2023-01-07 23:42:39.541  WARN 14784 --- [nio-8081-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'car' on field 'manufactureYear': rejected value [0]; codes [Min.car.manufactureYear,Min.manufactureYear,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [car.manufactureYear,manufactureYear]; arguments []; default message [manufactureYear],1950]; default message [Min 1950]]
2023-01-07 23:42:39.541 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : Completed 400 BAD_REQUEST
2023-01-07 23:42:39.542 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={masked}
2023-01-07 23:42:39.542 DEBUG 14784 --- [nio-8081-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2023-01-07 23:42:39.543 DEBUG 14784 --- [nio-8081-exec-5] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2023-01-07 23:42:39.544 DEBUG 14784 --- [nio-8081-exec-5] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 400

Controller: have been trying to debug here

@PostMapping("/create")
public String createCars(@Valid @ModelAttribute("car") CreateCarViewModel car, @AuthenticationPrincipal User user, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "/cars/create-car";
    }
    car.setUser(Set.of(user));
    carService.create(modelMapper.map(car, CreateCarDTO.class));
    return "redirect:/cars";
}

create-car.html

<!DOCTYPE html>

Add car:

    <form action="#" th:action="@{/cars/create}" th:object="${car}" method="post">

                <input class="form-control" type="text" th:field="*{brand}" placeholder="Brand" id="brand">
                Brand Error

                <input class="form-control" type="text" th:field="*{model}" placeholder="Model" id="model">
                Brand Error

                <input class="form-control" type="text" th:field="*{color}" placeholder="Color" id="color">
                Color Error

                <input class="form-control" type="text" th:field="*{registrationNumber}"
                       placeholder="Registration Number"
                       id="registrationNumber">
                Registration Number Error

                Manufacture Year:
                <input class="form-control" type="text" th:field="*{manufactureYear}"
                       placeholder="Manufacture Year"
                       id="manufactureYear">
                Manufacture Year Error

        <button type="submit" class="button">Submit</button>
    </form>


来源: stackexchange

问:
Could use some help installing pyqt6
I have tried to install pyqt6 in many possible ways including:

```<code>pip install pyqt6
pip3 install pyqt6
python -m pip install pyqt6
python3 -m pip install pyqt6
python3.9 -m pip install pyqt6
</code>```

i have pip-22.3.1 and Python 3.9.1 (installed manually from source because my linux mint doesn't have 3.9 in the repository - same problem on another machine with ubuntu installed)

I always get the following error:

```<code>Collecting pyqt6
  Using cached PyQt6-6.4.0.tar.gz (1.0 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [32 lines of output]
      Querying qmake about your Qt installation...
      Traceback (most recent call last):
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
          main()
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "project.py", line 65, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/builder.py", line 78, in apply_user_defaults
          self._get_qt_configuration()
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/builder.py", line 523, in _get_qt_configuration
          raise UserException(
      sipbuild.exceptions.UserException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

I already found this question:
Require help installing pyqt6
but nobody every answered. so i though maybe somebody can help this time?

see above, i tried many different versions of python. and i googled all the possible keywords. all i found was the hint to use 3.9 instead of 3.10 and one other thread on stack overflow (5 months ago) which got no answers.

ContentLicense: CC BY-SA 4.0

Title: Could use some help installing pyqt6

Body:
I have tried to install pyqt6 in many possible ways including:

pip install pyqt6
pip3 install pyqt6
python -m pip install pyqt6
python3 -m pip install pyqt6
python3.9 -m pip install pyqt6

i have pip-22.3.1 and Python 3.9.1 (installed manually from source because my linux mint doesn't have 3.9 in the repository - same problem on another machine with ubuntu installed)

I always get the following error:

Collecting pyqt6
  Using cached PyQt6-6.4.0.tar.gz (1.0 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [32 lines of output]
      Querying qmake about your Qt installation...
      Traceback (most recent call last):
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
          main()
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/home/dirk/.local/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "project.py", line 65, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/sipbuild/project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/builder.py", line 78, in apply_user_defaults
          self._get_qt_configuration()
        File "/tmp/pip-build-env-g5ul20hq/overlay/lib/python3.9/site-packages/pyqtbuild/builder.py", line 523, in _get_qt_configuration
          raise UserException(
      sipbuild.exceptions.UserException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

I already found this question:
Require help installing pyqt6
but nobody every answered. so i though maybe somebody can help this time?

see above, i tried many different versions of python. and i googled all the possible keywords. all i found was the hint to use 3.9 instead of 3.10 and one other thread on stack overflow (5 months ago) which got no answers.


问:
Error installing tensor flow-metal plugin
I followed the instruction to install the tensorflow-metal plugin, but when I ran the verification example found on the website I am getting these errors

```<code>2023-01-07 16:51:14.262420: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2023-01-07 16:51:14.262841: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
Metal device set to: Apple M2

</code>```

and

```<code>2023-01-07 16:51:21.570969: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at xla_ops.cc:418 : NOT_FOUND: could not find registered platform with id: 0x110095240
</code>```

I tried googling this issue and set up a virtual environment, but nothing works so far.

Body:
I followed the instruction to install the tensorflow-metal plugin, but when I ran the verification example found on the website I am getting these errors

2023-01-07 16:51:14.262420: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2023-01-07 16:51:14.262841: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
Metal device set to: Apple M2

and

2023-01-07 16:51:21.570969: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at xla_ops.cc:418 : NOT_FOUND: could not find registered platform with id: 0x110095240

I tried googling this issue and set up a virtual environment, but nothing works so far.


问:
PHP MicroTimer class error with phpliteadmin
I'm getting a This page isn’t workinglocalhost is currently unable to handle this request. HTTP ERROR 500 error when trying to load phpliteadmin.php (See phpLiteAdmin). Looking at the Apache log

```<code>[mpm_prefork:notice] [pid 527610] AH00170: caught SIGWINCH, shutting down gracefully
[Sat Jan 07 15:16:21.081744 2023] [mpm_prefork:notice] [pid 528031] AH00163: Apache/2.4.54 (Ubuntu) configured -- resuming normal operations
[Sat Jan 07 15:16:21.081776 2023] [core:notice] [pid 528031] AH00094: Command line: '/usr/sbin/apache2'
[Sat Jan 07 15:16:27.554033 2023] [php:error] [pid 528032] [client ::1:36282] PHP Fatal error:  Uncaught Error: Class "MicroTimer" not found in /var/www/html/phpliteadmin.php:476\nStack trace:\n#0 {main}\n  thrown in /var/www/html/phpliteadmin.php on line 476
</code>```

The file's permissions are root root 644 just like my index.html and info.php files. Any ideas what this is about? I'm using the downloaded latest. Before, I installed from apt and it wouldn't see my config's given directory. So I'm at a standstill...

Body:
I'm getting a This page isn’t workinglocalhost is currently unable to handle this request. HTTP ERROR 500 error when trying to load phpliteadmin.php (See phpLiteAdmin). Looking at the Apache log

[mpm_prefork:notice] [pid 527610] AH00170: caught SIGWINCH, shutting down gracefully
[Sat Jan 07 15:16:21.081744 2023] [mpm_prefork:notice] [pid 528031] AH00163: Apache/2.4.54 (Ubuntu) configured -- resuming normal operations
[Sat Jan 07 15:16:21.081776 2023] [core:notice] [pid 528031] AH00094: Command line: '/usr/sbin/apache2'
[Sat Jan 07 15:16:27.554033 2023] [php:error] [pid 528032] [client ::1:36282] PHP Fatal error:  Uncaught Error: Class "MicroTimer" not found in /var/www/html/phpliteadmin.php:476\nStack trace:\n#0 {main}\n  thrown in /var/www/html/phpliteadmin.php on line 476

The file's permissions are root root 644 just like my index.html and info.php files. Any ideas what this is about? I'm using the downloaded latest. Before, I installed from apt and it wouldn't see my config's given directory. So I'm at a standstill...


问:
How to resolve "MismatchingStateError: (mismatching_state) CSRF Warning!" when using Github Authentication in a Flask App?
I am using the Flask-Dance package for logging in to my app via Github and I've configured it in my project but I get this error in response:

```<code>oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning!      State not equal in request and response.
</code>```

What can I do ?

My code is:

github_bp = make_github_blueprint()
app.register_blueprint(github_bp, url_prefix="/login")
```
<p>and</p>
<pre class="lang-py prettyprint-override"><code>@app.route('/')
def github():
    if not github.authorized:
        return redirect(url_for('github.login'))
    resp = github.get('/user')
    assert resp.ok
    login = resp.json()['login']
    return f'You are {login} on GitHub'
</code>```

Body:
I am using the Flask-Dance package for logging in to my app via Github and I've configured it in my project but I get this error in response:

oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning!      State not equal in request and response.

What can I do ?

My code is:

github_bp = make_github_blueprint()
app.register_blueprint(github_bp, url_prefix="/login")

and

@app.route('/')
def github():
    if not github.authorized:
        return redirect(url_for('github.login'))
    resp = github.get('/user')
    assert resp.ok
    login = resp.json()['login']
    return f'You are {login} on GitHub'


问:
Raspberry Pi Pico load values from config file
I am using the C, C++ SDK for RPI Pico. I have written a C program that gets a value from a config text file then uses the said value for various purposes.

The problem is that I want to give this to an end user. And I thought that the easiest thing would be to give them the uf2 file and this config text file, and they could put the RPI Pico in Mass storage mode and play with the config as they see fit.

But if I move the config and *.uf2 file to the Pico it will not actually read any data from this config file.

Is there a way to do this? Or should I look into a different approach? I would need the simplest approach possible, because I am very much a newbie in embedded programming, also I would rather not add hardware components, like extra memory or dipswitches (to set the values). I also need this value to be stored after a power outage (so it's not okay if the end-user sets the values through some serial means, or any other means that would not persist a power-cycle and are volatile.).


问:
Cannot convert relative path Home\daemon\7.6 to an absolute file.?
I tryed every tutorial. Doesnt work...
Like settings and locate .gradle folder. Download gradle 7.6 and select too.

Tryed Fix this


问:
How to upload or charge data to my hooks before the page get renderd ? Next js
so I want to keep the data in my my hooks stored even when I reload the page, my initial data are fetched from my database in the first render.

Why I want that ? because:
I have a page with all my orders, and when I click in one of them it will take me to that order page, the problem is everything looks good when i jump from link to another but when i try to reload the order page it render the page after it loads the order info from the hook.

what I really want is to get the order info before the compenent get fully renderd.. and when i typed a wrong id in the url i want to take me to the 404 page before the order component ger render.

i tried to save the orders in a localStorage and get them later but I always have the same problem,

i'm new to this and I want a good way to do it.. Thanks.

GlobalState.js(first lines):

```<code>export const DataProvider = ({ children }) => {
  const initialState = { notify: {}, auth: {}, cart: [], modal: {}, orders: [] };
  const [state, dispatch] = useReducer(reducers, initialState);
  const { cart, auth, orders } = state;
</code>```

here is how i get the orders and i saved them to orders GlobalState:

```<code> useEffect(() => {
    if (auth.token) {
      getData('order', auth.token)
        .then(res => {
          if (res.err) return dispatch({ type: 'NOTIFY', payload: { error: res.err } })
          // add orders to local storage
          window.localStorage.setItem('__next__orders01__distou', JSON.stringify(res.orders))
          dispatch({ type: 'ADD_ORDERS', payload: res.orders })
        })
    }
  }, [auth.token])
</code>```

Order Page:

```<code>const Order = (props) => {

  const { state, dispatch } = useContext(DataContext);
  const { auth, orders } = state;
  console.log(props.orderDetail)
  const router = useRouter();
  const [orderDetail, setOrderDetail] = useState([]);

  useEffect(() => {
    const my_orders = JSON.parse(localStorage.getItem('__next__orders01__distou'))
    if (my_orders) {
    const newArr = my_orders.filter((order) => order._id === router.query.id);
    if(newArr.length != 0){
      setOrderDetail(newArr);
      dispatch({ type: 'NOTIFY', payload: {} })
    }
  }
  }, [orders]);
  if (orderDetail.length === 0) return  dispatch({ type: 'NOTIFY', payload: { loading: true} })

  if (!auth.user) return null
  return (
    <>
     ...
   </>
)
}

I tried to save the orders in the local storage but i always get the same problem, i think i need to fetch the order data in every request, i tried getServerSideProps but it didn't work.
</code>```

Body:
so I want to keep the data in my my hooks stored even when I reload the page, my initial data are fetched from my database in the first render.

Why I want that ? because:
I have a page with all my orders, and when I click in one of them it will take me to that order page, the problem is everything looks good when i jump from link to another but when i try to reload the order page it render the page after it loads the order info from the hook.

what I really want is to get the order info before the compenent get fully renderd.. and when i typed a wrong id in the url i want to take me to the 404 page before the order component ger render.

i tried to save the orders in a localStorage and get them later but I always have the same problem,

i'm new to this and I want a good way to do it.. Thanks.

GlobalState.js(first lines):

export const DataProvider = ({ children }) => {
  const initialState = { notify: {}, auth: {}, cart: [], modal: {}, orders: [] };
  const [state, dispatch] = useReducer(reducers, initialState);
  const { cart, auth, orders } = state;

here is how i get the orders and i saved them to orders GlobalState:

 useEffect(() => {
    if (auth.token) {
      getData('order', auth.token)
        .then(res => {
          if (res.err) return dispatch({ type: 'NOTIFY', payload: { error: res.err } })
          // add orders to local storage
          window.localStorage.setItem('__next__orders01__distou', JSON.stringify(res.orders))
          dispatch({ type: 'ADD_ORDERS', payload: res.orders })
        })
    }
  }, [auth.token])

Order Page:

const Order = (props) => {

  const { state, dispatch } = useContext(DataContext);
  const { auth, orders } = state;
  console.log(props.orderDetail)
  const router = useRouter();
  const [orderDetail, setOrderDetail] = useState([]);

  useEffect(() => {
    const my_orders = JSON.parse(localStorage.getItem('__next__orders01__distou'))
    if (my_orders) {
    const newArr = my_orders.filter((order) => order._id === router.query.id);
    if(newArr.length != 0){
      setOrderDetail(newArr);
      dispatch({ type: 'NOTIFY', payload: {} })
    }
  }
  }, [orders]);
  if (orderDetail.length === 0) return  dispatch({ type: 'NOTIFY', payload: { loading: true} })

  if (!auth.user) return null
  return (
    <>
     ...
   </>
)
}

I tried to save the orders in the local storage but i always get the same problem, i think i need to fetch the order data in every request, i tried getServerSideProps but it didn't work.


问:
Update a fragment using broadcast receiver
im trying to build a step-counter app using Android Studio. I created a fragment "Home Fragment" with and inner class "MyService" where i selected my sensor "TYPE_STEP_COUNTER" and sending on my BroadcastReceiver the var step. Then i want to update the layout inflated on fragment but the ways i tryed doesn't work. here the code:

```<code>public class HomeFragment extends Fragment {

    //public static final String STEP_COUNT_UPDATE = "com.example.StayFit.STEP_COUNT_UPDATE";
    public static final String STAY_FIT = "com.example.stayfit";
    private static final int UPDATE_PROGRESS_BAR = 1;

    LocalBroadcastReceiver localtReceiver;
    IntentFilter intentFilter;
    DataBaseHandler dbHandler;
    SharedPreferences sharedPrefSC;

    TextView mTextViewKMPercorsi;
    TextView mTextObiettivoPassi;
    TextView mTextPassiRimanenti;
    CircularProgressIndicator circularProgress;

    private int obiettivoPassi;
    private String obiettivoPassiStr;
    private boolean isRegistered = false;
    Handler mHandler;   // Metodo 4
    public float lunghezzaPassi;
    private String lunghezzaPassiStr;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Recupero l'utente della sessione attraverso SP per ottenere l'obiettivo passi.
        sharedPrefSC = getActivity().getSharedPreferences(STAY_FIT, Context.MODE_PRIVATE);
        String nomeUtente = sharedPrefSC.getString("utenteSessione", "fail");
        //Log.d("SHAREDPREF","viene passato" + nomeUtente);

        // Recupero l'obiettivo passi dal DB
        dbHandler = new DataBaseHandler(getActivity());
        obiettivoPassi = dbHandler.getObiettivoPassi(nomeUtente);
        obiettivoPassiStr = Integer.toString(obiettivoPassi);

        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);

        // Metodo 4 - handler
        mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                if (message.what == UPDATE_PROGRESS_BAR) {
                    // Aggiorna la progress bar
                    int progress = message.arg1;;
                    circularProgress.setCurrentProgress(progress);
                    Toast.makeText(getActivity(), "Looper Corretto", Toast.LENGTH_SHORT).show();
                    mTextViewKMPercorsi.setText((String) message.obj + " Km");
                    mTextPassiRimanenti.setText("Forza! Ti mancano ancora " + message.arg2 + " passi per il tuo obiettivo!");
                }
            }
        };

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Faccio l'inflate del layout per questo fragment
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        circularProgress = v.findViewById(R.id.circular_progress);
        mTextViewKMPercorsi = v.findViewById(R.id.textViewKMPercorsi);
        mTextObiettivoPassi = v.findViewById(R.id.textObiettivoPassi);
        mTextPassiRimanenti = v.findViewById(R.id.textPassiRimanenti);

        mTextObiettivoPassi.setText("Obiettivo passi pls: " + obiettivoPassiStr);

        circularProgress.setMaxProgress(obiettivoPassi);
        //circularProgress.setCurrentProgress(conteggioPassiTotali);

        // Procedo a registrare il BroadCast Receiver:
        intentFilter = new IntentFilter(LocalBroadcastReceiver.STEP_COUNT_UPDATE);
        localtReceiver = new LocalBroadcastReceiver();
        if (!isRegistered) {
            registerLocalReceiver();
        }
        //getActivity().registerReceiver(broadcastReceiver, intentFilter);

        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);
        if (!isRegistered) {
            registerLocalReceiver();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);

        if (!isRegistered) {
            registerLocalReceiver();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().stopService(service);
        if (isRegistered) {
            unregisterLocalReceiver();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().stopService(service);

        if (isRegistered) {
            unregisterLocalReceiver();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isRegistered) {
            unregisterLocalReceiver();
        }

    }

    private void registerLocalReceiver() {
        if (!isRegistered) {
            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(localtReceiver, intentFilter);
            isRegistered = true;
        }
    }

    private void unregisterLocalReceiver() {
        if (isRegistered) {
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(localtReceiver);
            isRegistered = false;
        }
    }

}
</code>```

And here is the local BR:

```<code>public class LocalBroadcastReceiver extends BroadcastReceiver {

    public static final String STEP_COUNT_UPDATE = "com.example.StayFit.STEP_COUNT_UPDATE";
    public static final String STAY_FIT = "com.example.stayfit";
    private static final int UPDATE_PROGRESS_BAR = 1;

    private int conteggioPassiTotali;
    private float kmPercorsiFloat;
    private int passiRimanenti;
    private int obiettivoPassi;
    private float lunghezzaPassi=1;

    HomeFragment homeFragment;
    DataBaseHandler dbHandler;
    SharedPreferences sharedPrefSC;

    @Override
    public void onReceive(Context context, Intent intent) {
        sharedPrefSC = context.getSharedPreferences(STAY_FIT,Context.MODE_PRIVATE);
        String nomeUtente = sharedPrefSC.getString("utenteSessione", "fail");

        if (intent != null && STEP_COUNT_UPDATE.equals(intent.getAction())) {
            obiettivoPassi = dbHandler.getObiettivoPassi(nomeUtente);
            conteggioPassiTotali = intent.getIntExtra("conteggioPassiTotali", 1234);

            kmPercorsiFloat = (conteggioPassiTotali*lunghezzaPassi)/1000;
            passiRimanenti = obiettivoPassi-conteggioPassiTotali;

            String kmPercorsiStr = String.format("%.2f", kmPercorsiFloat);
            String conteggioPassiTotaliStr = String.valueOf(conteggioPassiTotali);

            // Metodo 4 - handler
            // Creating the message for the handler
            Message message = homeFragment.mHandler.obtainMessage(UPDATE_PROGRESS_BAR,conteggioPassiTotali,passiRimanenti,kmPercorsiStr);

            // Sending the handler
            homeFragment.mHandler.sendMessage(message);

        }
    }
}
</code>```

And here the Service class:

```<code>public class StepService extends Service implements SensorEventListener {

    public static final String STAY_FIT = "com.example.stayfit";

    private boolean primoAvvio;
    private int conteggioPassiTotali;
    private int conteggioPassiAvvio;
    private int conteggioPassiCorrenti;
    SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        sharedPreferences = getSharedPreferences(STAY_FIT, MODE_PRIVATE);
        primoAvvio = sharedPreferences.getBoolean("primoAvvio", false);

        Log.d("testServoce",Boolean.toString(primoAvvio));

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Ottengo un riferimento al SensorManager
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        // Ottengo un riferimento al sensore "STEP_COUNTER"
        Sensor stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

        // Verifica presenza del sensore
        if(stepCounterSensor != null) {
            // Lo rendo disponibile:
            sensorManager.registerListener(this, stepCounterSensor,SensorManager.SENSOR_DELAY_NORMAL);
                        //Toast.makeText(this, "Congratulazioni, Sensore Presente!", Toast.LENGTH_SHORT).show();
            Log.d("sensore","sensore presente");
        }else{
            Toast.makeText(this, "Sensore non presente", Toast.LENGTH_SHORT).show();
            Log.d("sensore","sensore NON presente");
        }

        // Dice al sistema di riavviare il serivice dopo un crash e di rilasciare gli intent presenti al momento del crash
        return START_REDELIVER_INTENT;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(primoAvvio){

            //primoAvvio = false;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("primoAvvio", false);
            editor.apply();
            conteggioPassiAvvio = (int) event.values[0];
            Log.d("TestPrimoAvvio",Boolean.toString(primoAvvio));
            //Log.d("TestNumeroPassi",Integer.toString(conteggioPassiAvvio));
        }
        Toast.makeText(this, "Rilevato passo", Toast.LENGTH_SHORT).show();
        // L'evento del sensore contiene il numero di passi effettuati dall'utente dal reboot
        conteggioPassiCorrenti = (int) event.values[0];
        conteggioPassiTotali = conteggioPassiCorrenti- conteggioPassiAvvio;

        Intent intentStep = new Intent(LocalBroadcastReceiver.STEP_COUNT_UPDATE);
        intentStep.putExtra("conteggioPassiTotali",conteggioPassiTotali);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentStep);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

}

</code>```

Any suggestion?

I just want to update the circleProgressBar with the current number of step. I don't know if i got a problem with the broadcast or with the code below onSensorChanged

EDIT: just modified the code with update.

Body:
im trying to build a step-counter app using Android Studio. I created a fragment "Home Fragment" with and inner class "MyService" where i selected my sensor "TYPE_STEP_COUNTER" and sending on my BroadcastReceiver the var step. Then i want to update the layout inflated on fragment but the ways i tryed doesn't work. here the code:

public class HomeFragment extends Fragment {

    //public static final String STEP_COUNT_UPDATE = "com.example.StayFit.STEP_COUNT_UPDATE";
    public static final String STAY_FIT = "com.example.stayfit";
    private static final int UPDATE_PROGRESS_BAR = 1;

    LocalBroadcastReceiver localtReceiver;
    IntentFilter intentFilter;
    DataBaseHandler dbHandler;
    SharedPreferences sharedPrefSC;

    TextView mTextViewKMPercorsi;
    TextView mTextObiettivoPassi;
    TextView mTextPassiRimanenti;
    CircularProgressIndicator circularProgress;

    private int obiettivoPassi;
    private String obiettivoPassiStr;
    private boolean isRegistered = false;
    Handler mHandler;   // Metodo 4
    public float lunghezzaPassi;
    private String lunghezzaPassiStr;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Recupero l'utente della sessione attraverso SP per ottenere l'obiettivo passi.
        sharedPrefSC = getActivity().getSharedPreferences(STAY_FIT, Context.MODE_PRIVATE);
        String nomeUtente = sharedPrefSC.getString("utenteSessione", "fail");
        //Log.d("SHAREDPREF","viene passato" + nomeUtente);

        // Recupero l'obiettivo passi dal DB
        dbHandler = new DataBaseHandler(getActivity());
        obiettivoPassi = dbHandler.getObiettivoPassi(nomeUtente);
        obiettivoPassiStr = Integer.toString(obiettivoPassi);

        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);

        // Metodo 4 - handler
        mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                if (message.what == UPDATE_PROGRESS_BAR) {
                    // Aggiorna la progress bar
                    int progress = message.arg1;;
                    circularProgress.setCurrentProgress(progress);
                    Toast.makeText(getActivity(), "Looper Corretto", Toast.LENGTH_SHORT).show();
                    mTextViewKMPercorsi.setText((String) message.obj + " Km");
                    mTextPassiRimanenti.setText("Forza! Ti mancano ancora " + message.arg2 + " passi per il tuo obiettivo!");
                }
            }
        };

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Faccio l'inflate del layout per questo fragment
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        circularProgress = v.findViewById(R.id.circular_progress);
        mTextViewKMPercorsi = v.findViewById(R.id.textViewKMPercorsi);
        mTextObiettivoPassi = v.findViewById(R.id.textObiettivoPassi);
        mTextPassiRimanenti = v.findViewById(R.id.textPassiRimanenti);

        mTextObiettivoPassi.setText("Obiettivo passi pls: " + obiettivoPassiStr);

        circularProgress.setMaxProgress(obiettivoPassi);
        //circularProgress.setCurrentProgress(conteggioPassiTotali);

        // Procedo a registrare il BroadCast Receiver:
        intentFilter = new IntentFilter(LocalBroadcastReceiver.STEP_COUNT_UPDATE);
        localtReceiver = new LocalBroadcastReceiver();
        if (!isRegistered) {
            registerLocalReceiver();
        }
        //getActivity().registerReceiver(broadcastReceiver, intentFilter);

        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);
        if (!isRegistered) {
            registerLocalReceiver();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().startService(service);

        if (!isRegistered) {
            registerLocalReceiver();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().stopService(service);
        if (isRegistered) {
            unregisterLocalReceiver();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Intent service = new Intent(getActivity(), StepService.class);
        getActivity().stopService(service);

        if (isRegistered) {
            unregisterLocalReceiver();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isRegistered) {
            unregisterLocalReceiver();
        }

    }

    private void registerLocalReceiver() {
        if (!isRegistered) {
            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(localtReceiver, intentFilter);
            isRegistered = true;
        }
    }

    private void unregisterLocalReceiver() {
        if (isRegistered) {
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(localtReceiver);
            isRegistered = false;
        }
    }

}

And here is the local BR:

public class LocalBroadcastReceiver extends BroadcastReceiver {

    public static final String STEP_COUNT_UPDATE = "com.example.StayFit.STEP_COUNT_UPDATE";
    public static final String STAY_FIT = "com.example.stayfit";
    private static final int UPDATE_PROGRESS_BAR = 1;

    private int conteggioPassiTotali;
    private float kmPercorsiFloat;
    private int passiRimanenti;
    private int obiettivoPassi;
    private float lunghezzaPassi=1;

    HomeFragment homeFragment;
    DataBaseHandler dbHandler;
    SharedPreferences sharedPrefSC;

    @Override
    public void onReceive(Context context, Intent intent) {
        sharedPrefSC = context.getSharedPreferences(STAY_FIT,Context.MODE_PRIVATE);
        String nomeUtente = sharedPrefSC.getString("utenteSessione", "fail");

        if (intent != null && STEP_COUNT_UPDATE.equals(intent.getAction())) {
            obiettivoPassi = dbHandler.getObiettivoPassi(nomeUtente);
            conteggioPassiTotali = intent.getIntExtra("conteggioPassiTotali", 1234);

            kmPercorsiFloat = (conteggioPassiTotali*lunghezzaPassi)/1000;
            passiRimanenti = obiettivoPassi-conteggioPassiTotali;

            String kmPercorsiStr = String.format("%.2f", kmPercorsiFloat);
            String conteggioPassiTotaliStr = String.valueOf(conteggioPassiTotali);

            // Metodo 4 - handler
            // Creating the message for the handler
            Message message = homeFragment.mHandler.obtainMessage(UPDATE_PROGRESS_BAR,conteggioPassiTotali,passiRimanenti,kmPercorsiStr);

            // Sending the handler
            homeFragment.mHandler.sendMessage(message);

        }
    }
}

And here the Service class:

public class StepService extends Service implements SensorEventListener {

    public static final String STAY_FIT = "com.example.stayfit";

    private boolean primoAvvio;
    private int conteggioPassiTotali;
    private int conteggioPassiAvvio;
    private int conteggioPassiCorrenti;
    SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        sharedPreferences = getSharedPreferences(STAY_FIT, MODE_PRIVATE);
        primoAvvio = sharedPreferences.getBoolean("primoAvvio", false);

        Log.d("testServoce",Boolean.toString(primoAvvio));

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Ottengo un riferimento al SensorManager
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        // Ottengo un riferimento al sensore "STEP_COUNTER"
        Sensor stepCounterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

        // Verifica presenza del sensore
        if(stepCounterSensor != null) {
            // Lo rendo disponibile:
            sensorManager.registerListener(this, stepCounterSensor,SensorManager.SENSOR_DELAY_NORMAL);
                        //Toast.makeText(this, "Congratulazioni, Sensore Presente!", Toast.LENGTH_SHORT).show();
            Log.d("sensore","sensore presente");
        }else{
            Toast.makeText(this, "Sensore non presente", Toast.LENGTH_SHORT).show();
            Log.d("sensore","sensore NON presente");
        }

        // Dice al sistema di riavviare il serivice dopo un crash e di rilasciare gli intent presenti al momento del crash
        return START_REDELIVER_INTENT;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(primoAvvio){

            //primoAvvio = false;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("primoAvvio", false);
            editor.apply();
            conteggioPassiAvvio = (int) event.values[0];
            Log.d("TestPrimoAvvio",Boolean.toString(primoAvvio));
            //Log.d("TestNumeroPassi",Integer.toString(conteggioPassiAvvio));
        }
        Toast.makeText(this, "Rilevato passo", Toast.LENGTH_SHORT).show();
        // L'evento del sensore contiene il numero di passi effettuati dall'utente dal reboot
        conteggioPassiCorrenti = (int) event.values[0];
        conteggioPassiTotali = conteggioPassiCorrenti- conteggioPassiAvvio;

        Intent intentStep = new Intent(LocalBroadcastReceiver.STEP_COUNT_UPDATE);
        intentStep.putExtra("conteggioPassiTotali",conteggioPassiTotali);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intentStep);

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

}

Any suggestion?

I just want to update the circleProgressBar with the current number of step. I don't know if i got a problem with the broadcast or with the code below onSensorChanged

EDIT: just modified the code with update.


问:
How to fix choppy animations in HTML/CSS/jQuery Flexbox Image Gallery?
I'm trying to make a filterable gallery using CSS flexbox that has smooth animations using HTML, CSS, and jQuery (JS).

Everything works but the animations are sometimes choppy when filtering.

Here is a reproduction of my problem where I use an .img-hidden class to reduce width, height, and margin to 0px:

$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").removeClass("img-hidden");
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).removeClass("img-hidden");
                }
                else {
                    $(".image").eq(i).addClass("img-hidden");
                }
            });
        }
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    transition: width 1s ease, height 1s ease, margin 1s ease;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* Transition Classes */

.img-hidden {
    width: 0px !important;
    height: 0px !important;
    margin: 0px;
}</code>```

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    Filter by:
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>

```
</div>
</div>
</p>
<p>However, this method isn't the only method I tried.</p>
<p>Here is the same problem where I used jQuery's built-in <code>show()</code> and <code>hide()</code> methods:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").show(1000);
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).show(1000);
                }
                else {
                    $(".image").eq(i).hide(1000);
                }
            });
        }
    }
});</code>```

/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  </head>
  <body>
    <label for="filters">Filter by: </label>
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>
    <div class="images">
      <div class="image" data-tag="cat">
        <!-- Source: Manja Vitolic on Unsplash -->
        <img src="https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1443&q=80" />
      </div>
      <div class="image" data-tag="cat">
        <!-- Source: Micheal Sum on Unsplash -->
        <img src="https://images.unsplash.com/photo-1519052537078-e6302a4968d4?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="cat">
        <!-- Source: Mikhail Vasilyev on Unsplash -->
        <img src="https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1529&q=80" />
      </div>
      <div class="image" data-tag="cat">
        <!-- Source: Pacto Visual on Unsplash -->
        <img src="https://images.unsplash.com/photo-1478098711619-5ab0b478d6e6?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="dog">
        <!-- Source: Victor Grabarczyk on Unsplash -->
        <img src="https://images.unsplash.com/photo-1561037404-61cd46aa615b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="dog">
        <!-- Source: Marliese Streefland on Unsplash -->
        <img src="https://images.unsplash.com/photo-1543466835-00a7907e9de1?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1374&q=80" />
      </div>
      <div class="image" data-tag="dog">
        <!-- Source: Pauline Loroy on Unsplash -->
        <img src="https://images.unsplash.com/photo-1587300003388-59208cc962cb?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="dog">
        <!-- Source: Justin Veenema on Unsplash -->
        <img src="https://images.unsplash.com/photo-1477884213360-7e9d7dcc1e48?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="bird">
        <!-- Source: Vincent van Zalinge on Unsplash -->
        <img src="https://images.unsplash.com/photo-1444464666168-49d633b86797?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1469&q=80" />
      </div>
      <div class="image" data-tag="bird">
        <!-- Source: Boris Smokrovic on Unsplash -->
        <img src="https://images.unsplash.com/photo-1480044965905-02098d419e96?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
      <div class="image" data-tag="bird">
        <!-- Source: Zdeněk Macháček on Unsplash -->
        <img src="https://images.unsplash.com/photo-1551085254-e96b210db58a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1280&q=80" />
      </div>
      <div class="image" data-tag="bird">
        <!-- Source: Jan Meeus on Unsplash -->
        <img src="https://images.unsplash.com/photo-1522926193341-e9ffd686c60f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80" />
      </div>
    </div>
  </body>
</html></code>```

I even tried using CSS Animations to animate transform: scale and the width, height, and margin properties:

$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").removeClass("img-hidden");
            $(".image").addClass("img-shown");
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).removeClass("img-hidden");
                    $(".image").eq(i).addClass("img-shown");
                }
                else {
                    $(".image").eq(i).removeClass("img-shown");
                    $(".image").eq(i).addClass("img-hidden");
                }
            });
        }
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* Transition Classes */

.img-shown {
    animation: show-image 1s ease 0s 1 forwards;
    transform-origin: center;
}

.img-hidden {
    animation: hide-image 1s ease 0s 1 forwards;
    transform-origin: center;
}

/* Animations */

@keyframes hide-image {
    0% {
        transform: scale(1);
    }

    100% {
        transform: scale(0);
        width: 0;
        height: 0;
        margin: 0;
    }
}

@keyframes show-image {
    0% {
        transform: scale(0);
        width: 0;
        height: 0;
        margin: 0;
    }

    100% {
        transform: scale(1);
    }
}</code>```

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    Filter by:
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>

```

No matter what method I try, they all result in choppy animations.

Any way I can make the animations more smooth and less choppy?

Body:
I'm trying to make a filterable gallery using CSS flexbox that has smooth animations using HTML, CSS, and jQuery (JS).

Everything works but the animations are sometimes choppy when filtering.

Here is a reproduction of my problem where I use an .img-hidden class to reduce width, height, and margin to 0px:

$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").removeClass("img-hidden");
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).removeClass("img-hidden");
                }
                else {
                    $(".image").eq(i).addClass("img-hidden");
                }
            });
        }
    }
});

/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    transition: width 1s ease, height 1s ease, margin 1s ease;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* Transition Classes */

.img-hidden {
    width: 0px !important;
    height: 0px !important;
    margin: 0px;
}

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    Filter by:
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>

However, this method isn't the only method I tried.

Here is the same problem where I used jQuery's built-in show() and hide() methods:

$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").show(1000);
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).show(1000);
                }
                else {
                    $(".image").eq(i).hide(1000);
                }
            });
        }
    }
});

/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    Filter by:
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>

I even tried using CSS Animations to animate transform: scale and the width, height, and margin properties:

$(document).ready(function() {
    // Initialization

    filterImage("");
    shuffleImages();

    // On Filter Dropdown Change

    $(".filters").change(function() {
        if($(".filters").val() == "all") {
            filterImage("");
        }
        else {
            filterImage($(".filters").val());
        }
    });

    // Shuffle Order of Images

    function shuffleImages() {
        // https://stackoverflow.com/questions/18483241/random-div-order-on-page-load

        $(".image").each(function() {
            var target = Math.floor(Math.random() * $(".image").length - 1) + 1;
            var target2 = Math.floor(Math.random() * $(".image").length - 1) + 1;
            $(".image").eq(target).before($(".image").eq(target2));
        });
    }

    // Filter Images

    function filterImage(tag) {
        if(tag == "") {
            $(".image").removeClass("img-hidden");
            $(".image").addClass("img-shown");
        }
        else {
            $(".image").each(function(i) {
                if(($(".image").eq(i).data("tag")).includes(tag)) {
                    $(".image").eq(i).removeClass("img-hidden");
                    $(".image").eq(i).addClass("img-shown");
                }
                else {
                    $(".image").eq(i).removeClass("img-shown");
                    $(".image").eq(i).addClass("img-hidden");
                }
            });
        }
    }
});

/* Images Container */

.images {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding-top: 15px;
    justify-content: center;
}

/* Individual Image */

.image {
    display: block;
    width: 200px;
    height: 150px;
    margin: 5px;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
}

.image img {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* Transition Classes */

.img-shown {
    animation: show-image 1s ease 0s 1 forwards;
    transform-origin: center;
}

.img-hidden {
    animation: hide-image 1s ease 0s 1 forwards;
    transform-origin: center;
}

/* Animations */

@keyframes hide-image {
    0% {
        transform: scale(1);
    }

    100% {
        transform: scale(0);
        width: 0;
        height: 0;
        margin: 0;
    }
}

@keyframes show-image {
    0% {
        transform: scale(0);
        width: 0;
        height: 0;
        margin: 0;
    }

    100% {
        transform: scale(1);
    }
}

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    Filter by:
    <select class="filters" id="filters">
      <option value="all">All</option>
      <option value="cat">Cat</option>
      <option value="dog">Dog</option>
      <option value="bird">Bird</option>
    </select>

No matter what method I try, they all result in choppy animations.

Any way I can make the animations more smooth and less choppy?


问:
I found the source of my lagging GUI, a function, but what can I do?
I've found the cause of my lagging GUI, it's the function inRegularIntervals()

It takes an array of numbers and sort them like this:

```<code>{0: [1, 0, 0, 1, 0, 0, 0], 10: [10, 18], 20: [28], 30: [], 40: [], 50: [], 60: [], 70: [70, 73, 73, 75], 80: [80], 90: [], 100: [106], 110: [], 120: [], 130: [], 140: [140], 150: [150], 160: [], 170: [170], 180: [], 190: [194, 196], 200: [200, 202], 210: [], 220: [], 230: [], 240: [], 250: [], 260: [], 270: [], 280: [], 290: [], 300: [], 310: [], 320: [], 330: [336], 340: [], 350: [353, 356].............................................}
</code>```

After that I count the items for each bin

```<code>def inRegularIntervals(data, interval):
     """Sorts elements of data into bins of regular sizes.
     The size of each bin is given by 'interval'."""
     # init dict so keys are ordered - collection.defaultdict(list)
     # would be faster - but this works for lists of a couple of
     # thousand numbers if you have a quarter up to one second ...

     # if random key order is ok, shorten this to d = {}

     d = {k:[] for k in range(0, max(data), interval)}
     for n in data:
        key = n // interval # get key
        key *= interval
        d.setdefault(key, [])
        d[key].append(n) # add number

     return d

#First I put values into the array transactions_NOT_sorted#
transactions_NOT_sorted.append(int(round(amount)))

#Then I sort the values into bins of regular sizes. transaction_sorted is a list#
transactions_sorted = inRegularIntervals(transactions_NOT_sorted,10)

#count items for each bin
for key, value in transactions_sorted.items():
        count_items = len([item for item in value if item])
               if count_items > 0:
                    data_for_plot[key]=count_items

</code>```

I need a faster version of this. Should I use threading or multiprocessing?

Body:
I've found the cause of my lagging GUI, it's the function inRegularIntervals()

It takes an array of numbers and sort them like this:

{0: [1, 0, 0, 1, 0, 0, 0], 10: [10, 18], 20: [28], 30: [], 40: [], 50: [], 60: [], 70: [70, 73, 73, 75], 80: [80], 90: [], 100: [106], 110: [], 120: [], 130: [], 140: [140], 150: [150], 160: [], 170: [170], 180: [], 190: [194, 196], 200: [200, 202], 210: [], 220: [], 230: [], 240: [], 250: [], 260: [], 270: [], 280: [], 290: [], 300: [], 310: [], 320: [], 330: [336], 340: [], 350: [353, 356].............................................}

After that I count the items for each bin

def inRegularIntervals(data, interval):
     """Sorts elements of data into bins of regular sizes.
     The size of each bin is given by 'interval'."""
     # init dict so keys are ordered - collection.defaultdict(list)
     # would be faster - but this works for lists of a couple of
     # thousand numbers if you have a quarter up to one second ...

     # if random key order is ok, shorten this to d = {}

     d = {k:[] for k in range(0, max(data), interval)}
     for n in data:
        key = n // interval # get key
        key *= interval
        d.setdefault(key, [])
        d[key].append(n) # add number

     return d

#First I put values into the array transactions_NOT_sorted#
transactions_NOT_sorted.append(int(round(amount)))

#Then I sort the values into bins of regular sizes. transaction_sorted is a list#
transactions_sorted = inRegularIntervals(transactions_NOT_sorted,10)

#count items for each bin
for key, value in transactions_sorted.items():
        count_items = len([item for item in value if item])
               if count_items > 0:
                    data_for_plot[key]=count_items

I need a faster version of this. Should I use threading or multiprocessing?


问:
DatabaseError when trying to print all flatpages in Django template
I have a Django app that I have just added flatpages to. The issue I am running into is printing out the list of all flatpages that I have created. The reason I want to do this is so that I can print them out in a header navigation template so that they will appear automatically as I create/remove them. Else I would manually have to update the html file to add a new link.

I have this added in my views.py

```<code>urlpatterns += [
    re_path(r'^(?P<url>.*/)$', views.flatpage),
]
</code>```

Right now I am using the flatpages default template as my test file.

Error:

```<code>DatabaseError at /aaa/
No exception message supplied
Request Method: GET
Request URL:    http://214.191.20.123/aaa/
Django Version: 3.2
Exception Type: DatabaseError
Exception Location: /home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute
Python Executable:  /home/django/parser/venv/bin/python
Python Version: 3.8.10
Python Path:
['/home/django/parser',
 '/home/django/parser/venv/bin',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/django/parser/venv/lib/python3.8/site-packages']
Server time:    Sat, 07 Jan 2023 22:01:23 +0000
</code>```

Error:

```<code>Environment:

Request Method: GET
Request URL: http://214.191.20.123/aaa/

Django Version: 3.2
Python Version: 3.8.10
Installed Applications:
['adobeparser',
 'cbs_parser',
 'segment_parser',
 'parsers',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.flatpages']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware']

Template error:
In template /home/django/parser/parsers/templates/flatpages/default.html, error at line 25
   (Could not get exception message)
   15 :             <span class="sr-only">Toggle navigation</span>
   16 :             <span class="icon-bar"></span>
   17 :             <span class="icon-bar"></span>
   18 :             <span class="icon-bar"></span>
   19 :           </button>
   20 :           <a class="navbar-brand" href="#">Flatpages Example</a>
   21 :         </div>
   22 :         <div class="collapse navbar-collapse" id="menu">
   23 :           {% get_flatpages as flatpages %}
   24 :           <ul class="nav navbar-nav">
   25 :              {% for page in flatpages %}
   26 :               <li><a href="/pages{{ page.url }}">{{ page.title }}</a></li>
   27 :             {% endfor %}
   28 :           </ul>
   29 :         </div>
   30 :       </div>
   31 :     </nav>
   32 :     <div class="container">
   33 :       {{ flatpage.content }}
   34 :     </div>
   35 :   </body>

Traceback (most recent call last):
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse
    return handler(self, statement)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 933, in _select
    return SelectQuery(self.db, self.connection_properties, sm, self._params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 116, in __init__
    super().__init__(*args)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__
    self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 152, in parse
    self.where = WhereConverter(self, statement)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__
    self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 119, in parse
    self.op = WhereOp(
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 476, in __init__
    self.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate
    op.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate
    op.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 258, in evaluate
    self.rhs.negate()

The above exception ('NoneType' object has no attribute 'negate') was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute
    self.result = Query(
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__
    self._query = self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 885, in parse
    raise exe from e

The above exception (

    Keyword: None
    Sub SQL: None
    FAILED SQL: SELECT "django_flatpage"."id", "django_flatpage"."url", "django_flatpage"."title", "django_flatpage"."content", "django_flatpage"."enable_comments", "django_flatpage"."template_name", "django_flatpage"."registration_required" FROM "django_flatpage" INNER JOIN "django_flatpage_sites" ON ("django_flatpage"."id" = "django_flatpage_sites"."flatpage_id") WHERE ("django_flatpage_sites"."site_id" = %(0)s AND NOT "django_flatpage"."registration_required") ORDER BY "django_flatpage"."url" ASC
    Params: (5,)
    Version: 1.3.6) was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute
    raise db_exe from e

The above exception () was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/contrib/flatpages/views.py", line 45, in flatpage
    return render_flatpage(request, f)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/contrib/flatpages/views.py", line 69, in render_flatpage
    return HttpResponse(template.render({'flatpage': f}, request))
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 168, in render
    len_values = len(values)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1169, in execute_sql
    cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute
    raise db_exe from e

Exception Type: DatabaseError at /aaa/
Exception Value:
</code>```

I have tried removing everything from the default template so that when navigating to the flat page I only see in plain text whatever I have added to that page from the admin panel. Then I put the bare minimum in the default page

```<code>{% load flatpages %}
{% get_flatpages as flatpages %}
<ul>
    {% for page in flatpages %}
        <li><a href="{{ page.url }}">{{ page.title }}</a></li>
    {% endfor %}
</ul>
</code>```

After some reading I also seen that the {% get_flatpages as flatpages %} has to be in a block so I then tried...

```<code>{% load flatpages %}
{% block content %}
{% get_flatpages as flatpages %}
<ul>
    {% for page in flatpages %}
        <li><a href="{{ page.url }}">{{ page.title }}</a></li>
    {% endfor %}
</ul>
{% endblock %}
</code>```

Which still gives me the same error. I am not sure what I have to do or if this is possible with MongoDB? I just want to be able to add/update/remove pages in the admin panel without having to SSH to the server and update the navigation links to these pages.

Body:
I have a Django app that I have just added flatpages to. The issue I am running into is printing out the list of all flatpages that I have created. The reason I want to do this is so that I can print them out in a header navigation template so that they will appear automatically as I create/remove them. Else I would manually have to update the html file to add a new link.

I have this added in my views.py

urlpatterns += [
    re_path(r'^(?P<url>.*/)$', views.flatpage),
]

Right now I am using the flatpages default template as my test file.

Error:

DatabaseError at /aaa/
No exception message supplied
Request Method: GET
Request URL:    http://214.191.20.123/aaa/
Django Version: 3.2
Exception Type: DatabaseError
Exception Location: /home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute
Python Executable:  /home/django/parser/venv/bin/python
Python Version: 3.8.10
Python Path:
['/home/django/parser',
 '/home/django/parser/venv/bin',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/django/parser/venv/lib/python3.8/site-packages']
Server time:    Sat, 07 Jan 2023 22:01:23 +0000

Error:

Environment:

Request Method: GET
Request URL: http://214.191.20.123/aaa/

Django Version: 3.2
Python Version: 3.8.10
Installed Applications:
['adobeparser',
 'cbs_parser',
 'segment_parser',
 'parsers',
 'crispy_forms',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.flatpages']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware']

Template error:
In template /home/django/parser/parsers/templates/flatpages/default.html, error at line 25
   (Could not get exception message)
   15 :             Toggle navigation
   16 :
   17 :
   18 :
   19 :           </button>
   20 :           Flatpages Example
   21 :

   22 :

   23 :           {% get_flatpages as flatpages %}
   24 :

   25 :              {% for page in flatpages %}
   26 :
{{ page.title }}

   27 :             {% endfor %}
   28 :

   29 :

   30 :

   31 :
   32 :

   33 :       {{ flatpage.content }}
   34 :

   35 :

Traceback (most recent call last):
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse
    return handler(self, statement)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 933, in _select
    return SelectQuery(self.db, self.connection_properties, sm, self._params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 116, in __init__
    super().__init__(*args)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__
    self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 152, in parse
    self.where = WhereConverter(self, statement)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__
    self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 119, in parse
    self.op = WhereOp(
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 476, in __init__
    self.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate
    op.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate
    op.evaluate()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 258, in evaluate
    self.rhs.negate()

The above exception ('NoneType' object has no attribute 'negate') was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute
    self.result = Query(
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__
    self._query = self.parse()
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 885, in parse
    raise exe from e

The above exception (

    Keyword: None
    Sub SQL: None
    FAILED SQL: SELECT "django_flatpage"."id", "django_flatpage"."url", "django_flatpage"."title", "django_flatpage"."content", "django_flatpage"."enable_comments", "django_flatpage"."template_name", "django_flatpage"."registration_required" FROM "django_flatpage" INNER JOIN "django_flatpage_sites" ON ("django_flatpage"."id" = "django_flatpage_sites"."flatpage_id") WHERE ("django_flatpage_sites"."site_id" = %(0)s AND NOT "django_flatpage"."registration_required") ORDER BY "django_flatpage"."url" ASC
    Params: (5,)
    Version: 1.3.6) was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute
    raise db_exe from e

The above exception () was the direct cause of the following exception:
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/contrib/flatpages/views.py", line 45, in flatpage
    return render_flatpage(request, f)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/contrib/flatpages/views.py", line 69, in render_flatpage
    return HttpResponse(template.render({'flatpage': f}, request))
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 170, in render
    return self._render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 162, in _render
    return self.nodelist.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 938, in render
    bit = node.render_annotated(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/base.py", line 905, in render_annotated
    return self.render(context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/template/defaulttags.py", line 168, in render
    len_values = len(values)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 262, in __len__
    self._fetch_all()
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1169, in execute_sql
    cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/django/parser/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute
    raise db_exe from e

Exception Type: DatabaseError at /aaa/
Exception Value:

I have tried removing everything from the default template so that when navigating to the flat page I only see in plain text whatever I have added to that page from the admin panel. Then I put the bare minimum in the default page

{% load flatpages %}
{% get_flatpages as flatpages %}

    {% for page in flatpages %}

{{ page.title }}

    {% endfor %}

After some reading I also seen that the {% get_flatpages as flatpages %} has to be in a block so I then tried...

{% load flatpages %}
{% block content %}
{% get_flatpages as flatpages %}

    {% for page in flatpages %}

{{ page.title }}

    {% endfor %}

{% endblock %}

Which still gives me the same error. I am not sure what I have to do or if this is possible with MongoDB? I just want to be able to add/update/remove pages in the admin panel without having to SSH to the server and update the navigation links to these pages.


问:
how can I use a parameter to change a global variable with Javascript?
I'm using a CodeHS javascript Console sandbox for this. I have two variables, I'm trying to use a function that has a parameter. the parameter uses test++ (test is what I called my parameter) to add 1 to the parameter. What I want is for my variables to have one added by using a parameter.

here is what I've tried:

```<code>var num = 1;
var two = 3;
println(num);//the variables before
println(two);
update(num);//the function
update(two);
println(num);//the new variables
println(two);
function update(test){
    test++;
    println(test);
}
</code>```

the output:

```<code>1
3
2
4
1
3
</code>```

I'm trying to get:

```<code>1
3
2
4
2
4
</code>```

Body:
I'm using a CodeHS javascript Console sandbox for this. I have two variables, I'm trying to use a function that has a parameter. the parameter uses test++ (test is what I called my parameter) to add 1 to the parameter. What I want is for my variables to have one added by using a parameter.

here is what I've tried:

var num = 1;
var two = 3;
println(num);//the variables before
println(two);
update(num);//the function
update(two);
println(num);//the new variables
println(two);
function update(test){
    test++;
    println(test);
}

the output:

1
3
2
4
1
3

I'm trying to get:

1
3
2
4
2
4


问:
Use Expo only for personal device
I built an app with expo and React Native. I don't want to publish it on any app store - just load it on my iPhone. Can I manage that with  a free developer account?
I tried the expo run:ios command but it just installs the expo client on the phone.

If this is not possible can I use React Native to do that?

When I developed with Swift I could create a 7 day app and load it on my phone.

Title: Use Expo only for personal device


问:
History.js howto questions and behaviour in IE9 and FF3
I would like to use History.js but it doesn't work as expected and I'm not sure if I do it the right way...

Here is what I did:

```<code><!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<!-- jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>

<!-- jQuery ScrollTo Plugin -->
<script defer src="mySite/js/jquery.scrollto.min.js"></script>

<!-- JSON2 Plugin -->
<script type="text/javascript">if ( typeof window.JSON === 'undefined' ) { document.write('<script src="mySite/js/json2.js"><\/script>'); }</script>

<!-- jQuery ScrollTo Plugin -->
<script src="mySite/js/amplify.store.min.js"></script>

<!-- History.js -->
<script defer src="mySite/js/history.adapter.jquery.js"></script>
<script defer src="mySite/js/history.js"></script>
<script defer src="mySite/js/history.html4.js"></script>

<!-- ajaxify-mySite.js -->
<script defer src="mySite/js/ajaxify-mySite.js"></script>
</code>```

The ajaxify-mySite.js script is mostly the same as it is shown here

Thats whats going wrong:

In IE9 I get urls like "http://www.mySite.com/index.php/tools.html#index.php/contact.html?&_suid=478" (it should be "http://www.mySite.com/index.php#contact.html?&_suid=478" I think) and the content won't load the most time..

My FF3.6.21 loads all pages without using this script - is this normal behaviour?

Thanks!

ContentLicense: CC BY-SA 3.0

Body:
I would like to use History.js but it doesn't work as expected and I'm not sure if I do it the right way...

Here is what I did:

The ajaxify-mySite.js script is mostly the same as it is shown here

Thats whats going wrong:

In IE9 I get urls like "http://www.mySite.com/index.php/tools.html#index.php/contact.html?&_suid=478" (it should be "http://www.mySite.com/index.php#contact.html?&_suid=478" I think) and the content won't load the most time..

My FF3.6.21 loads all pages without using this script - is this normal behaviour?

Thanks!