问:
Docker: ERROR: relation "users" does not exist at character 13
I am trying to dockerize my app made with Python and FastAPI. I successfully created the images and container.

I tried to dockerize my postgres database it was done successfully until I try to create a new user. It throws the following error:

```<code> ERROR:  relation "users" does not exist at character 13
10 02:24:37.586 UTC [71] STATEMENT:  INSERT INTO users (email, password) VALUES ('sumitdadwal11@gmail.com', '$2b$12$VNya4IkKSGCuapswkJrh3u6POJVsdU2GSeIaV/ya4GprxNqEt5oim') RETURNING users.id
</code>```

It shows the following error in my FastAPI app image:

```<code> Traceback (most recent call last):

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context

    self.dialect.do_execute(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute

    cursor.execute(statement, parameters)

psycopg2.errors.UndefinedTable: relation "users" does not exist

LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...

                    ^

    The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 376, in run_asgi

    result = await app(self.scope, self.receive, self.send)

  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__

    return await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 208, in __call__

    await super().__call__(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__

    await self.middleware_stack(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__

    raise exc

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__

    await self.app(scope, receive, _send)

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 84, in __call__

    await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__

    raise exc

  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__

    await self.app(scope, receive, sender)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__

    await route.handle(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle

    await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 61, in app

    response = await func(request)

  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 226, in app

    raw_response = await run_endpoint_function(

  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 161, in run_endpoint_function

    return await run_in_threadpool(dependant.call, **values)

  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool

    return await anyio.to_thread.run_sync(func, *args)

  File "/usr/local/lib/python3.9/site-packages/anyio/to_thread.py", line 28, in run_sync

    return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,

  File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread

    return await future

  File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 754, in run

    result = context.run(func, *args)

  File "/usr/src/app/./app/routers/user.py", line 18, in create_user

    db.commit()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1428, in commit

    self._transaction.commit(_to_root=self.future)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 829, in commit

    self._prepare_impl()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 808, in _prepare_impl

    self.session.flush()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3345, in flush

    self._flush(objects)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3485, in _flush

    transaction.rollback(_capture_exception=True)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__

    compat.raise_(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_

    raise exception

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3445, in _flush

    flush_context.execute()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 456, in execute

    rec.execute(self)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 630, in execute

    util.preloaded.orm_persistence.save_obj(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 244, in save_obj

    _emit_insert_statements(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 1221, in _emit_insert_statements

    result = connection._execute_20(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20

    return meth(self, args_10style, kwargs_10style, execution_options)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection

    return connection._execute_clauseelement(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement

    ret = self._execute_context(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context

    self._handle_dbapi_exception(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception

    util.raise_(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_

    raise exception

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context

    self.dialect.do_execute(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute

    cursor.execute(statement, parameters)

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist

LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...

                    ^

[SQL: INSERT INTO users (email, password) VALUES (%(email)s, %(password)s) RETURNING users.id]

[parameters: {'email': 'sumitdadwal11@gmail.com', 'password': '$2b$12$5tcxP4b0hwVJpmHfyF10wuosYsdIxBkm1nhk1b1BZlLFZyCymodhK'}]

(Background on this error at: https://sqlalche.me/e/14/f405)
</code>```

This is my docker-compose.yml file:

```<code>   version: "3"
services:
  api:
    build: .
    ports:
      - 8000:8000
    # env_file:
    #      ./.env
    environment:
      - DATABASE_HOSTNAME=postgres
      - DATABASE_PORT=5432
      - DATABASE_PASSWORD=password123
      - DATABASE_NAME=fastapi
      - DATABASE_USERNAME=postgres
      - SECRET_KEY=secretkeysecretkeysecretkeysecretkey
      - ALGORITHM=HS256
      - ACCESS_TOKEN_EXPIRE_MINUTES=30
  postgres:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=password123
      - POSTGRES_DB=fastapi

    volumes:
      - postgres-db:/var/lib/postgresql/data

volumes:
  postgres-db:
</code>```

This is my Dockerfile:

```<code>  FROM python:3.9.9

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
</code>```

First I thought somethings wrong with my code but it is working fine when I am running it locally on my system.

Also, I am very new to docker.

I have tried different online solution but nothing worked out.

I think it getting connected to the wrong table named postgres but I cant find the reason behinf it.

UPDATE:
What I have noticed is that my postgress server has three databases:
-fastapi
-fastapi-project

postgres
fastapi is the one i want to connect to but i think it is getting connected to the postgres one and I dont remember creating that database.
Also the postgres database has no tables so it makes sense that it cannot find the user table.
But the question is how do I change databases?

Please let me know if you need any additional information.

Thanks in advance!

答:
I ran into the same problem following Sanjeev's tutorial. Given your settings, you are connecting to the right db, the issue is that it has no tables. This can be solved via Alembic.

In your docker-compose.yml, under api: add the line:

command: bash -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"
```
<p>That's it!</p>
<p>To check that the tables have been successfully created, open a terminal in your project folder and do the following:</p>
<ul>
<li><p>Run docker compose</p>
```docker-compose up -d
```
</li>
<li><p>Find the pg container name, in your case it should be something like <code>fastapi-postgres-1</code>, then start a bash session into your pg container</p>
```docker ps
docker exec -it fastapi-postgres-1 bash
```
</li>
<li><p>From here, access <code>psql</code> and find your db name, in your case it should be <code>fastapi</code></p>
```su - postgres
psql
\l
```
</li>
<li><p>Access your db and check that the tables have been created</p>
```\c fastapi
\dt
```
</li>
</ul>
<p>If result is something like this, you're good to go.</p>
```              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | alembic_version | table | postgres
 public | posts           | table | postgres
 public | users           | table | postgres
 public | votes           | table | postgres
(4 rows)
```

Body:
I am trying to dockerize my app made with Python and FastAPI. I successfully created the images and container.

I tried to dockerize my postgres database it was done successfully until I try to create a new user. It throws the following error:

 ERROR:  relation "users" does not exist at character 13
10 02:24:37.586 UTC [71] STATEMENT:  INSERT INTO users (email, password) VALUES ('sumitdadwal11@gmail.com', '$2b$12$VNya4IkKSGCuapswkJrh3u6POJVsdU2GSeIaV/ya4GprxNqEt5oim') RETURNING users.id

It shows the following error in my FastAPI app image:

 Traceback (most recent call last):

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context

    self.dialect.do_execute(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute

    cursor.execute(statement, parameters)

psycopg2.errors.UndefinedTable: relation "users" does not exist

LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...

                    ^

    The above exception was the direct cause of the following exception:

Traceback (most recent call last):

  File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 376, in run_asgi

    result = await app(self.scope, self.receive, self.send)

  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__

    return await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 208, in __call__

    await super().__call__(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__

    await self.middleware_stack(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__

    raise exc

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__

    await self.app(scope, receive, _send)

  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 84, in __call__

    await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__

    raise exc

  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__

    await self.app(scope, receive, sender)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__

    await route.handle(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle

    await self.app(scope, receive, send)

  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 61, in app

    response = await func(request)

  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 226, in app

    raw_response = await run_endpoint_function(

  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 161, in run_endpoint_function

    return await run_in_threadpool(dependant.call, **values)

  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 39, in run_in_threadpool

    return await anyio.to_thread.run_sync(func, *args)

  File "/usr/local/lib/python3.9/site-packages/anyio/to_thread.py", line 28, in run_sync

    return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,

  File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread

    return await future

  File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 754, in run

    result = context.run(func, *args)

  File "/usr/src/app/./app/routers/user.py", line 18, in create_user

    db.commit()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 1428, in commit

    self._transaction.commit(_to_root=self.future)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 829, in commit

    self._prepare_impl()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 808, in _prepare_impl

    self.session.flush()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3345, in flush

    self._flush(objects)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3485, in _flush

    transaction.rollback(_capture_exception=True)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__

    compat.raise_(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_

    raise exception

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 3445, in _flush

    flush_context.execute()

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 456, in execute

    rec.execute(self)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/unitofwork.py", line 630, in execute

    util.preloaded.orm_persistence.save_obj(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 244, in save_obj

    _emit_insert_statements(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/persistence.py", line 1221, in _emit_insert_statements

    result = connection._execute_20(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1614, in _execute_20

    return meth(self, args_10style, kwargs_10style, execution_options)

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection

    return connection._execute_clauseelement(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1481, in _execute_clauseelement

    ret = self._execute_context(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1845, in _execute_context

    self._handle_dbapi_exception(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2026, in _handle_dbapi_exception

    util.raise_(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_

    raise exception

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1802, in _execute_context

    self.dialect.do_execute(

  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 719, in do_execute

    cursor.execute(statement, parameters)

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist

LINE 1: INSERT INTO users (email, password) VALUES ('sumitdadwal11@g...

                    ^

[SQL: INSERT INTO users (email, password) VALUES (%(email)s, %(password)s) RETURNING users.id]

[parameters: {'email': 'sumitdadwal11@gmail.com', 'password': '$2b$12$5tcxP4b0hwVJpmHfyF10wuosYsdIxBkm1nhk1b1BZlLFZyCymodhK'}]

(Background on this error at: https://sqlalche.me/e/14/f405)

This is my docker-compose.yml file:

   version: "3"
services:
  api:
    build: .
    ports:
      - 8000:8000
    # env_file:
    #      ./.env
    environment:
      - DATABASE_HOSTNAME=postgres
      - DATABASE_PORT=5432
      - DATABASE_PASSWORD=password123
      - DATABASE_NAME=fastapi
      - DATABASE_USERNAME=postgres
      - SECRET_KEY=secretkeysecretkeysecretkeysecretkey
      - ALGORITHM=HS256
      - ACCESS_TOKEN_EXPIRE_MINUTES=30
  postgres:
    image: postgres
    environment:
      - POSTGRES_PASSWORD=password123
      - POSTGRES_DB=fastapi

    volumes:
      - postgres-db:/var/lib/postgresql/data

volumes:
  postgres-db:

This is my Dockerfile:

  FROM python:3.9.9

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

First I thought somethings wrong with my code but it is working fine when I am running it locally on my system.

Also, I am very new to docker.

I have tried different online solution but nothing worked out.

I think it getting connected to the wrong table named postgres but I cant find the reason behinf it.

UPDATE:
What I have noticed is that my postgress server has three databases:
-fastapi
-fastapi-project

postgres
fastapi is the one i want to connect to but i think it is getting connected to the postgres one and I dont remember creating that database.
Also the postgres database has no tables so it makes sense that it cannot find the user table.
But the question is how do I change databases?

Please let me know if you need any additional information.

Thanks in advance!

Body:
I ran into the same problem following Sanjeev's tutorial. Given your settings, you are connecting to the right db, the issue is that it has no tables. This can be solved via Alembic.

In your docker-compose.yml, under api: add the line:

command: bash -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"

That's it!

To check that the tables have been successfully created, open a terminal in your project folder and do the following:

Run docker compose

docker-compose up -d

Find the pg container name, in your case it should be something like fastapi-postgres-1, then start a bash session into your pg container

docker ps
docker exec -it fastapi-postgres-1 bash

From here, access psql and find your db name, in your case it should be fastapi

su - postgres
psql
\l

Access your db and check that the tables have been created

\c fastapi
\dt

If result is something like this, you're good to go.

              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | alembic_version | table | postgres
 public | posts           | table | postgres
 public | users           | table | postgres
 public | votes           | table | postgres
(4 rows)


来源: stackexchange

问:
How can I get user's group memberships included in the id token
I have an application that can successfully authenticate users through a B2C user flow policy and get an ID token in a JWT.

How can I update the user flow policy, so I get the user’s group membership as part of the ID token?

A link to documentation or concept would be a great help.

答:
On Azure B2C , it is not possible to get the user's groups membership in the idToken unfortunately. The mentioned above  example by @rbrayb is using Custom policies with Identity Experience Framework , which is one way to go if you need to add the group memberships to the idToken.

Another way to do this is Manually call the Graph API ( using msal library/ Microsoft identity Client NUGET ) , with the objectId of the connected user and an access token in order to get the groups to which the user belong : In this case you will create a group for each role , affect the users to the right groups based on their role, by finding the users group , u know what's his role , here is an example of implementing this kind of authorization on .Net5 web api and web App.

ContentLicense: CC BY-SA 4.0


问:
Flutter project debugging is not Run in my vivo phone
I am facing a difficult problem now. Right now I can't do a flutter debug on my real Vivo-v2020 phone device. I've tried everything possible, but I still get this error and can't debug. However, the installed app works properly.
In my device everything is okay, Developer Mode ON, USB Debugging mode also ON
Any solution to this? Please help me... This is very important for me.

log:

```<code>Launching lib\main.dart on V2022 in debug mode...
Running Gradle task 'assembleDebug'...
Parameter format not correct -
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
I/flutter ( 4243): Observatory listening on ************************************
</code>```

答:
I also had this problem with my vivo-v2025. But I solved the issue by following a simple step.

First, you just run the app on your phone using debug mode as usual.
Then you will see an error as shown below:

```<code>  "   Launching lib/main.dart on V2025 in debug mode...
      ✓  Built build/app/outputs/flutter-apk/app-debug.apk.
      I/flutter (22675): Observatory listening on***************** "
</code>```

After this, you just TERMINATE the program and start a fresh new run. The app will open. It worked in my case.

Posting an output image here .

Body:
I am facing a difficult problem now. Right now I can't do a flutter debug on my real Vivo-v2020 phone device. I've tried everything possible, but I still get this error and can't debug. However, the installed app works properly.
In my device everything is okay, Developer Mode ON, USB Debugging mode also ON
Any solution to this? Please help me... This is very important for me.

log:

Launching lib\main.dart on V2022 in debug mode...
Running Gradle task 'assembleDebug'...
Parameter format not correct -
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
I/flutter ( 4243): Observatory listening on ************************************

Body:
I also had this problem with my vivo-v2025. But I solved the issue by following a simple step.

First, you just run the app on your phone using debug mode as usual.
Then you will see an error as shown below:

  "   Launching lib/main.dart on V2025 in debug mode...
      ✓  Built build/app/outputs/flutter-apk/app-debug.apk.
      I/flutter (22675): Observatory listening on***************** "

After this, you just TERMINATE the program and start a fresh new run. The app will open. It worked in my case.

Posting an output image here .


问:
Check if two hours are between a time range
I allow myself to ask my question here, because after several hours of trying to make my code work, it still does not work!
So I would simply like to check if two times (For example 8:00 and 10:00) are included between a time range (For example between 8:00 and 9:00). I have already tried several combinations, it seems to work from time to time, but when I check if 9:00 and 10:00 is between 8:00 and 9:00, it returns that the time is not included in the time slot when it is supposed to be!
Here is my code for the moment: (all data has been transformed into strtotime())

```<code>if ((($hdebut >= $ihdebutcours) && ($hdebut <= $ihfincours)) && (($hfin >= $ihdebutcours) && ($hfin >= $ihfincours))) {
    $f++;
}
</code>```

For example :

$hdebut = 9:00

$hfin = 11:15

$ihdebutcours = 9:00

$ihfincours = 10:00

Thank you very much to the people who will help me, it will help me enormously to continue my project, and sorry for my bad English! Good day to you !

答:
I just found the problem! It was actually the operator! I changed it to "<" instead of "<="! Thank you all for your messages, and again sorry to have disturbed you! Good day to you !</p>
```<code>($hdebut <= $ihdebutcours AND $ihdebutcours < $hfin) OR ($hdebut < $ihfincours AND $ihfincours <= $hfin)
</code>```

Body:
I allow myself to ask my question here, because after several hours of trying to make my code work, it still does not work!
So I would simply like to check if two times (For example 8:00 and 10:00) are included between a time range (For example between 8:00 and 9:00). I have already tried several combinations, it seems to work from time to time, but when I check if 9:00 and 10:00 is between 8:00 and 9:00, it returns that the time is not included in the time slot when it is supposed to be!
Here is my code for the moment: (all data has been transformed into strtotime())

if ((($hdebut >= $ihdebutcours) && ($hdebut <= $ihfincours)) && (($hfin >= $ihdebutcours) && ($hfin >= $ihfincours))) {
    $f++;
}

For example :

$hdebut = 9:00

$hfin = 11:15

$ihdebutcours = 9:00

$ihfincours = 10:00

Thank you very much to the people who will help me, it will help me enormously to continue my project, and sorry for my bad English! Good day to you !

Body:
I just found the problem! It was actually the operator! I changed it to "<" instead of "<="! Thank you all for your messages, and again sorry to have disturbed you! Good day to you !

($hdebut <= $ihdebutcours AND $ihdebutcours < $hfin) OR ($hdebut < $ihfincours AND $ihfincours <= $hfin)


问:
How to do code coverage test for an ASP.NET WebForms app using Visual Studio 2010? Is Generic Test used?
I am using Visual Studio 2010 Ultimate. I want to find out which methods not being executed in the app. I read this tutorial for doing a code coverage test for an .exe file. I want to do the same for an ASP.NET WebForms app. What I am missing is if I need to create a Generic Test, what is to be entered in the different fields in the screen below, specially the wrapper program in the first field?

I will be clicking around the app to cover as many methods as I can.

UPDATE:

I added a winForm project and made its .exe file the wrapper. In the Code Coverage configuration I added the website project as an artifact to instrument (path = http://...). The code coverage results didn't show anything. I also added the web project assembly at one time. After trying different combinations on what artifacts to instrument, the code coverage results either showed nothing or showed results for the .exe only (If I added the winForm project). I also Googled around. I am not sure anymore if VS 2010 can code cover ASP.NET apps without using unit tests.

答: I used VsInstr.exe and VSPerfCmd.exe to accomplish what I needed.</p>

ContentLicense: CC BY-SA 3.0


问:
Detect query type( query, mutation, subscription) in graphql-java
Is there a way to detect the query type query , mutation or subscription , preferably without executing the query.

For example:

```<code>ExecutionInput executionInput = ExecutionInput
    .newExecutionInput()
    .query("subscription Test{test}")
    .build();
</code>```

Is it possible to detect that this is a subscription request? subscription Test{test} without executing the query?

Something like executionInput.isSubscription()

答:
You can use ParseAndValidate to parse the ExecutionInput :

ParseAndValidateResult parseResult = ParseAndValidate.parse(executionInput);
        parseResult.getDocument().getDefinitionsOfType(OperationDefinition.class)
        .forEach(d->{
            System.out.println(d.getOperation());
        });
```

The idea is to get the list of the OperationDefinition from Document (i.e query parsing result) and get its Operation type (an enum which has value QUERY,MUTATION,SUBSCRIPTION) from OperationDefinition.

P.S. I test with graphql-java v17

Body:
Is there a way to detect the query type query , mutation or subscription , preferably without executing the query.

For example:

ExecutionInput executionInput = ExecutionInput
    .newExecutionInput()
    .query("subscription Test{test}")
    .build();

Is it possible to detect that this is a subscription request? subscription Test{test} without executing the query?

Something like executionInput.isSubscription()

Body:
You can use ParseAndValidate to parse the ExecutionInput :

ParseAndValidateResult parseResult = ParseAndValidate.parse(executionInput);
        parseResult.getDocument().getDefinitionsOfType(OperationDefinition.class)
        .forEach(d->{
            System.out.println(d.getOperation());
        });

The idea is to get the list of the OperationDefinition from Document (i.e query parsing result) and get its Operation type (an enum which has value QUERY,MUTATION,SUBSCRIPTION) from OperationDefinition.

P.S. I test with graphql-java v17


问:
How Can I Make the Go HTTP Client NOT Follow Redirects Automatically?
I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.

I'm trying to use my Go script to grab the HTTP Location header for later processing.

Here's what I'm currently doing to achieve this functionality:

```<code>package main

import (
        "errors"
        "fmt"
        "io/ioutil"
        "net/http"
)

var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"

func noRedirect(req *http.Request, via []*http.Request) error {
        return errors.New("Don't redirect!")
}

func main() {

        client := &http.Client{
            CheckRedirect: noRedirect
        }
        req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
        req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)

        resp, err := client.Do(req)

        // If we get here, it means one of two things: either this http request
        // actually failed, or we got an http redirect response, and should process it.
        if err != nil {
            if resp.StatusCode == 302 {
                fmt.Println("got redirect")
            } else {
                panic("HTTP request failed.")
            }
        }
        defer resp.Body.Close()

}
</code>```

This feels like a bit of a hack to me. By overriding the http.Client's CheckRedirect function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).

I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.

Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling?

答:
As an addition of top rated answer,

You can control the particle size

```<code>func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
    err := fmt.Errorf("redirect policy: stopped after %d times", times)
    if len(via) >= times {
        return err
    }
    return nil
}

...

    client := &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return myCheckRedirect(req, via, 1)
        },
    }
</code>```

ref: https://golangbyexample.com/http-no-redirect-client-golang/

Body:
I'm currently writing some software in Go that interacts with a REST API. The REST API endpoint I'm trying to query returns an HTTP 302 redirect along with an HTTP Location header, pointing to a resource URI.

I'm trying to use my Go script to grab the HTTP Location header for later processing.

Here's what I'm currently doing to achieve this functionality:

package main

import (
        "errors"
        "fmt"
        "io/ioutil"
        "net/http"
)

var BASE_URL = "https://api.example.com/v1"
var STORMPATH_API_KEY_ID = "xxx"
var STORMPATH_API_KEY_SECRET = "xxx"

func noRedirect(req *http.Request, via []*http.Request) error {
        return errors.New("Don't redirect!")
}

func main() {

        client := &http.Client{
            CheckRedirect: noRedirect
        }
        req, err := http.NewRequest("GET", BASE_URL+"/tenants/current", nil)
        req.SetBasicAuth(EXAMPLE_API_KEY_ID, EXAMPLE_API_KEY_SECRET)

        resp, err := client.Do(req)

        // If we get here, it means one of two things: either this http request
        // actually failed, or we got an http redirect response, and should process it.
        if err != nil {
            if resp.StatusCode == 302 {
                fmt.Println("got redirect")
            } else {
                panic("HTTP request failed.")
            }
        }
        defer resp.Body.Close()

}

This feels like a bit of a hack to me. By overriding the http.Client's CheckRedirect function, I'm essentially forced to treat HTTP redirects like errors (which they aren't).

I've seen several other places suggesting to use an HTTP transport instead of an HTTP client -- but I'm not sure how to make this work since I need the HTTP Client as I need to use HTTP Basic Auth to communicate with this REST API.

Can any of you tell me a way to make HTTP requests with Basic Authentication -- while not following redirects -- that doesn't involve throwing errors and error handling?

Body:
As an addition of top rated answer,

You can control the particle size

func myCheckRedirect(req *http.Request, via []*http.Request, times int) error {
    err := fmt.Errorf("redirect policy: stopped after %d times", times)
    if len(via) >= times {
        return err
    }
    return nil
}

...

    client := &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return myCheckRedirect(req, via, 1)
        },
    }

ref: https://golangbyexample.com/http-no-redirect-client-golang/


问:
Error: Failed to lookup view "users/register" in views directory
My app can not find a page from the views directory. I think I've setup the configuration correctly and other files are working fine in views but this one is not working.

```<code>Error: Failed to lookup view "users/register" in views directory "D:\NODE PROJECTS\MyBlog\views"
    at Function.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\response.js:1017:7)
    at file:///D:/NODE%20PROJECTS/MyBlog/src/routes/UserRouter.js:18:9
    at Layer.handle [as handle_request] (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:112:3)
</code>```

This is my path setup

```<code>app.engine('ejs', engine)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, '../templates/views'))
</code>```

And a call from router

```<code>UserRoter.get('/register', (req, res)=>{
    res.render('users/register', {title: 'Sign Up'})
})
</code>```

And this is the structure of views directory

答:
You have a bug in the third line of code, instead of:

```<code>app.set('views', path.join(__dirname, '../templates/views'))
</code>```

Should be:

```<code>app.set('views', path.join(__dirname, '/templates/views'))
</code>```

I mirrored your project (folder and file structure) and everything seems to be fine:-)

Folder & file structure :

app.js

```<code>const express = require("express");
const path = require("path");

const port = 3000;
const app = express();

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/templates/views"));

app.get("/", (req, res) => {
  res.render("index", { title: "Keep Calm and Do not stop coding!" });
});

app.get("/register", (req, res) => {
  res.render("users/register", { title: "Sign Up" });
});

app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});
</code>```

register.ejs

```<code><title><%= title %></title>
<h1>Register page works fine!</h1>
</code>```

output:

Tested with "ejs": "^3.1.6", "express": "^4.17.2", node 16.13.0

Body:
My app can not find a page from the views directory. I think I've setup the configuration correctly and other files are working fine in views but this one is not working.

Error: Failed to lookup view "users/register" in views directory "D:\NODE PROJECTS\MyBlog\views"
    at Function.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\response.js:1017:7)
    at file:///D:/NODE%20PROJECTS/MyBlog/src/routes/UserRouter.js:18:9
    at Layer.handle [as handle_request] (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:112:3)

This is my path setup

app.engine('ejs', engine)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, '../templates/views'))

And a call from router

UserRoter.get('/register', (req, res)=>{
    res.render('users/register', {title: 'Sign Up'})
})

And this is the structure of views directory

Body:
You have a bug in the third line of code, instead of:

app.set('views', path.join(__dirname, '../templates/views'))

Should be:

app.set('views', path.join(__dirname, '/templates/views'))

I mirrored your project (folder and file structure) and everything seems to be fine:-)

Folder & file structure :

app.js

const express = require("express");
const path = require("path");

const port = 3000;
const app = express();

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/templates/views"));

app.get("/", (req, res) => {
  res.render("index", { title: "Keep Calm and Do not stop coding!" });
});

app.get("/register", (req, res) => {
  res.render("users/register", { title: "Sign Up" });
});

app.listen(port, () => {
  console.log(`Server is  listening at http://localhost:${port}`);
});

register.ejs

<title><%= title %></title>
<h1>Register page works fine!</h1>

output:

Tested with "ejs": "^3.1.6", "express": "^4.17.2", node 16.13.0


问:
I need help getting the right command
I have a list of minions I need to know the OS I don't know the command to use my list. I see people using this command salt '*' grains.item os but I need something like this: salt "my list" grains.item OS

答:
It depends what kind of list you mean. There are multiple ways to target different minions.

salt -E 'minion1|minion2|minion3' grains.item os
```

Title: I need help getting the right command


问:
How to deserialize from Number value to int (error - no int/Int-argument constructor/factory method to deserialize from Number value)
I have two classes Flight and Ticket. One flight can has lots of tickets, so Ticket has foreign key flight_id.

Here is my database with tables flight and ticket.

Here is my json request (from Mozilla debugger), which I want to save in the database.

You can see flight_id parameter, but I can't save it to my database, I've got such an error:

at [Source: (PushbackInputStream); line: 1, column: 53] (through reference chain: dto.TicketDto["flight_id"]) DefaultHandlerExceptionResolver : Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance ofmodel.Flight(although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (199); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance ofmodel.Flight(although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value

Class Ticket:

```<code>@Entity
@Table(name = "ticket")
public class Ticket {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int ticket_id;

@Column(name = "place")
private int place;

@Column(name = "name")
private String name;

@Column(name = "surname")
private String surname;

@JsonDeserialize(using = CustomParameterDeserializer.class)
@ManyToOne(targetEntity = Flight.class)
@JoinColumn(name = "flight_id")
@JsonBackReference("flight")
private Flight flight_id;

// getters setters
// constructor
</code>```

Class TicketDto:

```<code>public class TicketDto {

private int ticket_id;

private int place;

private String name;

private String surname;

private Flight flight_id;

private Customer customer_id;

// getters setters
</code>```

My class Flight:

```<code>@Entity
@Table(name = "flight")
public class Flight {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int flight_id;

//

@OneToMany(mappedBy = "flight_id")
@JsonManagedReference("flight")
private List<Ticket> ticket;

// getters setters
</code>```

My class FlightDto:

```<code>public class FlightDto {
private int flight_id;

//

private List<TicketDto> ticket;

// getters setters
</code>```

Here is the class TicketServiceImpl with the method to save my Ticket:

```<code>@Service
public class TicketServiceImpl implements TicketService {

@Autowired
TicketRepository repository;

@Override
public Ticket save(TicketDto ticketDto) {
    Ticket ticket = new Ticket();
    ticket.setName(ticketDto.getName());
    ticket.setSurname(ticketDto.getSurname());
    ticket.setCustomer_id(ticketDto.getCustomer_id());
    ticket.setFlight_id(ticketDto.getFlight_id());
    ticket.setPlace(ticketDto.getPlace());

    return repository.save(ticket);
}
</code>```

My class ticket.ts in Angular:

```<code>export class Ticket {
ticket_id: number;
place: string;
customer_id: number;
flight_id: number;
name: string;
surname: string;
}
</code>```

答:
for this error you have two possibilities to add in your class:

```<code>@JsonProperty("flight_id") private void unpackNested(Integer flight_id) {
    this.flight = new Flight(); flight.setFlight_id(flight_id);
}
</code>```

but it's not the best way to do it because you don't modify a class like that without knowing the impacts behind it or doing all the necessary analyzes behind it

Or the second solution on the Data that you give to your DTO add this to you:

```<code>"flight_id":{
    "flight_id": id
}
</code>```

Body:
I have two classes Flight and Ticket. One flight can has lots of tickets, so Ticket has foreign key flight_id.

Here is my database with tables flight and ticket.

Here is my json request (from Mozilla debugger), which I want to save in the database.

You can see flight_id parameter, but I can't save it to my database, I've got such an error:

at [Source: (PushbackInputStream); line: 1, column: 53] (through reference chain: dto.TicketDto["flight_id"]) DefaultHandlerExceptionResolver : Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance ofmodel.Flight(although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (199); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance ofmodel.Flight(although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value

Class Ticket:

@Entity
@Table(name = "ticket")
public class Ticket {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int ticket_id;

@Column(name = "place")
private int place;

@Column(name = "name")
private String name;

@Column(name = "surname")
private String surname;

@JsonDeserialize(using = CustomParameterDeserializer.class)
@ManyToOne(targetEntity = Flight.class)
@JoinColumn(name = "flight_id")
@JsonBackReference("flight")
private Flight flight_id;

// getters setters
// constructor

Class TicketDto:

public class TicketDto {

private int ticket_id;

private int place;

private String name;

private String surname;

private Flight flight_id;

private Customer customer_id;

// getters setters

My class Flight:

@Entity
@Table(name = "flight")
public class Flight {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int flight_id;

//

@OneToMany(mappedBy = "flight_id")
@JsonManagedReference("flight")
private List<Ticket> ticket;

// getters setters

My class FlightDto:

public class FlightDto {
private int flight_id;

//

private List<TicketDto> ticket;

// getters setters

Here is the class TicketServiceImpl with the method to save my Ticket:

@Service
public class TicketServiceImpl implements TicketService {

@Autowired
TicketRepository repository;

@Override
public Ticket save(TicketDto ticketDto) {
    Ticket ticket = new Ticket();
    ticket.setName(ticketDto.getName());
    ticket.setSurname(ticketDto.getSurname());
    ticket.setCustomer_id(ticketDto.getCustomer_id());
    ticket.setFlight_id(ticketDto.getFlight_id());
    ticket.setPlace(ticketDto.getPlace());

    return repository.save(ticket);
}

My class ticket.ts in Angular:

export class Ticket {
ticket_id: number;
place: string;
customer_id: number;
flight_id: number;
name: string;
surname: string;
}

Body:
for this error you have two possibilities to add in your class:

@JsonProperty("flight_id") private void unpackNested(Integer flight_id) {
    this.flight = new Flight(); flight.setFlight_id(flight_id);
}

but it's not the best way to do it because you don't modify a class like that without knowing the impacts behind it or doing all the necessary analyzes behind it

Or the second solution on the Data that you give to your DTO add this to you:

"flight_id":{
    "flight_id": id
}


问:
how to move two Devex gridview columns together?
i am using devex gridview with c#, what i want is when i drag column to change its order, other column should to be moved next or before my moved column i used mouse up event and column position changed event i get a stack over flow exception
the could used is :

```<code> int index1 = gridView1.Columns["mail2"].VisibleIndex;
m_Mail1selection.CheckMarkColumn.VisibleIndex = index1;
int index2 = gridView1.Columns["mail1"].VisibleIndex;
m_Mail2selection.CheckMarkColumn.VisibleIndex = index2;
</code>```

any one know how to achieve that, the first columns is for mail address and the second is a Checkedit to mark the email is going to be sent or not and the ssame thing for mail2

thanks in advance to any help

regards

答:
Use the ColumnPositionChanged event, however you need to ensure you use conditions. The problem you have is you are setting the VisibleIndex regardless if you need to or not, as you keep changing the position of the column the event keeps firing and therefore puts the event into a eternal loop (which what a StackOverflow is)

Try something like this

```<code>    private void gridView1_ColumnPositionChanged(object sender, EventArgs e)
    {
        if ((colMail1Check.VisibleIndex - colMail1.VisibleIndex) != 1)
        {
            colMail1Check.VisibleIndex = colMail1.VisibleIndex + 1;
        }
        if ((colMail2Check.VisibleIndex - colMail2.VisibleIndex) != 1)
        {
            colMail2Check.VisibleIndex = colMail2.VisibleIndex + 1;
        }
    }
</code>```

What this will do is check if the Check column is next to its "main" column and if not adjust the VisibleIndex to be next to the main column. This will also handle if someone drags the column in between the two columns (ie, you drag the Mail2 column in between the Mail1 and Mail1Check columns, as the Mail2Check will be moved next to Mail2 and Mail1Check will be moved beside the Mail1 again, ensuring it is always beside the column.

Hope this helps

Body:
i am using devex gridview with c#, what i want is when i drag column to change its order, other column should to be moved next or before my moved column i used mouse up event and column position changed event i get a stack over flow exception
the could used is :

 int index1 = gridView1.Columns["mail2"].VisibleIndex;
m_Mail1selection.CheckMarkColumn.VisibleIndex = index1;
int index2 = gridView1.Columns["mail1"].VisibleIndex;
m_Mail2selection.CheckMarkColumn.VisibleIndex = index2;

any one know how to achieve that, the first columns is for mail address and the second is a Checkedit to mark the email is going to be sent or not and the ssame thing for mail2

thanks in advance to any help

regards

Body:
Use the ColumnPositionChanged event, however you need to ensure you use conditions. The problem you have is you are setting the VisibleIndex regardless if you need to or not, as you keep changing the position of the column the event keeps firing and therefore puts the event into a eternal loop (which what a StackOverflow is)

Try something like this

    private void gridView1_ColumnPositionChanged(object sender, EventArgs e)
    {
        if ((colMail1Check.VisibleIndex - colMail1.VisibleIndex) != 1)
        {
            colMail1Check.VisibleIndex = colMail1.VisibleIndex + 1;
        }
        if ((colMail2Check.VisibleIndex - colMail2.VisibleIndex) != 1)
        {
            colMail2Check.VisibleIndex = colMail2.VisibleIndex + 1;
        }
    }

What this will do is check if the Check column is next to its "main" column and if not adjust the VisibleIndex to be next to the main column. This will also handle if someone drags the column in between the two columns (ie, you drag the Mail2 column in between the Mail1 and Mail1Check columns, as the Mail2Check will be moved next to Mail2 and Mail1Check will be moved beside the Mail1 again, ensuring it is always beside the column.

Hope this helps


问:
How do I update the "board" variable's array's so that the turns of X and O alternate in turns? Btw, this is a Tic Tac Toe Game

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    } else {
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    } else {
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    } else {
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    } else {
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    } else {
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    } else {
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    } else {
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    } else {
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}</code>```

        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">

```
</div>
</div>
</p>
<p>The function turnMove is determining what move it is in and using this allows the addEventListener to determine if the innerHTML and splice will add "X" or "O" to the div and board arrays.</p>
<p>How can I alternate the "X"s and "O"s? I need to update the board "state." How do I do that?</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>let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

// This code is applicable for the 9 squares.
// square2, square2, and so on...

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}</code>```

答:
Here's my way to fix your problem.

1. Edit your turnMove()

You want to increase the turns every time a square is clicked on. It could be very simple, like this:

let turns = 0;
const turnMove = () => turns++;
```
<h3>2. Change the way you use <code>turnMove()</code></h3>
<p>You need to call turnMove as a function which is <code>turnMove()</code>, not <code>turnMove</code>. And <code>yourSquareElement</code> is a parameter from the on-click callback, you can change its name to whatever you want, but you can't change its value.</p>
<pre class="lang-js prettyprint-override"><code>square9.addEventListener("click", function(yourSquareElement){
    if((turnMove() % 2 === 0)){}
})
</code>```

Those are two things to solve your problem. One tip for you is to put variables in console.log() to see what value they're holding. If you do that, you will see yourSquareElement is actually an Event object no matter what name you give it.

See my demo here:

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    }else{
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    }else{
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    }else{
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    }else{
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    }else{
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    }else{
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    }else{
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    }else{
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    }else{
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

let turns = 0;
const turnMove = () => turns++;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}</code>```

        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">

```
</div>
</div>
</p>
<h3>Update: I refactored your script to make it even cleaner.</h3>
<p>I merged all the on-click events for each square into one, hope you find this useful. Your script now is:</p>
<pre class="lang-js prettyprint-override"><code>const board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
];

let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
    const col = index % 3;
    const row = Math.floor(index / 3);

    thisSquare.addEventListener('click', () => {
        const player = turnMove() % 2 === 0 ? "X" : "O";

        thisSquare.innerHTML = player;
        board[row][col] = player;

        console.log(row, col, board);
    });
});
</code>```

const board = [
  ["", "", ""],
  ["", "", ""],
  ["", "", ""]
];

let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
  const col = index % 3;
  const row = Math.floor(index / 3);

  thisSquare.addEventListener('click', () => {
    const player = turnMove() % 2 === 0 ? "X" : "O";

    thisSquare.innerHTML = player;
    board[row][col] = player;

    console.log(row, col, board);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#board {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 40%;
  height: 40vw;
  margin: auto;
  border: 2px solid black;
  text-align: center;
}

.square {
  background-color: aliceblue;
  border: 1px solid black;
}

* {
  font-size: 2.5rem;
}</code>```

  <title>Tic Tac Toe Game</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width-device-width initial-scale=1">

```

Body:
let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    } else {
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    } else {
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    } else {
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    } else {
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    } else {
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    } else {
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    } else {
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    } else {
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}

#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}

        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">

The function turnMove is determining what move it is in and using this allows the addEventListener to determine if the innerHTML and splice will add "X" or "O" to the div and board arrays.

How can I alternate the "X"s and "O"s? I need to update the board "state." How do I do that?

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

// This code is applicable for the 9 squares.
// square2, square2, and so on...

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}

Body:
Here's my way to fix your problem.

1. Edit your turnMove()

You want to increase the turns every time a square is clicked on. It could be very simple, like this:

let turns = 0;
const turnMove = () => turns++;

2. Change the way you use turnMove()

You need to call turnMove as a function which is turnMove(), not turnMove. And yourSquareElement is a parameter from the on-click callback, you can change its name to whatever you want, but you can't change its value.

square9.addEventListener("click", function(yourSquareElement){
    if((turnMove() % 2 === 0)){}
})

Those are two things to solve your problem. One tip for you is to put variables in console.log() to see what value they're holding. If you do that, you will see yourSquareElement is actually an Event object no matter what name you give it.

See my demo here:

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]

var square1 = document.getElementById("square1")
square1.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    }else{
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    }else{
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    }else{
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    }else{
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    }else{
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    }else{
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    }else{
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    }else{
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    }else{
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

let turns = 0;
const turnMove = () => turns++;

#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;

}

.square {
    background-color: aliceblue;
    border: 1px solid black;

}

* {
    font-size: 2.5rem;
}

<html>
    <head>
        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">
    </head>

<body>
    <div id="board">
        <div id="square1" class="square"></div>
        <div id="square2" class="square"></div>
        <div id="square3" class="square"></div>

        <div id="square4" class="square"></div>
        <div id="square5" class="square"></div>
        <div id="square6" class="square"></div>

        <div id="square7" class="square"></div>
        <div id="square8" class="square"></div>
        <div id="square9" class="square"></div>
        <script type="text/javascript" src="script.js"></script>
    </div>
</body>

</html>

Update: I refactored your script to make it even cleaner.

I merged all the on-click events for each square into one, hope you find this useful. Your script now is:

const board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
];

let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
    const col = index % 3;
    const row = Math.floor(index / 3);

    thisSquare.addEventListener('click', () => {
        const player = turnMove() % 2 === 0 ? "X" : "O";

        thisSquare.innerHTML = player;
        board[row][col] = player;

        console.log(row, col, board);
    });
});

const board = [
  ["", "", ""],
  ["", "", ""],
  ["", "", ""]
];

let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
  const col = index % 3;
  const row = Math.floor(index / 3);

  thisSquare.addEventListener('click', () => {
    const player = turnMove() % 2 === 0 ? "X" : "O";

    thisSquare.innerHTML = player;
    board[row][col] = player;

    console.log(row, col, board);
  });
});

#board {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 40%;
  height: 40vw;
  margin: auto;
  border: 2px solid black;
  text-align: center;
}

.square {
  background-color: aliceblue;
  border: 1px solid black;
}

* {
  font-size: 2.5rem;
}

<html>

<head>
  <title>Tic Tac Toe Game</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width-device-width initial-scale=1">
</head>

<body>
  <div id="board">
    <div id="square1" class="square"></div>
    <div id="square2" class="square"></div>
    <div id="square3" class="square"></div>

    <div id="square4" class="square"></div>
    <div id="square5" class="square"></div>
    <div id="square6" class="square"></div>

    <div id="square7" class="square"></div>
    <div id="square8" class="square"></div>
    <div id="square9" class="square"></div>
    <script type="text/javascript" src="script.js"></script>
  </div>
</body>

</html>


问:
React authentication isn't updating properly
when i have my functions in UserAuthContext.js my App isn't working properly. I try to login but the user is not directet to /browse as it should. But if i put the same code in app.js i can create and login with an account. I don't know what the reason is
here is the code
https://codesandbox.io/s/cool-euler-eicfr?file=/src/App.js
-not working version (above code belongs to this): https://not-working.netlify.app/
-working version where i have the code in app.js
https://netflix-clone-kasamtde.netlify.app/</p>

答:
You cannot use useAuthContext in a component that is not a child of UserAuthContextProvider. It will always return undefined

Easiest fix for this is to move UserAuthContextProvider into index.js:

```<code>// index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import App from './App';
import UserAuthContextProvider from "./components/Contexts/UserAuthContext.js";

render(
  <React.StrictMode>
    <UserAuthContextProvider><App /></UserAuthContextProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
</code>```

Body:
You cannot use useAuthContext in a component that is not a child of UserAuthContextProvider. It will always return undefined

Easiest fix for this is to move UserAuthContextProvider into index.js:

// index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import App from './App';
import UserAuthContextProvider from "./components/Contexts/UserAuthContext.js";

render(
  <React.StrictMode>
    <UserAuthContextProvider><App /></UserAuthContextProvider>
  </React.StrictMode>,
  document.getElementById('root')
);


问:
How can I, scrape data from a Javascript Content of a website?
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)
</code>```

And this, is the output which is displaying.

```<code>PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]
</code>```

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

答:
Final Answer - To this Question.

```<code>from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

# browser.get(
#     "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

browser.get(
    "https://www.nykaa.com/kay-beauty-hydrating-foundation/p/1229442?productId=1229442&pps=3&skuId=772975")

browser.execute_script("document.body.style.zoom='50%'")
browser.execute_script("document.body.style.zoom='100%'")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element(By.XPATH,
                                "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements(By.ID, 'content-details')

for desc in desc_data:
    para_details = browser.find_element(By.XPATH,
                                        '//*[@id="content-details"]/p[1]').text
    expiry = browser.find_element(By.XPATH,
                                  '//*[@id="content-details"]/p[2]').text
    country = browser.find_element(By.XPATH,
                                   '//*[@id="content-details"]/p[3]').text
    importer = browser.find_element(By.XPATH,
                                    '//*[@id="content-details"]/p[4]').text
    address = browser.find_element(By.XPATH,
                                   '//*[@id="content-details"]/p[5]').text
    # print(para_details, country, importer, address)
    print(f"{para_details} \n")
    print(f"{expiry} \n")
    print(f"{country} \n")
    print(f"{importer} \n")
    print(f"{address} \n")
</code>```

Body:
Actually, I am trying to fetch the content from the Product Description from the Nykaa Website.

URL:- https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502

This is the URL, and in the section of the Product description, clicking upon the 'Read More' button, at the end there is some text.

The Text which, I want to extract is :

Explore the entire range of Foundation available on Nykaa. Shop more
Nykaa Cosmetics products here.You can browse through the complete
world of Nykaa Cosmetics Foundation . Alternatively, you can also find
many more products from the Nykaa SkinShield Anti-Pollution Matte
Foundation range.

Expiry Date: 15 February 2024

Country of Origin: India

Name of Mfg / Importer / Brand: FSN E-commerce Ventures Pvt Ltd

Address of Mfg / Importer / Brand: 104 Vasan Udyog Bhavan Sun Mill
Compound Senapati Bapat Marg, Lower Parel, Mumbai City Maharashtra -
400013

After inspecting the page, when I, 'disable the javascript' all the content from 'product description' vanishes off. It means the content is loading dynamically with the help of Javascript.

I have used 'selenium' for this purpose. And This, is what I have tried.

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

browser.get(
    "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element_by_xpath(xpath="/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements_by_class_name('content-details')

for desc in desc_data:
    para_details = browser.find_element_by_xpath(
        './/*[@id="content-details"]/p[1]').text
    extra_details = browser.find_elements_by_xpath(
        './/*[@id="content-details"]/p[2]', './/*[@id="content-details"]/p[3]', './/*[@id="content-details"]/p[4]', './/*[@id="content-details"]/p[5]').text
    print(para_details, extra_details)

And this, is the output which is displaying.

PS E:\Web Scraping - Nykaa> python -u "e:\Web Scraping - Nykaa\scrape_nykaa_final.py"
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:16: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  browser = webdriver.Chrome(

DevTools listening on ws://127.0.0.1:1033/devtools/browser/097c0e11-6f2c-4742-a2b5-cd05bee72661
e:\Web Scraping - Nykaa\scrape_nykaa_final.py:28: DeprecationWarning: find_element_by_* commands are deprecated. Please use find_element() instead
  loadMore = browser.find_element_by_xpath(
[9312:4972:0206/110327.883:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
[9312:4972:0206/110328.019:ERROR:ssl_client_socket_impl.cc(996)] handshake failed; returned -1, SSL error code 1, net_error -101
Traceback (most recent call last):
  File "e:\Web Scraping - Nykaa\scrape_nykaa_final.py", line 28, in <module>
    loadMore = browser.find_element_by_xpath(
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 520, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
        Ordinal0 [0x00FDFDC3+2555331]
        Ordinal0 [0x00F777F1+2127857]
        Ordinal0 [0x00E72E08+1060360]
        Ordinal0 [0x00E9E49E+1238174]
        Ordinal0 [0x00E9E69B+1238683]
        Ordinal0 [0x00EC9252+1413714]
        Ordinal0 [0x00EB7B54+1342292]
        Ordinal0 [0x00EC75FA+1406458]
        Ordinal0 [0x00EB7976+1341814]
        Ordinal0 [0x00E936B6+1193654]
        Ordinal0 [0x00E94546+1197382]
        GetHandleVerifier [0x01179622+1619522]
        GetHandleVerifier [0x0122882C+2336844]
        GetHandleVerifier [0x010723E1+541697]
        GetHandleVerifier [0x01071443+537699]
        Ordinal0 [0x00F7D18E+2150798]
        Ordinal0 [0x00F81518+2168088]
        Ordinal0 [0x00F81660+2168416]
        Ordinal0 [0x00F8B330+2208560]
        BaseThreadInitThunk [0x76C9FA29+25]
        RtlGetAppContainerNamedObjectPath [0x77337A9E+286]
        RtlGetAppContainerNamedObjectPath [0x77337A6E+238]

Please, anyone help me getting this issue resolved, or any another specific piece of the code to write, which I am missing to fetch the text content from Product description. It would be a big help.

Thanks .

Body:
Final Answer - To this Question.

from msilib.schema import Error
from tkinter import ON
from turtle import goto
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
from random import randint
import pandas as pd
import requests
import csv

browser = webdriver.Chrome(
    r'C:\Users\paart\.wdm\drivers\chromedriver\win32\97.0.4692.71\chromedriver.exe')

browser.maximize_window()  # For maximizing window
browser.implicitly_wait(20)  # gives an implicit wait for 20 seconds

# browser.get(
#     "https://www.nykaa.com/nykaa-skinshield-matte-foundation/p/460512?productId=460512&pps=1&skuId=460502")

browser.get(
    "https://www.nykaa.com/kay-beauty-hydrating-foundation/p/1229442?productId=1229442&pps=3&skuId=772975")

browser.execute_script("document.body.style.zoom='50%'")
browser.execute_script("document.body.style.zoom='100%'")

# Creates "load more" button object.
browser.implicitly_wait(20)
loadMore = browser.find_element(By.XPATH,
                                "/html/body/div[1]/div/div[3]/div[1]/div[2]/div/div/div[2]")

loadMore.click()
browser.implicitly_wait(20)

desc_data = browser.find_elements(By.ID, 'content-details')

for desc in desc_data:
    para_details = browser.find_element(By.XPATH,
                                        '//*[@id="content-details"]/p[1]').text
    expiry = browser.find_element(By.XPATH,
                                  '//*[@id="content-details"]/p[2]').text
    country = browser.find_element(By.XPATH,
                                   '//*[@id="content-details"]/p[3]').text
    importer = browser.find_element(By.XPATH,
                                    '//*[@id="content-details"]/p[4]').text
    address = browser.find_element(By.XPATH,
                                   '//*[@id="content-details"]/p[5]').text
    # print(para_details, country, importer, address)
    print(f"{para_details} \n")
    print(f"{expiry} \n")
    print(f"{country} \n")
    print(f"{importer} \n")
    print(f"{address} \n")


问:
Scheduling function in Kivy with Clock
I'm having a trouble with updating my label informing which file is being downloaded with pytube in Kivy. What I am trying to get: While function DownloadPlaylist is working, when it is downloading files the program freezes and it is unable to update label. I want to create something like time.sleep, while program after each download of a file from playlist will stop for a moment and update the label or that it will update each second. I don't know how to pass title argument to the showtitle function, as well as I have trouble with calling the function in proper spot, I don't know on which activity (here it is on_touch_down, but it is surely wrong) to call it. Here is my code and thanks for help.</p>
```<code>class SecondWindow(Screen):

    def showtitle(self, title):
        self.ids.output_label.text= "Currently downloading: " + title
    def on_touch_down(self,touch):
        Clock.schedule_interval(self.showtitle)

    def checkbox_click(self,instance,value,mp3):
        if value == True:
            self.ids.output_label.text="You selected downloading MP3 file"
        else:
            self.ids.output_label.text="You selected downloading video file"

    def DownloadPlaylist(self):
        url=self.ids.url.text
        urldownload=baseurl
        my_playlist=Playlist(url)
        for video in my_playlist.videos:

            if(video.age_restricted==True):
                with open(today,"a") as f:
                    f.write(video.title)
                    f.write("\n")
                    f.close()
                pass

        if(self.ids.output_label.text=="You selected downloading MP3 file"):
            for video in my_playlist.videos:
                vid = video.streams.filter(only_audio=True).first()
                out_file = vid.download(urldownload)
                base, ext = os.path.splitext(out_file)
                new_file = base + '.mp3'
                os.rename(out_file, new_file)
        else:
            for video in my_playlist.videos:
                self.ids.output_label.text=f'Currently downloading: {video.title}'
                video.streams.get_highest_resolution().download(urldownload)
</code>```

答:
Difficult to be sure about what is happening with so little code provided, but it sounds like your DownloadPlaylist() method is being run on the main thread. The GUI of a Kivy app is updated on the main thread, but it cannot update when you are using the main thread for something else. The fix is to run your DownloadPlaylist() on another thread (See threading).

And you can pass arguments to methods in Clock.schedule.. methods by using partial, for example:

```<code>Clock.schedule_once(partial(self.showtitle, new_title))
</code>```

Title: Scheduling function in Kivy with Clock

Body:
I'm having a trouble with updating my label informing which file is being downloaded with pytube in Kivy. What I am trying to get: While function DownloadPlaylist is working, when it is downloading files the program freezes and it is unable to update label. I want to create something like time.sleep, while program after each download of a file from playlist will stop for a moment and update the label or that it will update each second. I don't know how to pass title argument to the showtitle function, as well as I have trouble with calling the function in proper spot, I don't know on which activity (here it is on_touch_down, but it is surely wrong) to call it. Here is my code and thanks for help.

class SecondWindow(Screen):

    def showtitle(self, title):
        self.ids.output_label.text= "Currently downloading: " + title
    def on_touch_down(self,touch):
        Clock.schedule_interval(self.showtitle)

    def checkbox_click(self,instance,value,mp3):
        if value == True:
            self.ids.output_label.text="You selected downloading MP3 file"
        else:
            self.ids.output_label.text="You selected downloading video file"

    def DownloadPlaylist(self):
        url=self.ids.url.text
        urldownload=baseurl
        my_playlist=Playlist(url)
        for video in my_playlist.videos:

            if(video.age_restricted==True):
                with open(today,"a") as f:
                    f.write(video.title)
                    f.write("\n")
                    f.close()
                pass

        if(self.ids.output_label.text=="You selected downloading MP3 file"):
            for video in my_playlist.videos:
                vid = video.streams.filter(only_audio=True).first()
                out_file = vid.download(urldownload)
                base, ext = os.path.splitext(out_file)
                new_file = base + '.mp3'
                os.rename(out_file, new_file)
        else:
            for video in my_playlist.videos:
                self.ids.output_label.text=f'Currently downloading: {video.title}'
                video.streams.get_highest_resolution().download(urldownload)

Body:
Difficult to be sure about what is happening with so little code provided, but it sounds like your DownloadPlaylist() method is being run on the main thread. The GUI of a Kivy app is updated on the main thread, but it cannot update when you are using the main thread for something else. The fix is to run your DownloadPlaylist() on another thread (See threading).

And you can pass arguments to methods in Clock.schedule.. methods by using partial, for example:

Clock.schedule_once(partial(self.showtitle, new_title))