问:
Why doesn't this code for doing string comparisons with user input compile?
```<code>#include <stdio.h>
int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male)
 || (marietal_status == unmarried && age >25 && sex == female))
    printf("insured");
    else
    printf("uninsured");
}
</code>```

ouput:

gcc /tmp/NaKWq16d9Q.c -lm
/tmp/NaKWq16d9Q.c: In function 'main':
/tmp/NaKWq16d9Q.c:10:28: error: 'married' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                            ^~~~~~~
/tmp/NaKWq16d9Q.c:10:28: note: each undeclared identifier is reported only once for each function it appears in
/tmp/NaKWq16d9Q.c:10:60: error: 'unmarried' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                            ^~~~~~~~~
/tmp/NaKWq16d9Q.c:10:92: error: 'male' undeclared (first use in this function)
   10 | ried) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                              ^~~~

/tmp/NaKWq16d9Q.c:10:152: error: 'female' undeclared (first use in this function)
   10 |  && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                                        ^~~~~~
```

答:
You're trying to compare a variable, the compiler is telling you that it is undeclared (which means it doesn't exist, you didn't set it like int age for example which is a declared variable).

When working with strings use double quotations, "

For example when initializing a string, char sex[15] = "female";

So your if condition should look like this:

```<code>if((strcmp(marietal_status, "married") == 0) || (strcmp(marietal_status, "unmarried") == 0) && age > 30 && (strcmp(sex, "male") == 0) || (strcmp(marietal_status, "unmarried") == 0) && age >25 && (strcmp(sex,  "female") == 0))
</code>```

Running it produces this:

```<code>./a.out
Age, Marietal status, sex of the driver : 23 unmarried male
uninsured
</code>```

Note that this means you expect the user to input exactly this, otherwise it won't be matched by the comparison. I'd recommend going through a C tutorial, https://www.tutorialspoint.com/cprogramming/index.htm

Edit:As someone else has already pointed out, string comparison in C is done by the strcmp function, don't forget to #include <string.h>

marietal_status == "unmarried" would work in some other language like Python or JavaScript

Body:
#include <stdio.h>
int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male)
 || (marietal_status == unmarried && age >25 && sex == female))
    printf("insured");
    else
    printf("uninsured");
}

ouput:

gcc /tmp/NaKWq16d9Q.c -lm
/tmp/NaKWq16d9Q.c: In function 'main':
/tmp/NaKWq16d9Q.c:10:28: error: 'married' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                            ^~~~~~~
/tmp/NaKWq16d9Q.c:10:28: note: each undeclared identifier is reported only once for each function it appears in
/tmp/NaKWq16d9Q.c:10:60: error: 'unmarried' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                            ^~~~~~~~~
/tmp/NaKWq16d9Q.c:10:92: error: 'male' undeclared (first use in this function)
   10 | ried) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                              ^~~~

/tmp/NaKWq16d9Q.c:10:152: error: 'female' undeclared (first use in this function)
   10 |  && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                                        ^~~~~~

Body:
You're trying to compare a variable, the compiler is telling you that it is undeclared (which means it doesn't exist, you didn't set it like int age for example which is a declared variable).

When working with strings use double quotations, "

For example when initializing a string, char sex[15] = "female";

So your if condition should look like this:

if((strcmp(marietal_status, "married") == 0) || (strcmp(marietal_status, "unmarried") == 0) && age > 30 && (strcmp(sex, "male") == 0) || (strcmp(marietal_status, "unmarried") == 0) && age >25 && (strcmp(sex,  "female") == 0))

Running it produces this:

./a.out
Age, Marietal status, sex of the driver : 23 unmarried male
uninsured

Note that this means you expect the user to input exactly this, otherwise it won't be matched by the comparison. I'd recommend going through a C tutorial, https://www.tutorialspoint.com/cprogramming/index.htm

Edit:As someone else has already pointed out, string comparison in C is done by the strcmp function, don't forget to #include <string.h>

marietal_status == "unmarried" would work in some other language like Python or JavaScript


来源: stackexchange

问:
C# WPF RichTextBox restrict text formatting to visible text
I have a RichTextBox displaying a FlowDocument that is large (>10k lines). I am attempting to apply text formatting to the entire Document. This is taking a while to complete.

Is there any way to focus the formatting on the visible parts of the Document only?

For Information: I am attempting to search through the contents of the RichTextBox and highlight all matching occurrences. The searching function is baised upon this one. I am using the following code to 'highlight' each match found.

```<code>protected void ColorTextRanges(Color color)
{
    foreach ( var textRange in locatedInstances )
    {
        if ( textRange != null )
        {
            textRange.ApplyPropertyValue( TextElement.BackgroundProperty, new SolidColorBrush( color ) );
        }
    }
}
</code>```

答:
Rather than create the brush in the loop create it outside and reuse it. Not going to be major but should help a little.  And you might test for the BackgroundProperty and only set it if it is wrong - this might make it slower but  if most of the document is already the right color then it should help.</p>

```<code>    protected void ColorTextRanges(Color color)
    {
        SolidColorBrush brush = new SolidColorBrush( color );
        foreach ( var textRange in locatedInstances )
        {
            if ( textRange != null )
            {
                textRange.ApplyPropertyValue( TextElement.BackgroundProperty,  brush);
            }
        }
   }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a RichTextBox displaying a FlowDocument that is large (>10k lines). I am attempting to apply text formatting to the entire Document. This is taking a while to complete.

Is there any way to focus the formatting on the visible parts of the Document only?

For Information: I am attempting to search through the contents of the RichTextBox and highlight all matching occurrences. The searching function is baised upon this one. I am using the following code to 'highlight' each match found.

protected void ColorTextRanges(Color color)
{
    foreach ( var textRange in locatedInstances )
    {
        if ( textRange != null )
        {
            textRange.ApplyPropertyValue( TextElement.BackgroundProperty, new SolidColorBrush( color ) );
        }
    }
}

Body:
Rather than create the brush in the loop create it outside and reuse it. Not going to be major but should help a little.  And you might test for the BackgroundProperty and only set it if it is wrong - this might make it slower but  if most of the document is already the right color then it should help.

    protected void ColorTextRanges(Color color)
    {
        SolidColorBrush brush = new SolidColorBrush( color );
        foreach ( var textRange in locatedInstances )
        {
            if ( textRange != null )
            {
                textRange.ApplyPropertyValue( TextElement.BackgroundProperty,  brush);
            }
        }
   }


问:
How to draw High-Precision-Numbers in chartjs
The number precision of my data is about 0.000001,

let's take some demo value between 0.01 and 0.02,

such as

```<code>[0.010001
,0.011111
,0.012222
,0.013333
,0.014444
,0.015555
,0.016666
,0.017777
,0.018888
,0.019999
];
</code>```

when I plot with these datasets,
and then hover to any points,
all of them tooltips with precision of only 0.001,
looks like all value has run with (original-data).toFixed(3),

but I want to show the real original value,
or more precision like 0.000001

Is there any way to set float precision in chartjs?

答:
You can adjust the label callback so you can return the raw value instead of the parsed value of chart.js like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [0.010005, 0.011111, 0.012222, 0.013333, 0.014444, 0.015555, 0.016666, 0.017777, 0.019888, 0.019999],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw}`)
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body></code>```

ContentLicense: CC BY-SA 4.0

Body:
The number precision of my data is about 0.000001,

let's take some demo value between 0.01 and 0.02,

such as

[0.010001
,0.011111
,0.012222
,0.013333
,0.014444
,0.015555
,0.016666
,0.017777
,0.018888
,0.019999
];

when I plot with these datasets,
and then hover to any points,
all of them tooltips with precision of only 0.001,
looks like all value has run with (original-data).toFixed(3),

but I want to show the real original value,
or more precision like 0.000001

Is there any way to set float precision in chartjs?

Body:
You can adjust the label callback so you can return the raw value instead of the parsed value of chart.js like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [0.010005, 0.011111, 0.012222, 0.013333, 0.014444, 0.015555, 0.016666, 0.017777, 0.019888, 0.019999],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (ctx) => (`${ctx.dataset.label}: ${ctx.raw}`)
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>


问:
Unable to start FastAPI server with postgresql using docker compose
I am creating a FastAPI server with simple CRUD functionalities with Postgresql as database. Everything works well in my local environment. However, when I tried to make it run in containers using docker-compose up, it failed. I was getting this error:

rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  | (Background on this error at: https://sqlalche.me/e/14/e3q8)
networks_lab2_rest_api_1 exited with code 1

```
<p>The directory structure:</p>
```├── Dockerfile
├── README.md
├── __init__.py
├── app
│   ├── __init__.py
│   ├── __pycache__
│   ├── crud.py
│   ├── database.py
│   ├── main.py
│   ├── models.py
│   ├── object_store
│   └── schemas.py
├── docker-compose.yaml
├── requirements.txt
├── tests
│   ├── __init__.py
│   ├── __pycache__
│   ├── assets
│   ├── test_create.py
│   ├── test_delete.py
│   ├── test_file.py
│   ├── test_get.py
│   ├── test_heartbeat.py
│   └── test_put.py
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pyvenv.cfg

```
<p>My <code>docker-compose.yaml</code></p>
<pre class="lang-yaml prettyprint-override"><code>version: "3"

services:
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      POSTGRES_USER: ${DATABASE_TYPE}
      POSTGRES_PASSWORD: ${DATABASE_PASSWORD}
      POSTGRES_DB: ${DATABASE_NAME}
    ports:
      - "5432:5432"

  rest_api:
    build: .
    command: uvicorn app.main:app --host 0.0.0.0
    env_file:
      - ./.env
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db

volumes:
  postgres_data:
</code>```

My Dockerfile for the fastAPI server (under ./app)

```<code>FROM python:3.8-slim-buster

RUN apt-get update \
    && apt-get -y install libpq-dev gcc \
    && pip install psycopg2

WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

COPY requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .
</code>```

My database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dotenv import load_dotenv
import os

# def create_connection_string():
#     load_dotenv()
#     db_type = os.getenv("DATABASE_TYPE")
#     username = os.getenv("DATABASE_USERNAME")
#     password = os.getenv("DATABASE_PASSWORD")
#     host = os.getenv("DATABASE_HOST")
#     port = os.getenv("DATABASE_PORT")
#     name = os.getenv("DATABASE_NAME")
#
#     return "{0}://{1}:{2}@{3}/{4}".format(db_type, username, password, host, name)

SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@db:5432/postgres"

engine = create_engine(
    SQLALCHEMY_DATABASE_URI
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

```
<p>My <code>main.py</code></p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Optional
import os, base64, shutil
from functools import wraps

from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Request, Header
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()
SECRET_KEY = os.getenv("SECRET")

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def check_request_header(x_token: str = Header(...)):
    if x_token != SECRET_KEY:
        raise HTTPException(status_code=401, detail="Unauthorized")

# endpoints
@app.get("/heartbeat", dependencies=[Depends(check_request_header)], status_code=200)
def heartbeat():
    return "The connection is up"

</code>```

A more complete log is:

Creating db_1 ... done
Creating rest_api_1 ... done
Attaching to db_1, rest_api_1
db_1        | The files belonging to this database system will be owned by user "postgres".
db_1        | This user must also own the server process.
db_1        |
db_1        | The database cluster will be initialized with locale "en_US.utf8".
db_1        | The default database encoding has accordingly been set to "UTF8".
db_1        | The default text search configuration will be set to "english".
db_1        |

...

db_1        | selecting dynamic shared memory implementation ... posix
db_1        | selecting default max_connections ... 100
db_1        | selecting default shared_buffers ... 128MB
db_1        | selecting default time zone ... UTC
db_1        | creating configuration files ... ok
db_1        | running bootstrap script ... ok
db_1        | performing post-bootstrap initialization ... sh: locale: not found
db_1        | 2021-09-29 18:13:35.027 UTC [31] WARNING:  no usable system locales were found
rest_api_1  | Traceback (most recent call last):
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 3240, in _wrap_pool_connect
rest_api_1  |     return fn()

...

rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 584, in connect
rest_api_1  |     return self.dbapi.connect(*cargs, **cparams)
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | psycopg2.OperationalError: could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  |
rest_api_1  | The above exception was the direct cause of the following exception:
rest_api_1  |
rest_api_1  | Traceback (most recent call last):
rest_api_1  |   File "/usr/local/bin/uvicorn", line 8, in <module>
rest_api_1  |     sys.exit(main())

...

est_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 584, in connect
rest_api_1  |     return self.dbapi.connect(*cargs, **cparams)
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  | (Background on this error at: https://sqlalche.me/e/14/e3q8)
rest_api_1 exited with code 1
db_1        | ok
db_1        | syncing data to disk ... ok
db_1        |
db_1        |
db_1        | Success. You can now start the database server using:
...

db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  starting PostgreSQL 13.4 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20210424) 10.3.1 20210424, 64-bit
db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1        | 2021-09-29 18:13:36.328 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1        | 2021-09-29 18:13:36.332 UTC [48] LOG:  database system was shut down at 2021-09-29 18:13:36 UTC
db_1        | 2021-09-29 18:13:36.336 UTC [1] LOG:  database system is ready to accept connections
```

I have gone through a very extensive search and read docs/tutorials about running FastAPI server and Postgresql with docker-compose, such as

https://testdriven.io/blog/fastapi-docker-traefik/
https://github.com/AmishaChordia/FastAPI-PostgreSQL-Docker/blob/master/FastAPI/docker-compose.yml
https://www.jeffastor.com/blog/pairing-a-postgresql-db-with-your-dockerized-fastapi-app

Their approach is the same as mine but it just keeps giving me this Connection refused Is the server running on host "db" (172.29.0.2) and accepting TCP/IP connections on port 5432? error message ...

Can anyone help me out here? Any help will be appreciated !!

答:
You could also handle retries by using Docker's restart mechanism. If you use max attempts and the right dela, you can make it so the DB will most likely be ready by the second try while preventing infinite restart.

```<code>rest_api:
    ...
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s # default
        max_attempts: 5
    ...
</code>```

Note that I'm not a Docker expert, but this seems like it better aligns with the containers as cattle instead of pets paradigm. Why add complexity to the application when the issue can be handled by existing functionality in a higher layer?

Body:
I am creating a FastAPI server with simple CRUD functionalities with Postgresql as database. Everything works well in my local environment. However, when I tried to make it run in containers using docker-compose up, it failed. I was getting this error:

rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  | (Background on this error at: https://sqlalche.me/e/14/e3q8)
networks_lab2_rest_api_1 exited with code 1

The directory structure:

├── Dockerfile
├── README.md
├── __init__.py
├── app
│   ├── __init__.py
│   ├── __pycache__
│   ├── crud.py
│   ├── database.py
│   ├── main.py
│   ├── models.py
│   ├── object_store
│   └── schemas.py
├── docker-compose.yaml
├── requirements.txt
├── tests
│   ├── __init__.py
│   ├── __pycache__
│   ├── assets
│   ├── test_create.py
│   ├── test_delete.py
│   ├── test_file.py
│   ├── test_get.py
│   ├── test_heartbeat.py
│   └── test_put.py
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pyvenv.cfg

My docker-compose.yaml

version: "3"

services:
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      POSTGRES_USER: ${DATABASE_TYPE}
      POSTGRES_PASSWORD: ${DATABASE_PASSWORD}
      POSTGRES_DB: ${DATABASE_NAME}
    ports:
      - "5432:5432"

  rest_api:
    build: .
    command: uvicorn app.main:app --host 0.0.0.0
    env_file:
      - ./.env
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db

volumes:
  postgres_data:

My Dockerfile for the fastAPI server (under ./app)

FROM python:3.8-slim-buster

RUN apt-get update \
    && apt-get -y install libpq-dev gcc \
    && pip install psycopg2

WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

COPY requirements.txt .
RUN pip install -r requirements.txt

# copy project
COPY . .

My database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dotenv import load_dotenv
import os

# def create_connection_string():
#     load_dotenv()
#     db_type = os.getenv("DATABASE_TYPE")
#     username = os.getenv("DATABASE_USERNAME")
#     password = os.getenv("DATABASE_PASSWORD")
#     host = os.getenv("DATABASE_HOST")
#     port = os.getenv("DATABASE_PORT")
#     name = os.getenv("DATABASE_NAME")
#
#     return "{0}://{1}:{2}@{3}/{4}".format(db_type, username, password, host, name)

SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@db:5432/postgres"

engine = create_engine(
    SQLALCHEMY_DATABASE_URI
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

My main.py

from typing import List, Optional
import os, base64, shutil
from functools import wraps

from fastapi import Depends, FastAPI, HTTPException, UploadFile, File, Request, Header
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()
SECRET_KEY = os.getenv("SECRET")

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def check_request_header(x_token: str = Header(...)):
    if x_token != SECRET_KEY:
        raise HTTPException(status_code=401, detail="Unauthorized")

# endpoints
@app.get("/heartbeat", dependencies=[Depends(check_request_header)], status_code=200)
def heartbeat():
    return "The connection is up"

A more complete log is:

Creating db_1 ... done
Creating rest_api_1 ... done
Attaching to db_1, rest_api_1
db_1        | The files belonging to this database system will be owned by user "postgres".
db_1        | This user must also own the server process.
db_1        |
db_1        | The database cluster will be initialized with locale "en_US.utf8".
db_1        | The default database encoding has accordingly been set to "UTF8".
db_1        | The default text search configuration will be set to "english".
db_1        |

...

db_1        | selecting dynamic shared memory implementation ... posix
db_1        | selecting default max_connections ... 100
db_1        | selecting default shared_buffers ... 128MB
db_1        | selecting default time zone ... UTC
db_1        | creating configuration files ... ok
db_1        | running bootstrap script ... ok
db_1        | performing post-bootstrap initialization ... sh: locale: not found
db_1        | 2021-09-29 18:13:35.027 UTC [31] WARNING:  no usable system locales were found
rest_api_1  | Traceback (most recent call last):
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 3240, in _wrap_pool_connect
rest_api_1  |     return fn()

...

rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 584, in connect
rest_api_1  |     return self.dbapi.connect(*cargs, **cparams)
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | psycopg2.OperationalError: could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  |
rest_api_1  | The above exception was the direct cause of the following exception:
rest_api_1  |
rest_api_1  | Traceback (most recent call last):
rest_api_1  |   File "/usr/local/bin/uvicorn", line 8, in <module>
rest_api_1  |     sys.exit(main())

...

est_api_1  |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 584, in connect
rest_api_1  |     return self.dbapi.connect(*cargs, **cparams)
rest_api_1  |   File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
rest_api_1  |     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
rest_api_1  | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
rest_api_1  |   Is the server running on host "db" (172.29.0.2) and accepting
rest_api_1  |   TCP/IP connections on port 5432?
rest_api_1  |
rest_api_1  | (Background on this error at: https://sqlalche.me/e/14/e3q8)
rest_api_1 exited with code 1
db_1        | ok
db_1        | syncing data to disk ... ok
db_1        |
db_1        |
db_1        | Success. You can now start the database server using:
...

db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  starting PostgreSQL 13.4 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20210424) 10.3.1 20210424, 64-bit
db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1        | 2021-09-29 18:13:36.325 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1        | 2021-09-29 18:13:36.328 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1        | 2021-09-29 18:13:36.332 UTC [48] LOG:  database system was shut down at 2021-09-29 18:13:36 UTC
db_1        | 2021-09-29 18:13:36.336 UTC [1] LOG:  database system is ready to accept connections

I have gone through a very extensive search and read docs/tutorials about running FastAPI server and Postgresql with docker-compose, such as

https://testdriven.io/blog/fastapi-docker-traefik/
https://github.com/AmishaChordia/FastAPI-PostgreSQL-Docker/blob/master/FastAPI/docker-compose.yml
https://www.jeffastor.com/blog/pairing-a-postgresql-db-with-your-dockerized-fastapi-app

Their approach is the same as mine but it just keeps giving me this Connection refused Is the server running on host "db" (172.29.0.2) and accepting TCP/IP connections on port 5432? error message ...

Can anyone help me out here? Any help will be appreciated !!

Body:
You could also handle retries by using Docker's restart mechanism. If you use max attempts and the right dela, you can make it so the DB will most likely be ready by the second try while preventing infinite restart.

rest_api:
    ...
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s # default
        max_attempts: 5
    ...

Note that I'm not a Docker expert, but this seems like it better aligns with the containers as cattle instead of pets paradigm. Why add complexity to the application when the issue can be handled by existing functionality in a higher layer?


问:
How to send unicode characters in subject using Drafts.send in Gmail API?
If a user has created a draft in the gmail web UI that contains Unicode characters in the subject, calling Draft.Send seems to not handle these unicode characters correctly.

You can test this by:

Create a draft in gmail with the subject "snowman ☃"

Call drafts.list to get the draft id in the API explorer (https://developers.google.com/gmail/api/v1/reference/users/drafts/list#try-it)

Call Drafts.send using that draft id in the api explorer (https://developers.google.com/gmail/api/v1/reference/users/drafts/send#try-it)

Goto Gmail web ui, then the sent folder, and see that the email was sent with a subject of "snowman: â˜ƒ"

Any workarounds for this?

答: Using NodeJs, here is what I got it working for sending Unicode Characters along with emoji signs. Details in this comment</p>


问:
How to use BeautifulSoup 4 to extract Tweet text?
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

```<code>import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)
</code>```

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

答:
Updated

This works fine for me

```<code>import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"
r = requests.get(link).text
soup = bs4.BeautifulSoup(r, "lxml")
tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})
dest = soup.find('a', {"class": "twitter-timeline-link u-hidden"})
dest.decompose()
content = tweet_text.text

print(content)
</code>```

Body:
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

Body:
Updated

This works fine for me

import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"
r = requests.get(link).text
soup = bs4.BeautifulSoup(r, "lxml")
tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})
dest = soup.find('a', {"class": "twitter-timeline-link u-hidden"})
dest.decompose()
content = tweet_text.text

print(content)


问:
How can I center a label in the middle of a panel in C#?
I am trying to make an Icon Generator Application in C#.
I have to panels, one that is in charge of the background colour (Border colour) and the other as foreground colour (Fill colour). I also have a label in the middle of the forgeground colour panel (Fill colour) see screenshots designer, application ran for first time, changed code using textbox and button (see arrow in screenshot)

I have tried using tablelayout panels and docking but it doesnt seem to work. I basically want to do what the designer align buttons do but through code.

Any help is greatly appriciated thanks!

答:
```<code> Label myLabel;
 Panel myPanel;
  int x = (myPanel.Size.Width - myLabel.Size.Width) / 2;
  int y = (myPanel.Size.Height - myLabel.Size.Height)/2;
    label1.Location = new Point(x, y);
</code>```


问:
jquery selectors and disabled='disabled'
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...</p>

```<code><input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {
</code>```

答:
If at all you want to submit the disabled input fields you can try something like this</p>

```<code>//This gives an array of name/value pair object.
var inputArray = $('input[id^="pre"], select[id^="pre"]').serializeArray();

//Now look only for disabled input fields and push into inputArray and then process that.
$("input:disabled").each(function(){
   inputArray.push({ name: this.name, value: this.value });
});

//Now process inputArray which contains all the input fields name/value pair
$.each(inputArray, function() {

});
</code>```

Body:
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...

<input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {

Body:
If at all you want to submit the disabled input fields you can try something like this

//This gives an array of name/value pair object.
var inputArray = $('input[id^="pre"], select[id^="pre"]').serializeArray();

//Now look only for disabled input fields and push into inputArray and then process that.
$("input:disabled").each(function(){
   inputArray.push({ name: this.name, value: this.value });
});

//Now process inputArray which contains all the input fields name/value pair
$.each(inputArray, function() {

});


答:
In C you can't compare two char array using ==. You have to use function strcmp like below:

```<code>#include <stdio.h>
#include <string.h>

int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if(strcmp(marietal_status, "married") == 0 || (strcmp(marietal_status, "unmarried") == 0 && age > 30 && strcmp(sex, "male"))
 || (strcmp(marietal_status, "unmarried") == 0 && age >25 && strcmp(sex, "female") == 0))
        printf("insured");
    else
        printf("uninsured");
}

</code>```

Title: Why doesn't this code for doing string comparisons with user input compile?

Body:
In C you can't compare two char array using ==. You have to use function strcmp like below:

#include <stdio.h>
#include <string.h>

int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if(strcmp(marietal_status, "married") == 0 || (strcmp(marietal_status, "unmarried") == 0 && age > 30 && strcmp(sex, "male"))
 || (strcmp(marietal_status, "unmarried") == 0 && age >25 && strcmp(sex, "female") == 0))
        printf("insured");
    else
        printf("uninsured");
}


问:
Font-Awesome Typescript error when running production build with my react project
I am facing an issue with Font-Awesome Icons in my react project. When I run in my local its working fine but with the production build its giving me following error. Not sure how to approach to resolve this issue. Can someone point me in the right direction here please?

答:
Actually, the docs shows how to

import {
  IconLookup,
  IconDefinition,
  findIconDefinition
} from '@fortawesome/fontawesome-svg-core'

// one icon
const coffeeLookup: IconLookup = {
  prefix: 'fas', iconName: 'coffee'
}
const coffeeIcon1: IconDefinition = findIconDefinition(coffeeLookup)

// the other icon
const coffeeLookup2: IconLookup = {
  prefix: 'fas', iconName: 'coffee'
}
const coffeeIcon2: IconDefinition = findIconDefinition(coffeeLookup2)

// ...

export class App extends React.Component {
  render() {
    return (
      <FaIcon icon={cond ? coffeeIcon1 : coffeeIcon2} />
    )
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

Body:
Actually, the docs shows how to

import {
  IconLookup,
  IconDefinition,
  findIconDefinition
} from '@fortawesome/fontawesome-svg-core'

// one icon
const coffeeLookup: IconLookup = {
  prefix: 'fas', iconName: 'coffee'
}
const coffeeIcon1: IconDefinition = findIconDefinition(coffeeLookup)

// the other icon
const coffeeLookup2: IconLookup = {
  prefix: 'fas', iconName: 'coffee'
}
const coffeeIcon2: IconDefinition = findIconDefinition(coffeeLookup2)

// ...

export class App extends React.Component {
  render() {
    return (
      <FaIcon icon={cond ? coffeeIcon1 : coffeeIcon2} />
    )
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


问:
I installed a newer version of git but homebrew doesn't recognize it
So when I tried to install gcc using homebrew, it gave me an error message saying

```<code>Error: Command failed with exit 129: git
Error: 'curl' must be installed and in your PATH!
</code>```

Then I checked the homebrew git version ( see attached)

And when I typed

```<code>git --version
</code>```

The system returns

```<code>git version 2.23.0
</code>```

The directory to the newest git is also in the path. So I am really not sure what the problem is

答: A strong possibility of your terminal and $PATH got confused. Either close terminal, or be super safe by logging out as your user and logging back in.

Body:
So when I tried to install gcc using homebrew, it gave me an error message saying

Error: Command failed with exit 129: git
Error: 'curl' must be installed and in your PATH!

Then I checked the homebrew git version ( see attached)

And when I typed

git --version

The system returns

git version 2.23.0

The directory to the newest git is also in the path. So I am really not sure what the problem is


答: A disabled input field is picked up in a selector, however it is not included when the form is serialized (serializeArray()), as it is not a "successful control". This behaviour is documented in the jQuery docs.

Title: jquery selectors and disabled='disabled'


问:
Get the average in a while loop
I am trying to get the average from my count. I don't know where to start, can someone help me? Here is my code:</p>
```<code>i = 1
count = 0

#while loop to determine number of candy bars sold
while i < 5 :
    count += eval(input("How many candy bars did you sell in week "+str(i)+"? "))
    i+= 1

#print statements to return wanted info
print("Total number of candy bars sold in a month is: ",count)
</code>```

答:
Simply divide the total by the number of weeks in a month (4):

i = 1
count = 0

#while loop to determine number of candy bars sold
while i < 5 :
    count += eval(input("How many candy bars did you sell in week "+str(i)+"? "))
    i+= 1

#print statements to return wanted info
print("Total number of candy bars sold in a month is: ",count)

average = count / 4.0
print("The average number of candybars per week is:", average)
```

Title: Get the average in a while loop

Body:
I am trying to get the average from my count. I don't know where to start, can someone help me? Here is my code:

i = 1
count = 0

#while loop to determine number of candy bars sold
while i < 5 :
    count += eval(input("How many candy bars did you sell in week "+str(i)+"? "))
    i+= 1

#print statements to return wanted info
print("Total number of candy bars sold in a month is: ",count)


问:
Where can I get the Authorized User instance in a laravel api call?
When I use Laravel API endpoint controller, how do I get the user I loggedin on the same instance over a web controller?</p>

答:
Depends on what authentication package are you using, but generally you can just use this:

```<code>$user = Auth::user(); //user instance
$id = Auth::id(); //user id
</code>```

Additionaly, when using POST request, you can use $request->user(), which will look like this:

```<code>public function update(Request $request)
{
    $user = $request->user(); //returns an instance of the authenticated user...
}
</code>```

Body:
Depends on what authentication package are you using, but generally you can just use this:

$user = Auth::user(); //user instance
$id = Auth::id(); //user id

Additionaly, when using POST request, you can use $request->user(), which will look like this:

public function update(Request $request)
{
    $user = $request->user(); //returns an instance of the authenticated user...
}


问:
Hilt Fragment has to be attached to @AndroidEntryPoint Activity, while testing (it is attached to @AndEntPoint marked activity)
I followed a lot of tutorials/ articles and the googles architecture sample

No matter what I try I keep getting an error saying that I need to attach Fragment to @AndroidEntryPoint annotated Activity. I've setup everything correctly but still can't get this to work properly.

```<code>java.lang.IllegalStateException: Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class com.nikolam.colorme.HiltTestActivity
    at dagger.hilt.internal.Preconditions.checkState(Preconditions.java:83)
    at dagger.hilt.android.internal.managers.FragmentComponentManager.createComponent(FragmentComponentManager.java:75)
    at dagger.hilt.android.internal.managers.FragmentComponentManager.generatedComponent(FragmentComponentManager.java:64)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.generatedComponent(Hilt_MainFragment.java:80)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.inject(Hilt_MainFragment.java:102)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.initializeComponentContext(Hilt_MainFragment.java:63)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.onAttach(Hilt_MainFragment.java:55)
    at androidx.fragment.app.Fragment.onAttach(Fragment.java:1783)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.onAttach(Hilt_MainFragment.java:45)
    at androidx.fragment.app.Fragment.performAttach(Fragment.java:2911)
    at androidx.fragment.app.FragmentStateManager.attach(FragmentStateManager.java:464)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:275)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
    at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1971)
    at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:305)
    at com.nikolam.colorme.main_feature.MainFragmentTest$whenMainActivityLaunchedNavigatorIsInvokedForFragment$$inlined$launchFragmentInHiltContainer$1.perform(HiltExt.kt:46)
    at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:660)
    at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source)
    at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:670)
    at com.nikolam.colorme.main_feature.MainFragmentTest.whenMainActivityLaunchedNavigatorIsInvokedForFragment(MainFragmentTest.kt:85)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at dagger.hilt.android.internal.testing.MarkThatRulesRanRule$1.evaluate(MarkThatRulesRanRule.java:106)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:263)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Now here is my setup.

Dependencies

```<code>    testImplementation(TestLibraryDependency.HILT_ANDROID_TESTING)
    kaptTest(TestLibraryDependency.HILT_ANDROID_TESTING_COMPILER)
    testImplementation(TestLibraryDependency.TEST_RUNNER)
    testImplementation(TestLibraryDependency.ESPRESSO_CORE)
    testImplementation(TestLibraryDependency.ANDROIDX_TEST_RULES)
    testImplementation(TestLibraryDependency.ANDROIDX_CORE_TESTING)
    testImplementation(TestLibraryDependency.ANDROIDX_TEST_EXT)
</code>```

This is my test

```<code>@HiltAndroidTest
@Config(application = HiltTestApplication::class, maxSdk = Build.VERSION_CODES.P)
@RunWith(RobolectricTestRunner::class)
class MainFragmentTest {

    @get:Rule()
    var hiltAndroidRule = HiltAndroidRule(this)

    @Before
    fun init() {
        hiltAndroidRule.inject()
    }

    @Test
    fun whenMainActivityLaunchedNavigatorIsInvokedForFragment() {
     //   launchActivity()
        // GIVEN - On the home screen
        val navController = mock(NavController::class.java)

        var fragment = launchFragmentInHiltContainer<MainFragment>() {
            Navigation.setViewNavController(this.view!!, navController)
        }

        // WHEN - Click on the "+" button
        onView(withId(R.id.add_floating_action)).perform(ViewActions.click())

        // THEN - Verify that we navigate to the add screen
        verify(navController).navigate(
            Uri.parse(UPLOAD_DEEPLINK)
        )
    }
</code>```

Launch in hilt container per google

```<code>inline fun <reified T : Fragment> launchFragmentInHiltContainer(
    fragmentArgs: Bundle? = null,
    @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
    crossinline action: Fragment.() -> Unit = {}
) {
    val startActivityIntent = Intent.makeMainActivity(
        ComponentName(
            ApplicationProvider.getApplicationContext(),
            HiltTestActivity::class.java
        )
    ).putExtra(EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId)

    ActivityScenario.launch<HiltTestActivity>(startActivityIntent).onActivity { activity ->
        val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
            Preconditions.checkNotNull(T::class.java.classLoader),
            T::class.java.name
        )
        fragment.arguments = fragmentArgs
        activity.supportFragmentManager
            .beginTransaction()
            .add(android.R.id.content, fragment, "")
            .commitNow()

        fragment.action()
    }
}
</code>```

(I also have their custom runner)

I also have a debug source set that contains HiltTestActivity like here, alongside debug manifest.

Besides this, I'd like to somehow inject and initialize my NavigationManager (wrapper class around navController) in my Activity. Is there a way to achieve this? When I tried to use my MainActivity for tests I kept getting errors because my lateinit @Injects weren't getting initialized...

```<code>@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding;

    private lateinit var navController : NavController
    @Inject
    lateinit var navManager: NavManager

    private fun initNavManager() {
        navManager.setOnNavEvent {
            navController.navigate(it)
        }
</code>```

答:
I was importing kapt twice. Removing one solved it.</p>
```<code>id 'org.jetbrains.kotlin.kapt'
id 'kotlin-kapt'
</code>```

Body:
I followed a lot of tutorials/ articles and the googles architecture sample

No matter what I try I keep getting an error saying that I need to attach Fragment to @AndroidEntryPoint annotated Activity. I've setup everything correctly but still can't get this to work properly.

java.lang.IllegalStateException: Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: class com.nikolam.colorme.HiltTestActivity
    at dagger.hilt.internal.Preconditions.checkState(Preconditions.java:83)
    at dagger.hilt.android.internal.managers.FragmentComponentManager.createComponent(FragmentComponentManager.java:75)
    at dagger.hilt.android.internal.managers.FragmentComponentManager.generatedComponent(FragmentComponentManager.java:64)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.generatedComponent(Hilt_MainFragment.java:80)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.inject(Hilt_MainFragment.java:102)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.initializeComponentContext(Hilt_MainFragment.java:63)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.onAttach(Hilt_MainFragment.java:55)
    at androidx.fragment.app.Fragment.onAttach(Fragment.java:1783)
    at com.nikolam.main_feature.presenter.main_screen.Hilt_MainFragment.onAttach(Hilt_MainFragment.java:45)
    at androidx.fragment.app.Fragment.performAttach(Fragment.java:2911)
    at androidx.fragment.app.FragmentStateManager.attach(FragmentStateManager.java:464)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:275)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
    at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1971)
    at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:305)
    at com.nikolam.colorme.main_feature.MainFragmentTest$whenMainActivityLaunchedNavigatorIsInvokedForFragment$$inlined$launchFragmentInHiltContainer$1.perform(HiltExt.kt:46)
    at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:660)
    at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source)
    at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:670)
    at com.nikolam.colorme.main_feature.MainFragmentTest.whenMainActivityLaunchedNavigatorIsInvokedForFragment(MainFragmentTest.kt:85)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at dagger.hilt.android.internal.testing.MarkThatRulesRanRule$1.evaluate(MarkThatRulesRanRule.java:106)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:263)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Now here is my setup.

Dependencies

    testImplementation(TestLibraryDependency.HILT_ANDROID_TESTING)
    kaptTest(TestLibraryDependency.HILT_ANDROID_TESTING_COMPILER)
    testImplementation(TestLibraryDependency.TEST_RUNNER)
    testImplementation(TestLibraryDependency.ESPRESSO_CORE)
    testImplementation(TestLibraryDependency.ANDROIDX_TEST_RULES)
    testImplementation(TestLibraryDependency.ANDROIDX_CORE_TESTING)
    testImplementation(TestLibraryDependency.ANDROIDX_TEST_EXT)

This is my test

@HiltAndroidTest
@Config(application = HiltTestApplication::class, maxSdk = Build.VERSION_CODES.P)
@RunWith(RobolectricTestRunner::class)
class MainFragmentTest {

    @get:Rule()
    var hiltAndroidRule = HiltAndroidRule(this)

    @Before
    fun init() {
        hiltAndroidRule.inject()
    }

    @Test
    fun whenMainActivityLaunchedNavigatorIsInvokedForFragment() {
     //   launchActivity()
        // GIVEN - On the home screen
        val navController = mock(NavController::class.java)

        var fragment = launchFragmentInHiltContainer<MainFragment>() {
            Navigation.setViewNavController(this.view!!, navController)
        }

        // WHEN - Click on the "+" button
        onView(withId(R.id.add_floating_action)).perform(ViewActions.click())

        // THEN - Verify that we navigate to the add screen
        verify(navController).navigate(
            Uri.parse(UPLOAD_DEEPLINK)
        )
    }

Launch in hilt container per google

inline fun <reified T : Fragment> launchFragmentInHiltContainer(
    fragmentArgs: Bundle? = null,
    @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
    crossinline action: Fragment.() -> Unit = {}
) {
    val startActivityIntent = Intent.makeMainActivity(
        ComponentName(
            ApplicationProvider.getApplicationContext(),
            HiltTestActivity::class.java
        )
    ).putExtra(EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId)

    ActivityScenario.launch<HiltTestActivity>(startActivityIntent).onActivity { activity ->
        val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
            Preconditions.checkNotNull(T::class.java.classLoader),
            T::class.java.name
        )
        fragment.arguments = fragmentArgs
        activity.supportFragmentManager
            .beginTransaction()
            .add(android.R.id.content, fragment, "")
            .commitNow()

        fragment.action()
    }
}

(I also have their custom runner)

I also have a debug source set that contains HiltTestActivity like here, alongside debug manifest.

Besides this, I'd like to somehow inject and initialize my NavigationManager (wrapper class around navController) in my Activity. Is there a way to achieve this? When I tried to use my MainActivity for tests I kept getting errors because my lateinit @Injects weren't getting initialized...

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding;

    private lateinit var navController : NavController
    @Inject
    lateinit var navManager: NavManager

    private fun initNavManager() {
        navManager.setOnNavEvent {
            navController.navigate(it)
        }

Body:
I was importing kapt twice. Removing one solved it.

id 'org.jetbrains.kotlin.kapt'
id 'kotlin-kapt'


问:
how to access the Json Responce dict value in the Html script
My django views

```<code>def contact_otp(request):
        if request.method=="POST":
            data = {
        "data-token":f"{otp.token}"
    }
            #
            return JsonResponse(data)

.then((response) => response.json())
          .then((data) => {
            console.log(data)
            const newVarPass = document.createElement("input")
            newVarPass.setAttribute('id','varPassID')
            newVarPass.setAttribute('value',`${data}`)
            newVarPass.value=`${data}`
            newVarPass.style.display="none"
            document.body.appendChild(newVarPass)
            alert("Check your Email We have send you the otp")
            console.log(data)

          })

    x = document.getElementById("varPassID")
                console.log(x)
                console.log("Lets check")
</code>```

How to get the values of the json keypair i want to have which is present in the json data i am always getting object object in the value now

updated console.log(data)

答:
```<code>document.getElementById("varPassID").innerText = data.data-token
</code>```

Reference: https://www.w3schools.com/jsref/prop_node_innertext.asp

Body:
My django views

def contact_otp(request):
        if request.method=="POST":
            data = {
        "data-token":f"{otp.token}"
    }
            #
            return JsonResponse(data)

.then((response) => response.json())
          .then((data) => {
            console.log(data)
            const newVarPass = document.createElement("input")
            newVarPass.setAttribute('id','varPassID')
            newVarPass.setAttribute('value',`${data}`)
            newVarPass.value=`${data}`
            newVarPass.style.display="none"
            document.body.appendChild(newVarPass)
            alert("Check your Email We have send you the otp")
            console.log(data)

          })

    x = document.getElementById("varPassID")
                console.log(x)
                console.log("Lets check")

How to get the values of the json keypair i want to have which is present in the json data i am always getting object object in the value now

updated console.log(data)

Body:
document.getElementById("varPassID").innerText = data.data-token

Reference: https://www.w3schools.com/jsref/prop_node_innertext.asp


问:
Bcrypt error: illegal arguments String unidentified
here is my complete code

```<code>var express = require('express'),
    app = express(),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    webToken = require('jsonwebtoken'),
    bcrypt = require('bcryptjs'),
    assert = require('assert');
    Schema = mongoose.Schema,
    secretKey = "omjdiuwkslxmshsoepdukslsj";

//User Schema
var userSchema = new Schema({
    username: {type: String, required: true, index: {unique:true}},
    password: {type: String, required: true, select: false}
})

userSchema.pre('save', function(next){
    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash(user.password, null, null, function(err, hash){
        if(err) return next(err);

        user.password = hash;
        next();
    })
});

userSchema.methods.comparePassword = function(password){
    var user = this;

    bcrypt.compare(password, user.password, function(err, result){
        if(err){
            console.log(err);
        }
        else {
            console.log("passwords match!");
            return;
        }
    })
}

var userModel = mongoose.model('users', userSchema);

//Connecting to Mongo
mongoose.connect("mongodb://localhost/userstories", function(err){
    if(err) {
        console.log(err);
    }
    else {
        console.log("Connected to database!");
    }
});

//Creating Token
function createToken(user){
    var token = webToken.sign({
        _id: user.id,
        username: user.username
    },  secretKey,{
        expiresIn: 30 * 60 * 1000
    })
    return token;
    }

//Middlewares
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));

//Api's

app.post('/signup', function(req, res){
    var user = new userModel({
        username: req.body.username,
        password: req.body.password
    })

    user.save(function(err){
        if(err){
            console.log(err);
        }

        else{
            res.json({message: "User created!"});
        }
    })
})

app.post('/login', function(req, res){

    userModel.findOne({username: req.body.username}, function(err, user){
        if(err) console.log(err);

            if(!user){
                res.send("User not found!");
            }
                 else if(user){

                      var validPassword = user.comparePassword(req.body.password);

                       if(validPassword){
                                var tokens = createToken(user);

                                res.json({
                                    success: true,
                                    message: "Successfully logged In",
                                    token: tokens
                                });
                        }

                            else {
                                    res.send("Invalid password");
                                  }

                     }
    })
});

//Running the server
app.listen(3000, function(err){
    if(err) console.log("port not working");
    else{
        console.log("Everything went just fine");
    }
})
</code>```

I've tried every approaches and saw all the answers here. But no one seem to come across this illegal argument error. Please figure this one out for me Im sure there is a bug I cant see

答: If you're testing this with Postman, I just found an issue where the default Content-Type header is set to text/plain. If you untick the default header (as it doesn't allow you to change it) and add another Content-Type header with a value of application/json, it works.

Body:
here is my complete code

var express = require('express'),
    app = express(),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    morgan = require('morgan'),
    webToken = require('jsonwebtoken'),
    bcrypt = require('bcryptjs'),
    assert = require('assert');
    Schema = mongoose.Schema,
    secretKey = "omjdiuwkslxmshsoepdukslsj";

//User Schema
var userSchema = new Schema({
    username: {type: String, required: true, index: {unique:true}},
    password: {type: String, required: true, select: false}
})

userSchema.pre('save', function(next){
    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash(user.password, null, null, function(err, hash){
        if(err) return next(err);

        user.password = hash;
        next();
    })
});

userSchema.methods.comparePassword = function(password){
    var user = this;

    bcrypt.compare(password, user.password, function(err, result){
        if(err){
            console.log(err);
        }
        else {
            console.log("passwords match!");
            return;
        }
    })
}

var userModel = mongoose.model('users', userSchema);

//Connecting to Mongo
mongoose.connect("mongodb://localhost/userstories", function(err){
    if(err) {
        console.log(err);
    }
    else {
        console.log("Connected to database!");
    }
});

//Creating Token
function createToken(user){
    var token = webToken.sign({
        _id: user.id,
        username: user.username
    },  secretKey,{
        expiresIn: 30 * 60 * 1000
    })
    return token;
    }

//Middlewares
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));

//Api's

app.post('/signup', function(req, res){
    var user = new userModel({
        username: req.body.username,
        password: req.body.password
    })

    user.save(function(err){
        if(err){
            console.log(err);
        }

        else{
            res.json({message: "User created!"});
        }
    })
})

app.post('/login', function(req, res){

    userModel.findOne({username: req.body.username}, function(err, user){
        if(err) console.log(err);

            if(!user){
                res.send("User not found!");
            }
                 else if(user){

                      var validPassword = user.comparePassword(req.body.password);

                       if(validPassword){
                                var tokens = createToken(user);

                                res.json({
                                    success: true,
                                    message: "Successfully logged In",
                                    token: tokens
                                });
                        }

                            else {
                                    res.send("Invalid password");
                                  }

                     }
    })
});

//Running the server
app.listen(3000, function(err){
    if(err) console.log("port not working");
    else{
        console.log("Everything went just fine");
    }
})

I've tried every approaches and saw all the answers here. But no one seem to come across this illegal argument error. Please figure this one out for me Im sure there is a bug I cant see


问:
"ValueError: invalid literal for int() with base 10:"
I'm attempting to create a function that allows you to set the maximum height and width in blocks. I need to adjust the max height to &MaxHeight= or none, and the width accordingly so they work with the API I'll be using later.

I've tried adding and removing str() and int() to the input and maxh/maxw, but the error remained. I've also read ValueError: invalid literal for int() with base 10: '', but it seems like the thread creator is experiencing a different issue with the same error message.

This is the code that is causing this error:

```<code>print("What is your desired max height and width in blocks? (Enter 0 for none)")
print("")
maxh = str(input("Height: "))
maxw = str(input("Width: "))
print("")

while maxh or maxw is not None:
  if int(maxh) == 0:
    maxh = None
  elif int(maxw) == 0:
    maxw = None
  elif int(maxh) > 0:
    maxh = "&MaxHeight=" + str(maxh)
  elif int(maxw) > 0:
    maxw = "&MaxWidth=" + str(maxw)
  else:
    print(Fore.RED + "The max height or width can not be less than 0. Please enter your desired max height and width in blocks? (Enter 0 for none)" + Fore.WHITE)
    print("")
    maxh = str(input("Height: "))
    maxw = str(input("Width: "))
    print("")
</code>```

Error with 24 as maxh and maxw:

```<code>Traceback (most recent call last):
  File "main.py", line 15, in <module>
    if int(maxh) == 0:
ValueError: invalid literal for int() with base 10: '&MaxHeight=24'
</code>```

答:
Keeping your ints and strs from getting mixed up is easier if you convert the inputs to int up front and then format them into strings only after you've validated them:

```<code>while True:
    print("What is your desired max height and width in blocks? (Enter 0 for none)")
    try:
        h = int(input("Height: "))
        w = int(input("Weight: "))
        if h < 0 or w < 0:
            raise ValueError("The max height or width can't be less than 0.")
        maxh = f"&MaxHeight={h}" if h else None
        maxw = f"&MaxWidth={w}" if w else None
        # We got valid values, so now we can exit the loop.
        break
    except ValueError as e:
        # We'll jump here if the input is invalid for any reason.
        # Print the error and then implicitly continue the loop.
        print(e)

# maxh and maxw are each now either valid strings or None
print(maxh, maxw)
</code>```
```<code>What is your desired max height and width in blocks? (Enter 0 for none)
Height: asdf
invalid literal for int() with base 10: 'asdf'
What is your desired max height and width in blocks? (Enter 0 for none)
Height: -1
Weight: 4
The max height or width can't be less than 0.
What is your desired max height and width in blocks? (Enter 0 for none)
Height: 20
Weight: 30
&MaxHeight=20 &MaxWidth=30
</code>```

Body:
I'm attempting to create a function that allows you to set the maximum height and width in blocks. I need to adjust the max height to &MaxHeight= or none, and the width accordingly so they work with the API I'll be using later.

I've tried adding and removing str() and int() to the input and maxh/maxw, but the error remained. I've also read ValueError: invalid literal for int() with base 10: '', but it seems like the thread creator is experiencing a different issue with the same error message.

This is the code that is causing this error:

print("What is your desired max height and width in blocks? (Enter 0 for none)")
print("")
maxh = str(input("Height: "))
maxw = str(input("Width: "))
print("")

while maxh or maxw is not None:
  if int(maxh) == 0:
    maxh = None
  elif int(maxw) == 0:
    maxw = None
  elif int(maxh) > 0:
    maxh = "&MaxHeight=" + str(maxh)
  elif int(maxw) > 0:
    maxw = "&MaxWidth=" + str(maxw)
  else:
    print(Fore.RED + "The max height or width can not be less than 0. Please enter your desired max height and width in blocks? (Enter 0 for none)" + Fore.WHITE)
    print("")
    maxh = str(input("Height: "))
    maxw = str(input("Width: "))
    print("")

Error with 24 as maxh and maxw:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    if int(maxh) == 0:
ValueError: invalid literal for int() with base 10: '&MaxHeight=24'

Body:
Keeping your ints and strs from getting mixed up is easier if you convert the inputs to int up front and then format them into strings only after you've validated them:

while True:
    print("What is your desired max height and width in blocks? (Enter 0 for none)")
    try:
        h = int(input("Height: "))
        w = int(input("Weight: "))
        if h < 0 or w < 0:
            raise ValueError("The max height or width can't be less than 0.")
        maxh = f"&MaxHeight={h}" if h else None
        maxw = f"&MaxWidth={w}" if w else None
        # We got valid values, so now we can exit the loop.
        break
    except ValueError as e:
        # We'll jump here if the input is invalid for any reason.
        # Print the error and then implicitly continue the loop.
        print(e)

# maxh and maxw are each now either valid strings or None
print(maxh, maxw)

What is your desired max height and width in blocks? (Enter 0 for none)
Height: asdf
invalid literal for int() with base 10: 'asdf'
What is your desired max height and width in blocks? (Enter 0 for none)
Height: -1
Weight: 4
The max height or width can't be less than 0.
What is your desired max height and width in blocks? (Enter 0 for none)
Height: 20
Weight: 30
&MaxHeight=20 &MaxWidth=30


问:
JavaScript syntax check with JavaScript?
How could a Commando like me check if inputed code is a valid JavaScript source using some JavaScript built-in methods (if any!) or in any other possible way!? (Something like a preparser found in various IDE's like NetBeans, Eclipse, etc)?

I have to check if code is OKAY and then window.eval()-it to the current document instance.

答: You're looking for Crockford's jslint.js. It's the same code that powers http://jslint.com/.</p>


问:
Can @Epic have dynamic values in Allure report. I need to pass my API name like @Epic(ApiName), Where ApiName is a String
Can @Epic have dynamic values in Allure report.

I need to pass my API name like @Epic(ApiName).

Private String ApiName = getApiName();
@Epic(ApiName)

答:
you can use Allure.getLifecycle() api solved this problem.
ex:</p>
```<code>@Test(dataProvider = "customer", dataProviderClass = GetUserData.class)
    public void CommonMethod(UserData data) throws IOException, InterruptedException {
        AllureLifecycle lifecycle = Allure.getLifecycle();
        final Label label =  new Label().setName("epic").setValue(data.getApi());
        lifecycle.updateTestCase(testResult -> testResult.getLabels().add(label));

        //testing code
}
</code>```

Body:
you can use Allure.getLifecycle() api solved this problem.
ex:

@Test(dataProvider = "customer", dataProviderClass = GetUserData.class)
    public void CommonMethod(UserData data) throws IOException, InterruptedException {
        AllureLifecycle lifecycle = Allure.getLifecycle();
        final Label label =  new Label().setName("epic").setValue(data.getApi());
        lifecycle.updateTestCase(testResult -> testResult.getLabels().add(label));

        //testing code
}


问:
Get sourced filename in busybox ash
The ash shell in busybox doesn't seem to implement any of the standard ways to get the filename that's being sourced.  For instance:

testo:

```<code>#!/usr/bin/env -S busybox ash
echo hello whorl
echo using source
source ./sourceme
echo using .
. ./sourceme
</code>```

sourceme:

```<code>echo underscore $_
echo bs $BASH_SOURCE
echo zero $0
</code>```

```<code># ./testo
hello whorl
using source
underscore ./testo
bs
zero ./testo
using .
underscore ./testo
bs
zero ./testo
</code>```

I need something to put in sourceme that will get its own name/path.

答:
This excellent answer contains a very clever way to accomplish this.  I've adapted their solution here - insert this line into sourceme:

```<code>echo lsof `lsof -p $$ -Fn | tail -n1 | sed 's!^[^/]*!!g'``
</code>```

And you get:

```<code>lsof /absolute/path/to/sourceme
</code>```

Note: since we're talking about busybox here, this is an implementation of the above using busybox's lsof:

```<code>lsof | grep '^'$$ | tail -n1 | awk '{print $3}'
</code>```

Note: if anyone finds a way to do this using some builtin mechanism from busybox ash, post an answer and I'll change the accepted answer to yours.

Title: Get sourced filename in busybox ash

Body:
The ash shell in busybox doesn't seem to implement any of the standard ways to get the filename that's being sourced.  For instance:

testo:

#!/usr/bin/env -S busybox ash
echo hello whorl
echo using source
source ./sourceme
echo using .
. ./sourceme

sourceme:

echo underscore $_
echo bs $BASH_SOURCE
echo zero $0

# ./testo
hello whorl
using source
underscore ./testo
bs
zero ./testo
using .
underscore ./testo
bs
zero ./testo

I need something to put in sourceme that will get its own name/path.

Body:
This excellent answer contains a very clever way to accomplish this.  I've adapted their solution here - insert this line into sourceme:

echo lsof `lsof -p $$ -Fn | tail -n1 | sed 's!^[^/]*!!g'``

And you get:

lsof /absolute/path/to/sourceme

Note: since we're talking about busybox here, this is an implementation of the above using busybox's lsof:

lsof | grep '^'$$ | tail -n1 | awk '{print $3}'

Note: if anyone finds a way to do this using some builtin mechanism from busybox ash, post an answer and I'll change the accepted answer to yours.


问:
How to set focus to the old window on button click in PyQt5 Python?
My Current Project is to create a On Screen Keyboard for my personal usage with my personal functionality. I made gui and primary function in PyQt5 with Python. I managed to type the letter on button click with pyautogui.write() method. But the problem is, where I want to type there is no focus. suppose I want to write on chrome's address bar or any other input field on my monitor. when I click on button to type a letter, chrome lost focus. I want to set focus to the old window while press on any button. I searched on google about this but didn't found any answer. How can i set focus to old window? or is there any better way to type on focus lost state?

答:
You should not try to "set the focus back", as it would be almost impossible to know what window had the focus before (and a new window might raise in the meantime). What you should actually do is to prevent your window to get focus at all, thus avoiding it to steal focus from the others.

In order to achieve this, you must set the appropriate window flag (or initialize the widget with it using the flags keyword argument), which for this is Qt.WindowDoesNotAcceptFocus.

Note that you might also want to set the Qt.WindowStaysOnTopHint in order to always keep your window above the others:

class MyKeyboard(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(
            QtCore.Qt.WindowDoesNotAcceptFocus
            | QtCore.Qt.WindowStaysOnTopHint
        )
```


问:
Why doesn't this code for doing string comparisons with user input compile?
```<code>#include <stdio.h>
int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male)
 || (marietal_status == unmarried && age >25 && sex == female))
    printf("insured");
    else
    printf("uninsured");
}
</code>```

ouput:

gcc /tmp/NaKWq16d9Q.c -lm
/tmp/NaKWq16d9Q.c: In function 'main':
/tmp/NaKWq16d9Q.c:10:28: error: 'married' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                            ^~~~~~~
/tmp/NaKWq16d9Q.c:10:28: note: each undeclared identifier is reported only once for each function it appears in
/tmp/NaKWq16d9Q.c:10:60: error: 'unmarried' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                            ^~~~~~~~~
/tmp/NaKWq16d9Q.c:10:92: error: 'male' undeclared (first use in this function)
   10 | ried) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                              ^~~~

/tmp/NaKWq16d9Q.c:10:152: error: 'female' undeclared (first use in this function)
   10 |  && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                                        ^~~~~~
```

答:
married, unmarried, male and female are undeclared entities.

It seems you mean string literals "married", "unmarried", "male" and "female".

But such a comparison like for example this

```<code>marietal_status == "married"
</code>```

will always evaluate to false because there are compared two pointers.

Instead you need to use the C string function strcmp declared in the header <string.h>.

So the if statement will look

```<code>#include <string.h>

//...

if( ( strcmp( marietal_status, "married" ) == 0) ||
    ( strcmp( marietal_status, "unmarried" ) == 0 &&
      age > 30 && strcmp( sex, "male" ) == 0 )
    || ( strcmp( marietal_status, "unmarried" ) == 0 && age >25 && strcmp( sex, "female" ) == 0 ) )
</code>```

Body:
#include <stdio.h>
int main()
{
    int age;
    char marietal_status[15], sex[15];

    printf("Age, Marietal status, sex of the driver : ");
    scanf("%i %s %s", &age, marietal_status, sex);

    if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male)
 || (marietal_status == unmarried && age >25 && sex == female))
    printf("insured");
    else
    printf("uninsured");
}

ouput:

gcc /tmp/NaKWq16d9Q.c -lm
/tmp/NaKWq16d9Q.c: In function 'main':
/tmp/NaKWq16d9Q.c:10:28: error: 'married' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                            ^~~~~~~
/tmp/NaKWq16d9Q.c:10:28: note: each undeclared identifier is reported only once for each function it appears in
/tmp/NaKWq16d9Q.c:10:60: error: 'unmarried' undeclared (first use in this function)
   10 |     if((marietal_status == married) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                            ^~~~~~~~~
/tmp/NaKWq16d9Q.c:10:92: error: 'male' undeclared (first use in this function)
   10 | ried) || (marietal_status == unmarried && age > 30 && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                              ^~~~

/tmp/NaKWq16d9Q.c:10:152: error: 'female' undeclared (first use in this function)
   10 |  && sex == male) || (marietal_status == unmarried && age >25 && sex == female))
      |                                                                        ^~~~~~

Body:
married, unmarried, male and female are undeclared entities.

It seems you mean string literals "married", "unmarried", "male" and "female".

But such a comparison like for example this

marietal_status == "married"

will always evaluate to false because there are compared two pointers.

Instead you need to use the C string function strcmp declared in the header <string.h>.

So the if statement will look

#include <string.h>

//...

if( ( strcmp( marietal_status, "married" ) == 0) ||
    ( strcmp( marietal_status, "unmarried" ) == 0 &&
      age > 30 && strcmp( sex, "male" ) == 0 )
    || ( strcmp( marietal_status, "unmarried" ) == 0 && age >25 && strcmp( sex, "female" ) == 0 ) )


问:
Passing parameters to Glue job from AWS Lambda
We need to pass 4 parameters from AWS Lambda to AWS Glue job while triggering Glue job.

```<code>response = client.start_job_run(JobName = 'my_test_Job',
         Arguments = {
           '--yr_partition_val':   2017,
           '--mon_partition_val':  05,
           '--date_partition_val':  25,
           '--hour_partition_val': 07 } )
</code>```

Glue need to catch these 4 parameters to proceed further in pyspark glue code.

I have tried using below in glue to catch parameters:

```<code>import sys
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv,
                      ['JOB_NAME',
                       'yr_partition_val',
                       'mon_partition_val',
                       'date_partition_val',
                       'hour_partition_val'])
</code>```

but got the error as:

```<code>self.error(_('argument %s is required') % name)
awsglue.utils.GlueArgumentError: argument --JobName is required
</code>```

Can someone help it out?

答:
```<code>glueJobName = 'job_01'
for record in event['Records']:
    print(record['s3']['object']['key'])
    file_name = unquote_plus(record['s3']['object']['key'])
    client = boto3.client('glue')
    print("Job is going to start")
    arguments = {
        '--source': 'abc',
        '--bucket_name': 'test',
        '--folder_name': 'abc-2',
        '--file_name': file_name,
    }
    response = client.start_job_run(JobName = 'job_01', Arguments=arguments)
return {
    'statusCode': 200,
    'body': json.dumps('Glue Trigger Lambda!' )
}
</code>```

Body:
We need to pass 4 parameters from AWS Lambda to AWS Glue job while triggering Glue job.

response = client.start_job_run(JobName = 'my_test_Job',
         Arguments = {
           '--yr_partition_val':   2017,
           '--mon_partition_val':  05,
           '--date_partition_val':  25,
           '--hour_partition_val': 07 } )

Glue need to catch these 4 parameters to proceed further in pyspark glue code.

I have tried using below in glue to catch parameters:

import sys
from awsglue.utils import getResolvedOptions

args = getResolvedOptions(sys.argv,
                      ['JOB_NAME',
                       'yr_partition_val',
                       'mon_partition_val',
                       'date_partition_val',
                       'hour_partition_val'])

but got the error as:

self.error(_('argument %s is required') % name)
awsglue.utils.GlueArgumentError: argument --JobName is required

Can someone help it out?


问:
amavisd-new rule to call external script
We are using amavisd-new (amavisd-new/oldstable,now 1:2.10.1-4) to filter both incomming and outgoing e-mails.

The thing is we receive a log of spam with fake sender from our domain. Since we have less than 100 accounts in our system, is there a plugin that can take the sender address then check it against a valid list of senders?
Thank you a lot.

our system configuration is:

debian stretch

amavisd-new/oldstable,now 1:2.10.1-4

spamassassin/oldstable,oldstable,now 3.4.2-1

答:
If spamassassin checks outgoing email then perhaps a local rule that checks for allowed senders such as:

header LOCAL_WHITELIST From =~ /(me)|(you)|(etc)@mydomain.org/

meta LOCAL_WHITELIST_MATCH ((LOCAL_WHITELIST) =1)
score LOCAL_WHITELIST_MATCH -1.0

meta LOCAL_WHITELIST_MISS ((LOCAL_WHITELIST) =0)
score LOCAL_WHITELIST_MISS 1.0

Unfortunately, I have no idea how to do this just for outgoing email.

It should be straightforward to write a shell script that automatically generates the white list for you and creates the above as a whitelist.cf for spamassassin.  That would be cool. Especially if you could get it to run automatically after the creation or deletion of an email account and then amavisd-new reload && service amavisd-new restart.


问:
try catch or async awaiit in useeffect for jest
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

```<code>const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);
</code>```

答:
```<code> const [data, setData] = useState(null);
 const [isLoading, setLoading] = useState(false);

 useEffect(async() => {
   setLoading(true)
   try{
        const res = await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
        const data = await res.json()
        setData(data)
        setLoading(false)
     }catch(err=>{
        console.log(err)
      })

   }, [500]);
</code>```

Body:
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);


问:
Rails I can't use belongs_to and class name methods correctly
First of all, good forum to all.
I am trying to develop an application with Ruby on rails and in this application there will be User and Room classes and these classes will communicate with each other with winner_id and creator_id, but I could not do the necessary actions, can you help?

Creating a user model:

```<code>$ rails g model User first_name last_name username role player_id:integer password
</code>```

Creating a room model:

```<code>$ rails g model Room rules:text online:boolean room_id:integer password:string winner:belongs_to creator:belongs_to
</code>```

User.rb:

class User < ApplicationRecord
    has_many :oda,class_name:"Room",foreign_key:"owner_id"
    has_many :winner,class_name:"Room",foreign_key:"winner_id"
end
```
<p>Room.rb:</p>
<pre class="lang-rb prettyprint-override"><code>class Room < ApplicationRecord
  belongs_to :owner,class_name:"User",foreign_key:"owner_id"
  belongs_to :winner,class_name:"User",foreign_key:"winner_id"
end
</code>```

The code I'm trying to run:

User.all

[#<User:0x00005598a714d120
  id: 1,
  first_name: "Lorem",
  last_name: "İpsum",
  username: "Wormer",
  role: "janitor",
  player_id: 1234,
  password: "[FILTERED]",
  created_at: Thu, 10 Feb 2022 15:54:15.312134000 UTC +00:00,
  updated_at: Thu, 10 Feb 2022 15:54:15.312134000 UTC +00:00>,
 #<User:0x00005598a71b8060
  id: 2,
  first_name: "Hello",
  last_name: "World",
  username: "MoonKnight",
  role: "player",
  player_id: 1234,
  password: "[FILTERED]",
  created_at: Thu, 10 Feb 2022 15:55:09.787504000 UTC +00:00,
  updated_at: Thu, 10 Feb 2022 15:55:09.787504000 UTC +00:00>]

room = Room.new do |room|
  room.rules = "None"
  room.online = true
  room.password = "a"
  room.room_id = 5555
end

room.winner = User.find_by(role:"player")
room.creator = User.find_by(role:"janitor")
room.save
```
<p>Error:</p>
<pre class="lang-rb prettyprint-override"><code>/home/user/.rvm/gems/ruby-3.0.1/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:147:in `initialize': SQLite3::SQLException: no such table: main.owners (ActiveRecord::StatementInvalid)
/home/user/.rvm/gems/ruby-3.0.1/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:147:in `initialize': no such table: main.owners (SQLite3::SQLException)

</code>```

答:
I solved the problem by creating the Room model like this:

class CreateRooms < ActiveRecord::Migration[6.1]
  def change
    create_table :rooms do |t|
      t.text :rules
      t.boolean :online
      t.integer :room_id
      t.string :password
      t.belongs_to :winner, null: false# remove,foreign_key:true
      t.belongs_to :creator, null: false# remove,foreign_key:true

      t.timestamps
    end
    add_foreign_key :rooms, :users, column: :winner_id
    add_foreign_key :rooms, :users, column: :creator_id
  end
end

```
<p>User.rb:</p>
<pre class="lang-rb prettyprint-override"><code>class User < ApplicationRecord
    has_many :winner_rooms,class_name:"Room",foreign_key:"winner_id"
    has_many :creator_rooms,class_name:"Room",foreign_key:"creator_id"

end

</code>```

Room.rb:

class Room < ApplicationRecord
  belongs_to :winner,class_name:"User",foreign_key:"winner_id"
  belongs_to :creator,class_name:"User",foreign_key:"creator_id"

end

```

Thanks to everyone who helped.

Body:
First of all, good forum to all.
I am trying to develop an application with Ruby on rails and in this application there will be User and Room classes and these classes will communicate with each other with winner_id and creator_id, but I could not do the necessary actions, can you help?

Creating a user model:

$ rails g model User first_name last_name username role player_id:integer password

Creating a room model:

$ rails g model Room rules:text online:boolean room_id:integer password:string winner:belongs_to creator:belongs_to

User.rb:

class User < ApplicationRecord
    has_many :oda,class_name:"Room",foreign_key:"owner_id"
    has_many :winner,class_name:"Room",foreign_key:"winner_id"
end

Room.rb:

class Room < ApplicationRecord
  belongs_to :owner,class_name:"User",foreign_key:"owner_id"
  belongs_to :winner,class_name:"User",foreign_key:"winner_id"
end

The code I'm trying to run:

User.all

[#<User:0x00005598a714d120
  id: 1,
  first_name: "Lorem",
  last_name: "İpsum",
  username: "Wormer",
  role: "janitor",
  player_id: 1234,
  password: "[FILTERED]",
  created_at: Thu, 10 Feb 2022 15:54:15.312134000 UTC +00:00,
  updated_at: Thu, 10 Feb 2022 15:54:15.312134000 UTC +00:00>,
 #<User:0x00005598a71b8060
  id: 2,
  first_name: "Hello",
  last_name: "World",
  username: "MoonKnight",
  role: "player",
  player_id: 1234,
  password: "[FILTERED]",
  created_at: Thu, 10 Feb 2022 15:55:09.787504000 UTC +00:00,
  updated_at: Thu, 10 Feb 2022 15:55:09.787504000 UTC +00:00>]

room = Room.new do |room|
  room.rules = "None"
  room.online = true
  room.password = "a"
  room.room_id = 5555
end

room.winner = User.find_by(role:"player")
room.creator = User.find_by(role:"janitor")
room.save

Error:

/home/user/.rvm/gems/ruby-3.0.1/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:147:in `initialize': SQLite3::SQLException: no such table: main.owners (ActiveRecord::StatementInvalid)
/home/user/.rvm/gems/ruby-3.0.1/gems/sqlite3-1.4.2/lib/sqlite3/database.rb:147:in `initialize': no such table: main.owners (SQLite3::SQLException)

Body:
I solved the problem by creating the Room model like this:

class CreateRooms < ActiveRecord::Migration[6.1]
  def change
    create_table :rooms do |t|
      t.text :rules
      t.boolean :online
      t.integer :room_id
      t.string :password
      t.belongs_to :winner, null: false# remove,foreign_key:true
      t.belongs_to :creator, null: false# remove,foreign_key:true

      t.timestamps
    end
    add_foreign_key :rooms, :users, column: :winner_id
    add_foreign_key :rooms, :users, column: :creator_id
  end
end

User.rb:

class User < ApplicationRecord
    has_many :winner_rooms,class_name:"Room",foreign_key:"winner_id"
    has_many :creator_rooms,class_name:"Room",foreign_key:"creator_id"

end

Room.rb:

class Room < ApplicationRecord
  belongs_to :winner,class_name:"User",foreign_key:"winner_id"
  belongs_to :creator,class_name:"User",foreign_key:"creator_id"

end

Thanks to everyone who helped.


问:
How to use BeautifulSoup 4 to extract Tweet text?
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

```<code>import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)
</code>```

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

答:
This will code will work atleast for me it did
I thinks you got your output because your were using html instead of lxml</p>
```<code>import requests
from bs4 import BeautifulSoup
#needed for bs4
import lxml

#url to the tweet
url = 'https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201'

#get the page source
tweet = requests.get(url).text

soup = BeautifulSoup(tweet, "lxml")

#finds the tweet
tweet_text = soup.find("p", class_='TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text').text)
print(tweet_text)
</code>```

Body:
Tweets are found under a class called TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text.

I tried scraping with BeautifulSoup 4 to obtain the Tweet text only, but I don't get the Tweet text, I only get the class printed. How can I get only the Tweet text? I only want the part highlighted in yellow in the screenshot below:

Script

import requests, bs4
from bs4 import BeautifulSoup

link = "https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201"

r = requests.get(link).text

soup = bs4.BeautifulSoup(r, "html")

tweet_text = soup.find("p", {"class": "TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text"})

content = str(tweet_text)

print(content)

Actual output:

<p class="TweetTextSize TweetTextSize--jumbo js-tw

Expected output:

i’m gonna need to take a moment to formulate an opinion and i’ll try to get back to y’all

Body:
This will code will work atleast for me it did
I thinks you got your output because your were using html instead of lxml

import requests
from bs4 import BeautifulSoup
#needed for bs4
import lxml

#url to the tweet
url = 'https://web.archive.org/web/20220210162643/https://twitter.com/toteskosh/status/1491809570997555201'

#get the page source
tweet = requests.get(url).text

soup = BeautifulSoup(tweet, "lxml")

#finds the tweet
tweet_text = soup.find("p", class_='TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text').text)
print(tweet_text)


问:
jquery selectors and disabled='disabled'
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...</p>

```<code><input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {
</code>```

答:
Try this instead. You can use each like this:

```<code>$('input[id^="pre"], select[id^="pre"]').each(function() { ... });
</code>```

Body:
I just noticed that a disabled input text field is not picked up in a selector when it is disabled. Is there a way to say select inputs disabled or not...

<input type="text" name="MYNAME" id="preXXXX" disabled='disabled' value="my Value"  />

$.each($('input[id^="pre"], select[id^="pre"]').serializeArray(), function() {

Body:
Try this instead. You can use each like this:

$('input[id^="pre"], select[id^="pre"]').each(function() { ... });