问:
Returning a big object from activity function throws an error
I have a Durable Functions instance with the following functions:

Starter/Trigger function. It uses a Storage Queue trigger. It also implements Singleton Orchestrator, because I want only one instance of the Orchestrator to run at a time:

```<code>async def main(msg: func.QueueMessage, starter: str) -> None:
    client = df.DurableOrchestrationClient(starter)
    payload = {"day": msg.get_body().decode('utf-8')}
    instance_id = msg.get_body().decode('utf-8')

    await client.terminate(instance_id, "New instance to be called")
    existing_instance = await client.get_status(instance_id)
    status = existing_instance.runtime_status

    if existing_instance.runtime_status in [df.OrchestrationRuntimeStatus.Completed, df.OrchestrationRuntimeStatus.Failed, df.OrchestrationRuntimeStatus.Terminated, None]:
        instance_id = await client.start_new("Orchestrator", instance_id, payload)
        logging.info(f"Started orchestration with ID = '{instance_id}'.")
        return
    else:
        return {
            'status': 409,
            'body': f"An instance with ID '${existing_instance.instance_id}' already exists"
        }
</code>```

Orchestrator function:

```<code>def orchestrator_function(context: df.DurableOrchestrationContext):
    input_context = context.get_input()
    day = input_context.get('day')
    day_date = datetime.datetime.strptime(day, '%y%m%d')
    day_raw = day_date.strftime('%Y%m%d')
    gps_data = yield context.call_activity('GetGPSData', day)
    logging.info("Downloaded blobs")
</code>```

Activity function:

```<code>def main(day: str) -> str:
    blob_data = download_blob(day)
    df_gps= pd.from_csv(blob_data)
    return df_gps.to_json()
</code>```

As you can see, the activity function simply downloads a blob (around 400MiB) from Azure Blob Storage, creates a dataframe out of it and returns the dataframe in JSON.

However, on execution, I get the following error:

```<code>[2022-12-12T10:53:03.677Z] 221101: Function 'Orchestrator (Orchestrator)' failed with an error. Reason: Message: Too many characters. The resulting number of bytes is larger than what can be returned as an int. (Parameter 'count')
 Unhandled exception while executing task: System.ArgumentOutOfRangeException: Too many characters. The resulting number of bytes is larger than what can be returned as an int. (Parameter 'count')
[2022-12-12T10:53:03.678Z]    at System.Text.UTF32Encoding.GetByteCount(Char* chars, Int32 count, EncoderNLS encoder)
[2022-12-12T10:53:03.678Z]    at System.Text.UTF32Encoding.GetByteCount(String s)
[2022-12-12T10:53:03.679Z]    at Microsoft.Azure.WebJobs.Extensions.DurableTask.DurableTaskExtension.GetIntputOutputTrace(String rawInputOutputData) in D:\a\_work\1\s\src\WebJobs.Extensions.DurableTask\DurableTaskExtension.cs:line 1480
</code>```

I would like to split and process the dataframe concurrently using the Fan In behavior further in other activity functions; however it seems like the output of the activity function is too big for the Orchestrator. What should I do instead of it in this scenario? I would be thankful for any suggestions as I have officially entered the 'losing my mind' phase of debugging this. I've already tried compressing the DataFrame in many ways, to no avail.

Body:
I have a Durable Functions instance with the following functions:

Starter/Trigger function. It uses a Storage Queue trigger. It also implements Singleton Orchestrator, because I want only one instance of the Orchestrator to run at a time:

async def main(msg: func.QueueMessage, starter: str) -> None:
    client = df.DurableOrchestrationClient(starter)
    payload = {"day": msg.get_body().decode('utf-8')}
    instance_id = msg.get_body().decode('utf-8')

    await client.terminate(instance_id, "New instance to be called")
    existing_instance = await client.get_status(instance_id)
    status = existing_instance.runtime_status

    if existing_instance.runtime_status in [df.OrchestrationRuntimeStatus.Completed, df.OrchestrationRuntimeStatus.Failed, df.OrchestrationRuntimeStatus.Terminated, None]:
        instance_id = await client.start_new("Orchestrator", instance_id, payload)
        logging.info(f"Started orchestration with ID = '{instance_id}'.")
        return
    else:
        return {
            'status': 409,
            'body': f"An instance with ID '${existing_instance.instance_id}' already exists"
        }

Orchestrator function:

def orchestrator_function(context: df.DurableOrchestrationContext):
    input_context = context.get_input()
    day = input_context.get('day')
    day_date = datetime.datetime.strptime(day, '%y%m%d')
    day_raw = day_date.strftime('%Y%m%d')
    gps_data = yield context.call_activity('GetGPSData', day)
    logging.info("Downloaded blobs")

Activity function:

def main(day: str) -> str:
    blob_data = download_blob(day)
    df_gps= pd.from_csv(blob_data)
    return df_gps.to_json()

As you can see, the activity function simply downloads a blob (around 400MiB) from Azure Blob Storage, creates a dataframe out of it and returns the dataframe in JSON.

However, on execution, I get the following error:

[2022-12-12T10:53:03.677Z] 221101: Function 'Orchestrator (Orchestrator)' failed with an error. Reason: Message: Too many characters. The resulting number of bytes is larger than what can be returned as an int. (Parameter 'count')
 Unhandled exception while executing task: System.ArgumentOutOfRangeException: Too many characters. The resulting number of bytes is larger than what can be returned as an int. (Parameter 'count')
[2022-12-12T10:53:03.678Z]    at System.Text.UTF32Encoding.GetByteCount(Char* chars, Int32 count, EncoderNLS encoder)
[2022-12-12T10:53:03.678Z]    at System.Text.UTF32Encoding.GetByteCount(String s)
[2022-12-12T10:53:03.679Z]    at Microsoft.Azure.WebJobs.Extensions.DurableTask.DurableTaskExtension.GetIntputOutputTrace(String rawInputOutputData) in D:\a\_work\1\s\src\WebJobs.Extensions.DurableTask\DurableTaskExtension.cs:line 1480

I would like to split and process the dataframe concurrently using the Fan In behavior further in other activity functions; however it seems like the output of the activity function is too big for the Orchestrator. What should I do instead of it in this scenario? I would be thankful for any suggestions as I have officially entered the 'losing my mind' phase of debugging this. I've already tried compressing the DataFrame in many ways, to no avail.


来源: stackexchange

问:
Snap Logic to Snowflake Connection using Key Pair Authentication
We used to have below field for OAuth2 in snapLogic while connecting to snowflake.

Authentication parameter value: refresh_token session:role:

However, while using key pair authentication, there is no field to put the functional role.

Hence, if the technical user was not created with default warehouse and default functional role, the snaplogic is unable to connect.

Any suggestions?

Thank You.

ContentLicense: CC BY-SA 4.0


问:
How to make a Expand/Collapse Button For Qtreeview in DOM model?
I have a Application which reads XML data and display it into Tree view, Now I want a button through which I can Expand/ Collapse the Qtreeview data at one click.
MainWindow.cpp

```<code>    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      model(new DomModel(QDomDocument(), this)),
      view(new QTreeView(this))
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
    fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);

    view->setModel(model);

    view->setSelectionMode(QAbstractItemView::MultiSelection);
    setCentralWidget(view);
    setWindowTitle(tr("QTreeViewXML"));

    //creating collapse button in treeview;
    A_collapse=new QPushButton("Collapse", this);
    A_collapse->setGeometry(QRect(QPoint(1400,300),QSize(200,45)));

    //creating selectAll button in treeview;
    S_selectAll=new QPushButton("SelectAll", this);
    S_selectAll->setGeometry(QRect(QPoint(1400,400),QSize(200,45)));

    connect(A_collapse, &QPushButton::released, this, &MainWindow::handleCollapse);
 //   connect(S_selectAll, &QPushButton::released, this, &MainWindow::handleSelectAll);

}
</code>```

OpenFile Function

```<code>void MainWindow::openFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
        xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                    "SVG files (*.svg);;User Interface files (*.ui)"));

    if (!filePath.isEmpty()) {
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly)) {
            QDomDocument document;
            if (document.setContent(&file)) {
                DomModel *newModel = new DomModel(document, this);
                view->setModel(newModel);
                delete model;
                model = newModel;
                xmlPath = filePath;
            }
            file.close();
        }
    }
}
</code>```

Unimplemented Button Function

```<code>void MainWindow::handleCollapse(){
}

void MainWindow::handleSelectAll(){
}

</code>```

I have buttons placed, now what I have to code?

Body:
I have a Application which reads XML data and display it into Tree view, Now I want a button through which I can Expand/ Collapse the Qtreeview data at one click.
MainWindow.cpp

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      model(new DomModel(QDomDocument(), this)),
      view(new QTreeView(this))
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(tr("&Open..."), this, &MainWindow::openFile, QKeySequence::Open);
    fileMenu->addAction(tr("E&xit"), this, &QWidget::close, QKeySequence::Quit);

    view->setModel(model);

    view->setSelectionMode(QAbstractItemView::MultiSelection);
    setCentralWidget(view);
    setWindowTitle(tr("QTreeViewXML"));

    //creating collapse button in treeview;
    A_collapse=new QPushButton("Collapse", this);
    A_collapse->setGeometry(QRect(QPoint(1400,300),QSize(200,45)));

    //creating selectAll button in treeview;
    S_selectAll=new QPushButton("SelectAll", this);
    S_selectAll->setGeometry(QRect(QPoint(1400,400),QSize(200,45)));

    connect(A_collapse, &QPushButton::released, this, &MainWindow::handleCollapse);
 //   connect(S_selectAll, &QPushButton::released, this, &MainWindow::handleSelectAll);

}

OpenFile Function

void MainWindow::openFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Open File"),
        xmlPath, tr("XML files (*.xml);;HTML files (*.html);;"
                    "SVG files (*.svg);;User Interface files (*.ui)"));

    if (!filePath.isEmpty()) {
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly)) {
            QDomDocument document;
            if (document.setContent(&file)) {
                DomModel *newModel = new DomModel(document, this);
                view->setModel(newModel);
                delete model;
                model = newModel;
                xmlPath = filePath;
            }
            file.close();
        }
    }
}

Unimplemented Button Function

void MainWindow::handleCollapse(){
}

void MainWindow::handleSelectAll(){
}

I have buttons placed, now what I have to code?


问:
Chrome extension | Getting Local Storage
I tried to read all the local storage items, but I'm missing a lot of items.

I'ved tried this approach: (manifest 2.0)

```<code>chrome.storage.local.get(null, function (items) {
      console.log('localStorage: ', items);
    });
</code>```

I get a list of 3 items when checking the dev tools "local storage" tab I see more than 20 items.

Body:
I tried to read all the local storage items, but I'm missing a lot of items.

I'ved tried this approach: (manifest 2.0)

chrome.storage.local.get(null, function (items) {
      console.log('localStorage: ', items);
    });

I get a list of 3 items when checking the dev tools "local storage" tab I see more than 20 items.


问:
how to animate a variable change in css keyframes
I want to animate the waves to go up when i click on the div i cant get the wave to animate when i change the heigt on the animation it self.

.tsx

```<code>          <div className={styles.circle}>
            <div className={styles.wave}></div>
          </div>
</code>```

.css

```<code>.circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-190%, -50%);
  width: 25%;
  height: 60%;
  background: #ccc;
  box-shadow: 0 0 0 5px #fff;
  border-radius: 50%;
  overflow: hidden;
}
.wave {
  position: relative;
  width: 100%;
  height: 100%;
  background: #4973ff;
  border-radius: 50%;
  box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.5);
}
.wave:before,
.wave:after {
  content: "";
  position: absolute;
  width: 200%;
  height: 200%;
  top: 0;
  left: 50%;
  transform: translate(-50%, -75%);
  background: #000;
}
.wave:before {
  border-radius: 45%;
  background: rgb(255, 255, 255);
  animation: animate 5s linear infinite;
}
.wave:after {
  border-radius: 40%;
  background: rgb(255, 255, 255, 0.5);
  animation: animate 10s linear infinite;
}

@keyframes animate {
  0% {
    transform: translate(-50%, var(--water)) rotate(0deg);
  }
  100% {
    transform: translate(-50%, var(--water)) rotate(360deg);

  }
}
</code>```

I tried putting translate: transform 2s linear but that didnt work for me eighter do you guys have any idea beaces when i change the

```<code>:root {
--water: -90%
}
</code>```

to

```<code>:root {
--water: -80%
}
</code>```

it will just snap and not animate

Body:
I want to animate the waves to go up when i click on the div i cant get the wave to animate when i change the heigt on the animation it self.

.tsx

.css

.circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-190%, -50%);
  width: 25%;
  height: 60%;
  background: #ccc;
  box-shadow: 0 0 0 5px #fff;
  border-radius: 50%;
  overflow: hidden;
}
.wave {
  position: relative;
  width: 100%;
  height: 100%;
  background: #4973ff;
  border-radius: 50%;
  box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.5);
}
.wave:before,
.wave:after {
  content: "";
  position: absolute;
  width: 200%;
  height: 200%;
  top: 0;
  left: 50%;
  transform: translate(-50%, -75%);
  background: #000;
}
.wave:before {
  border-radius: 45%;
  background: rgb(255, 255, 255);
  animation: animate 5s linear infinite;
}
.wave:after {
  border-radius: 40%;
  background: rgb(255, 255, 255, 0.5);
  animation: animate 10s linear infinite;
}

@keyframes animate {
  0% {
    transform: translate(-50%, var(--water)) rotate(0deg);
  }
  100% {
    transform: translate(-50%, var(--water)) rotate(360deg);

  }
}

I tried putting translate: transform 2s linear but that didnt work for me eighter do you guys have any idea beaces when i change the

:root {
--water: -90%
}

to

:root {
--water: -80%
}

it will just snap and not animate


问:
afterUpdate listener in typeorm does not listen to updates on @UpdateDateColumn - postgres DB
I'm working on a functionality, where in I have an entity called 'Employee' with a few columns like first name, last name, DOB, etc. and two columns:createdAt and updatedAt defined with @CreateDateColumn and @UpdateDateColumn respectively.

My requirement is that, whenever an update operation is performed on this entity, I should be logging the column name that was updated, along with the old and new value that it holds.

I'm performing the update on Employee table using queryRunner.manager.save()

To track the changes,
I'm making use of the entity subscribers 'afterUpdate' event.

Now on performing an update, for e.g. When I change the Name, my Employee entity is correctly updating the name as well as the 'updatedAt' field to current timestamp in DB
However,my 'afterUpdate' listener is only logging the 'name' column with its old and new values.
Its not logging the updatedAt column.

Can anyone please help me understand what's possibly going wrong here?

Entity definition:
...All columns (first name, etc.)
@UpdateDateColumn({name:'updated_at',type:'timestamp',nullable:true})
updatedAt:Date;

Subscriber code:

```<code>@EventSubscriber()
export class EmployeeSubscriber implements
EntitySubscriberInterface<EmployeeEntity> {
constructor()
{}
listenTo() {
return EmployeeEntity;
}

afterUpdate(event: UpdateEvent<EmployeeEnitity>){
const {updatedColumns, dataBaseEntity,entity}=event;
updatedColumns.forEach(({propertyName})=>{
//Get the updated column name and old and new values
//col_name = propertyName;
//oldVal= databaseEntity[propertyName as keyof EmployeeEntity] as string,
//newVal= entity?.[propertyName as keyof EmployeeEntity] as string,
})
}
}
</code>```

I tried using different save operations (via repository, queryRunner, manager), but it didn't work.
Official docs say the event is triggered only on save operation.

If I manually pass the date to updatedAt field, then I am able to get the field within the event handler, but I don't think that's the right approach as manual intervention should not be needed for @UpdateDateColumn

Body:
I'm working on a functionality, where in I have an entity called 'Employee' with a few columns like first name, last name, DOB, etc. and two columns:createdAt and updatedAt defined with @CreateDateColumn and @UpdateDateColumn respectively.

My requirement is that, whenever an update operation is performed on this entity, I should be logging the column name that was updated, along with the old and new value that it holds.

I'm performing the update on Employee table using queryRunner.manager.save()

To track the changes,
I'm making use of the entity subscribers 'afterUpdate' event.

Now on performing an update, for e.g. When I change the Name, my Employee entity is correctly updating the name as well as the 'updatedAt' field to current timestamp in DB
However,my 'afterUpdate' listener is only logging the 'name' column with its old and new values.
Its not logging the updatedAt column.

Can anyone please help me understand what's possibly going wrong here?

Entity definition:
...All columns (first name, etc.)
@UpdateDateColumn({name:'updated_at',type:'timestamp',nullable:true})
updatedAt:Date;

Subscriber code:

@EventSubscriber()
export class EmployeeSubscriber implements
EntitySubscriberInterface<EmployeeEntity> {
constructor()
{}
listenTo() {
return EmployeeEntity;
}

afterUpdate(event: UpdateEvent<EmployeeEnitity>){
const {updatedColumns, dataBaseEntity,entity}=event;
updatedColumns.forEach(({propertyName})=>{
//Get the updated column name and old and new values
//col_name = propertyName;
//oldVal= databaseEntity[propertyName as keyof EmployeeEntity] as string,
//newVal= entity?.[propertyName as keyof EmployeeEntity] as string,
})
}
}

I tried using different save operations (via repository, queryRunner, manager), but it didn't work.
Official docs say the event is triggered only on save operation.

If I manually pass the date to updatedAt field, then I am able to get the field within the event handler, but I don't think that's the right approach as manual intervention should not be needed for @UpdateDateColumn


问:
Passing string parameters for all internal queries as varchar and not nvarchar using pyodbc in Airflow
Background: We have Airflow 2.4.3 and the metadata database is SQL Server. Basically this one , our case uses sql server .

So, the connection for the internal db is through this connection string

```<code>[database]

sql_alchemy_conn = mssql+pyodbc://{{ database.user }}:{{ airflow_db_password }}@{{ database.server }}:{{ database.port }}/{{ database.name }}?driver=ODBC+Driver+17+for+SQL+Server
load_default_connections = False
</code>```

Now, the problem is : all of the internal update queries (e.g. when a task is done) sends parameters as nvarchar.

In JDBC we can do something like this : setSendStringParametersAsUnicode.

How does one go about doing the same for pyodbc , connecting to sql sever? Is it possible? I could not find the same method for ODBC.

Problem is these metadata tables have the column data type as varchar, with unique indexes on them and since these internal airflow update queries pass on string parameters as nvarchar, it results in table scans and often deadlocks.

Example of an internal update query

```<code>declare @p1 int
set @p1=2603
exec sp_prepexec @p1 output,N'@P1 nvarchar(18),@P2 nvarchar(40),@P3 nvarchar(72),@P4 nvarchar(60),@P5 int',N'UPDATE task_instance SET state=@P1 WHERE task_instance.dag_id = @P2 AND task_instance.run_id = @P3 AND task_instance.task_id = @P4 AND task_instance.map_index = @P5',N'scheduled',N'lead_value_score_1_1',N'scheduled__2022-12-10T09:12:00+00:00',N'predict_funding_scores_instant',-1

</code>```

Notice that all the columns in the where clause are passed on as nvarchar, whereas the table has them as varchar.

Any questions and I can try to answer them.

These update queries are airflow internal and thus we don't control them and thus trying to see if these can be set on the connection level.

Body:
Background: We have Airflow 2.4.3 and the metadata database is SQL Server. Basically this one , our case uses sql server .

So, the connection for the internal db is through this connection string

[database]

sql_alchemy_conn = mssql+pyodbc://{{ database.user }}:{{ airflow_db_password }}@{{ database.server }}:{{ database.port }}/{{ database.name }}?driver=ODBC+Driver+17+for+SQL+Server
load_default_connections = False

Now, the problem is : all of the internal update queries (e.g. when a task is done) sends parameters as nvarchar.

In JDBC we can do something like this : setSendStringParametersAsUnicode.

How does one go about doing the same for pyodbc , connecting to sql sever? Is it possible? I could not find the same method for ODBC.

Problem is these metadata tables have the column data type as varchar, with unique indexes on them and since these internal airflow update queries pass on string parameters as nvarchar, it results in table scans and often deadlocks.

Example of an internal update query

declare @p1 int
set @p1=2603
exec sp_prepexec @p1 output,N'@P1 nvarchar(18),@P2 nvarchar(40),@P3 nvarchar(72),@P4 nvarchar(60),@P5 int',N'UPDATE task_instance SET state=@P1 WHERE task_instance.dag_id = @P2 AND task_instance.run_id = @P3 AND task_instance.task_id = @P4 AND task_instance.map_index = @P5',N'scheduled',N'lead_value_score_1_1',N'scheduled__2022-12-10T09:12:00+00:00',N'predict_funding_scores_instant',-1

Notice that all the columns in the where clause are passed on as nvarchar, whereas the table has them as varchar.

Any questions and I can try to answer them.

These update queries are airflow internal and thus we don't control them and thus trying to see if these can be set on the connection level.


问:
pyspark two columns ids fusion
I would like to solve a problem with columns identifiers. I have a dataframe with two columns, containing two different ids:

id1
id2

A1
B1

A2
B1

A2
B2

A3
B2

A3
B2

A3
B3

A4
B3

A4
B4

A5
B5

A6
B5

A6
B6

A6
B6

A6
B7

A6
B7

A6
B7

I would like to merge both ids and create only one. It looks like a connected components problem, but I tried graphframes library from pyspark and cannot handle all the data (100M rows).

The perfect solution would be to avoid connected components and with basic operations, try to merge both ids and obtain this solution:

id1
id2
ID

A1
B1
C1

A2
B1
C1

A2
B2
C1

A3
B2
C1

A3
B2
C1

A3
B3
C1

A4
B3
C1

A4
B4
C1

A5
B5
C2

A6
B5
C2

A6
B6
C2

A6
B6
C2

A6
B7
C2

A6
B7
C2

A6
B7
C2

Any idea?

from graphframes import GraphFrame

I tried connected components but the dataframe is too large for this library

Title: pyspark two columns ids fusion


问:
C# MongoDb.Driver does not return newly created entity in collection
I'm trying to test the insertion of the newly created user in my MongoDb instance via SpecFlow. Unfortunately, my tests are failing because the database provider does not return the newly created instance, but I can see them added into the database via MongoDB Compass.

Test:

protected async Task<AuthUserDto> SignUp(string name, string email, string password)
{
    var request = new SignUpRequest(name, email, password);
    var content = CreateHttContent(request);
    await Client.PostAsync(RouteConstants.SignUp, content);

    await SignInWithPlatformAdmin();
    var response = await Client.GetAsync(Users.Presentation.Constants.RouteConstants.GetUsers);
    var apiResponse = await CastClientResponseContent<MessageSuccessApiResponse<List<AuthUserDto>>>(response);
    ClearClientAuthorizationHeader();

    // API response does not contain any user
    return apiResponse!.Data.First(x => x.Email == email);
}
```
<p>I'm creating the user and immediately try to get him back via API call (uses <code>AuthUserDtoRepository</code>). I have noticed that I can get the user via the <code>IMongoRepository</code> class, but not via <code>IMongoDbContext</code>. But <code>IMongoRepository</code> uses <code>IMongoDbContext</code> under the hood.</p>
<p>The exploration can be seen in the snippet of the <code>AuthUserDtoRepository</code> in the method <code>GetAllAsync</code>.</p>
<p>In the following, you can see my code setup.</p>
<p><strong>MongoDB configuration:</strong></p>
<pre class="lang-cs prettyprint-override"><code>public static void AddAuthServices(this IServiceCollection services, IConfiguration configuration)
{
    var mongoDbConfigSection = configuration.GetRequiredSection(MongoDbConfigConstants.SectionKey);
    services.Configure<MongoDbConfig>(mongoDbConfigSection);
    var mongoDbConfig = mongoDbConfigSection.Get<MongoDbConfig>();

    services.AddIdentity<AuthUser, AuthRole>(options => { options.User.RequireUniqueEmail = true; })
        .AddMongoDbStores<AuthUser, AuthRole, Guid>(mongoDbConfig.Connection, mongoDbConfig.Database)
        .AddDefaultTokenProviders();

    ...
}
</code>```

Get Users:

internal sealed class AuthUserDtoRepository : IAuthUserDtoRepository
{
    private readonly IAuthUserMapping _authUserMapping;
    private readonly IMongoDbContext _mongoDbContext;
    private readonly IMongoRepository _mongoRepository;
    private readonly IUserStore<AuthUser> _userStore;

    public AuthUserDtoRepository(IAuthUserMapping authUserMapping, IMongoDbContext mongoDbContext, IMongoRepository mongoRepository, IUserStore<AuthUser> userStore)
    {
        _authUserMapping = authUserMapping;
        _mongoDbContext = mongoDbContext;
        _mongoRepository = mongoRepository;
        _userStore = userStore;
    }

    private IMongoCollection<AuthUser> AuthUserCollection =>
        _mongoDbContext.GetCollection<AuthUser>(CollectionConstants.CollectionNames.AuthUsers);

    private IMongoCollection<AuthRole> AuthRoleCollection =>
        _mongoDbContext.GetCollection<AuthRole>(CollectionConstants.CollectionNames.AuthRoles);

    public async Task<List<T>> GetAllAsync<T>() where T : IAuthUserDto
    {
        // usersFromMongoRepository: returns the created user
        var usersFromMongoRepository = await _mongoRepository.GetAllAsync<AuthUser>(_ => true);
        // usersFromMongoDbContext: empty
        var usersFromMongoDbContext = await AuthUserCollection.Find(_ => true).ToListAsync();
        // usersFromUserStore: empty
        var usersFromUserStore = await _userStore.FindByIdAsync(usersFromMongoRepository.First().Id.ToString(), CancellationToken.None);

        return await AuthUserCollection.Aggregate()
            .Lookup<AuthUser, AuthRole, AuthUserRoleLookup>(AuthRoleCollection, user => user.Roles, role => role.Id,
                userRole => userRole.Roles).Project(_authUserMapping.Map<T>()).ToListAsync();
    }
}
```

I would appreciate any tips on how I can get the up-to-date data from MongoDb via IMongoDbContext or via the MongoClient directly.

Body:
I'm trying to test the insertion of the newly created user in my MongoDb instance via SpecFlow. Unfortunately, my tests are failing because the database provider does not return the newly created instance, but I can see them added into the database via MongoDB Compass.

Test:

protected async Task<AuthUserDto> SignUp(string name, string email, string password)
{
    var request = new SignUpRequest(name, email, password);
    var content = CreateHttContent(request);
    await Client.PostAsync(RouteConstants.SignUp, content);

    await SignInWithPlatformAdmin();
    var response = await Client.GetAsync(Users.Presentation.Constants.RouteConstants.GetUsers);
    var apiResponse = await CastClientResponseContent<MessageSuccessApiResponse<List<AuthUserDto>>>(response);
    ClearClientAuthorizationHeader();

    // API response does not contain any user
    return apiResponse!.Data.First(x => x.Email == email);
}

I'm creating the user and immediately try to get him back via API call (uses AuthUserDtoRepository). I have noticed that I can get the user via the IMongoRepository class, but not via IMongoDbContext. But IMongoRepository uses IMongoDbContext under the hood.

The exploration can be seen in the snippet of the AuthUserDtoRepository in the method GetAllAsync.

In the following, you can see my code setup.

MongoDB configuration:

public static void AddAuthServices(this IServiceCollection services, IConfiguration configuration)
{
    var mongoDbConfigSection = configuration.GetRequiredSection(MongoDbConfigConstants.SectionKey);
    services.Configure<MongoDbConfig>(mongoDbConfigSection);
    var mongoDbConfig = mongoDbConfigSection.Get<MongoDbConfig>();

    services.AddIdentity<AuthUser, AuthRole>(options => { options.User.RequireUniqueEmail = true; })
        .AddMongoDbStores<AuthUser, AuthRole, Guid>(mongoDbConfig.Connection, mongoDbConfig.Database)
        .AddDefaultTokenProviders();

    ...
}

Get Users:

internal sealed class AuthUserDtoRepository : IAuthUserDtoRepository
{
    private readonly IAuthUserMapping _authUserMapping;
    private readonly IMongoDbContext _mongoDbContext;
    private readonly IMongoRepository _mongoRepository;
    private readonly IUserStore<AuthUser> _userStore;

    public AuthUserDtoRepository(IAuthUserMapping authUserMapping, IMongoDbContext mongoDbContext, IMongoRepository mongoRepository, IUserStore<AuthUser> userStore)
    {
        _authUserMapping = authUserMapping;
        _mongoDbContext = mongoDbContext;
        _mongoRepository = mongoRepository;
        _userStore = userStore;
    }

    private IMongoCollection<AuthUser> AuthUserCollection =>
        _mongoDbContext.GetCollection<AuthUser>(CollectionConstants.CollectionNames.AuthUsers);

    private IMongoCollection<AuthRole> AuthRoleCollection =>
        _mongoDbContext.GetCollection<AuthRole>(CollectionConstants.CollectionNames.AuthRoles);

    public async Task<List<T>> GetAllAsync<T>() where T : IAuthUserDto
    {
        // usersFromMongoRepository: returns the created user
        var usersFromMongoRepository = await _mongoRepository.GetAllAsync<AuthUser>(_ => true);
        // usersFromMongoDbContext: empty
        var usersFromMongoDbContext = await AuthUserCollection.Find(_ => true).ToListAsync();
        // usersFromUserStore: empty
        var usersFromUserStore = await _userStore.FindByIdAsync(usersFromMongoRepository.First().Id.ToString(), CancellationToken.None);

        return await AuthUserCollection.Aggregate()
            .Lookup<AuthUser, AuthRole, AuthUserRoleLookup>(AuthRoleCollection, user => user.Roles, role => role.Id,
                userRole => userRole.Roles).Project(_authUserMapping.Map<T>()).ToListAsync();
    }
}

I would appreciate any tips on how I can get the up-to-date data from MongoDb via IMongoDbContext or via the MongoClient directly.


问:
show error if Xml element is less than 15 words
Show the error message if the Element tag  value is less than 15 words?

This is my xml file

<books>
  <book id="bk110">
    <author>O'Brien, Tim</author>
    <title>Microsoft .NET: The Programming Bible</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-09</publish_date>
    <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description>
  </book>
  <book id="bk111">
    <author>O'Brien, Tim</author>
    <title>MSXML3: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-01</publish_date>
    <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description>
  </book>
</books>
```

I am stucked. I am not getting logic

Body:
Show the error message if the Element tag  value is less than 15 words?

This is my xml file

<books>
  <book id="bk110">
    <author>O'Brien, Tim</author>
    <title>Microsoft .NET: The Programming Bible</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-09</publish_date>
    <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description>
  </book>
  <book id="bk111">
    <author>O'Brien, Tim</author>
    <title>MSXML3: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-01</publish_date>
    <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description>
  </book>
</books>

I am stucked. I am not getting logic


问:
Load new set of geometry per frame in Vulkan
I try to develop a render server thats draw an any scene per request.
I need to destroy the previous scene and load new one when new request is incoming. But also I need create a new pipeline with new VkPipelineVertexInputStateCreateInfo.

Can I do without pipeline recreation ?

IMO the best approach is to create just 1 VBO and 1 IBO, but I dont understand how to use offset in IBO to perform drawing. Is it possible ?


问:
Symfony Monolog container error once every 500 requests
Since upgrading to PHP 8.1, Symfony 6.1, Monolog 3.2, I have been seeing a PHP fatal error while constructing the Symfony DI container:

```<code>2022/12/12 04:10:02 [error] 31#31: *919 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught TypeError: Monolog\Logger::getLevelName(): Argument #1 ($level) must be of type Monolog\Level|int, Symfony\Bridge\Monolog\Handler\ConsoleHandler given, called in /app/vendor/monolog/monolog/src/Monolog/Logger.php on line 196 and defined in /app/vendor/monolog/monolog/src/Monolog/Logger.php:437
Stack trace:
#0 /app/vendor/monolog/monolog/src/Monolog/Logger.php(196): Monolog\Logger::getLevelName()
#1 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1441): Monolog\Logger->pushHandler()
#2 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1103): ContainerOqglp2q\App_KernelProdContainer->getMonolog_Logger_RequestService()
#3 /app/vendor/symfony/dependency-injection/Container.php(218): ContainerOqglp2q\App_KernelProdContainer->getHttpKernelService()
#4 /app/vendor/symfony/dependency-injection/Container.php(198): Symfony\Component\DependencyInjection\Container->make()
#5 /app/vendor/symfony/http-kernel/Kernel.php(195): Symfony\Compone" while reading response header from upstream, client: 172.27.0.16, server: _, request: "POST /job-engine-client/execute HTTP/1.0", upstream: "fastcgi://192.168.64.5:9000", host: "x"
</code>```

I have not been able to reproduce the error manually, as it only happens in my staging environment, and very inconsistent.
It is currently only visible in HTTP requests triggered by a cronjob every 5 minutes. In the past 4 days, it only happened 2 times.

The application is deployed using docker compose, with a custom Ubuntu Dockerfile.
The application is deployed to multiple hosts, and shows the same random occurence of errors on each host.

When looking at the Monolog Logger.php file, it is really hard to understand how the stack trace that is logged can be ever triggered.

I'm suspecting some kind of PHP opcache or JIT issue, or perhaps an issue with the docker filesystem returning some other cached (older) versions of files.

Has anyone seen similar errors, or perhaps other suggestions how to debug & resolve this issue?

Body:
Since upgrading to PHP 8.1, Symfony 6.1, Monolog 3.2, I have been seeing a PHP fatal error while constructing the Symfony DI container:

2022/12/12 04:10:02 [error] 31#31: *919 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught TypeError: Monolog\Logger::getLevelName(): Argument #1 ($level) must be of type Monolog\Level|int, Symfony\Bridge\Monolog\Handler\ConsoleHandler given, called in /app/vendor/monolog/monolog/src/Monolog/Logger.php on line 196 and defined in /app/vendor/monolog/monolog/src/Monolog/Logger.php:437
Stack trace:
#0 /app/vendor/monolog/monolog/src/Monolog/Logger.php(196): Monolog\Logger::getLevelName()
#1 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1441): Monolog\Logger->pushHandler()
#2 /app/var/cache/prod/ContainerOqglp2q/App_KernelProdContainer.php(1103): ContainerOqglp2q\App_KernelProdContainer->getMonolog_Logger_RequestService()
#3 /app/vendor/symfony/dependency-injection/Container.php(218): ContainerOqglp2q\App_KernelProdContainer->getHttpKernelService()
#4 /app/vendor/symfony/dependency-injection/Container.php(198): Symfony\Component\DependencyInjection\Container->make()
#5 /app/vendor/symfony/http-kernel/Kernel.php(195): Symfony\Compone" while reading response header from upstream, client: 172.27.0.16, server: _, request: "POST /job-engine-client/execute HTTP/1.0", upstream: "fastcgi://192.168.64.5:9000", host: "x"

I have not been able to reproduce the error manually, as it only happens in my staging environment, and very inconsistent.
It is currently only visible in HTTP requests triggered by a cronjob every 5 minutes. In the past 4 days, it only happened 2 times.

The application is deployed using docker compose, with a custom Ubuntu Dockerfile.
The application is deployed to multiple hosts, and shows the same random occurence of errors on each host.

When looking at the Monolog Logger.php file, it is really hard to understand how the stack trace that is logged can be ever triggered.

I'm suspecting some kind of PHP opcache or JIT issue, or perhaps an issue with the docker filesystem returning some other cached (older) versions of files.

Has anyone seen similar errors, or perhaps other suggestions how to debug & resolve this issue?


问:
Changing Units of time-Dimension of a NetCDF in R
In R I want to write out a NetCDF from a raster stack using the terra package.

With terra::writeCDF I can modify the name of my time-Dimension. I also want to change the units of this dimension, which is so far unknown.
Does anybody know how to implement this, if possible within the writeCDF function?


问:
PyQt hiding widget for set period of time
I'm presenting Matplotlib charts in PyQt, and I need to blank the screen for 5 seconds in-between the charts. For some reason the chart is never hidden, rather a delay of 5 seconds before presenting new chart. I believe this is todo with PyQt threading. Does anyone know how to achieve this?</p>
```<code>self.centralWidget().hide()
time.sleep(5)
self.newChart()
</code>```

Body:
I'm presenting Matplotlib charts in PyQt, and I need to blank the screen for 5 seconds in-between the charts. For some reason the chart is never hidden, rather a delay of 5 seconds before presenting new chart. I believe this is todo with PyQt threading. Does anyone know how to achieve this?

self.centralWidget().hide()
time.sleep(5)
self.newChart()


问:
How can I change title of an animated barplot created with ggplot in r, in each frame?
I've built an animated barplot with ggplot and gganimate.
Nevertheless, I would like to add a title and description every time the graph moves, for example entering the year per each frame.

the actual code is the following:

library(ggplot2)
library(gganimate)
library(animation)
library(gifski)

a <- data.frame(group=df_AllYears$Teams, values=df_16$Average16,
       frame=rep('a',10))
b <- data.frame(group=df_AllYears$Teams, values=df_17$Average17,
       frame=rep('b',10))
c <- data.frame(group=df_AllYears$Teams, values=df_18$Average18,
       frame=rep('c',10))
d <- data.frame(group=df_AllYears$Teams, values=df_19$Average19,
       frame=rep('d',10))
e <- data.frame(group=df_AllYears$Teams, values=df_20$Average20,
       frame=rep('e',10))
f <- data.frame(group=df_AllYears$Teams, values=df_21$Average21,
       frame=rep('f',10))
g <- data.frame(group=df_AllYears$Teams, values=df_22$Average22,
       frame=rep('g',10))

data <- rbind(a,b,c,d,e,f,g)

ggplot(a, aes(x=group, y=values, fill=group)) +
  geom_bar(stat='identity')

myPlot<- ggplot(data, aes(x=group, y=values, fill=group)) +
  geom_bar(stat='identity',) +
  scale_fill_manual("legend", values = c("Ferrari"="#BC2129",
     "McLaren"="#FF8900", "Mercedes"="#029B95",
     "Toro Rosso"="#0D1623", "Renault"="#FFD503",
     "Red Bull"="#10233B", "Haas F1 Team"="#EA1A39",
     "Sauber"="#9E2233",
     "Force India"="#F8AFD2","Williams"="#00A1E4")) +
  theme_bw() +
  theme(axis.text.x = element_blank(), legend.position = "bottom",
    axis.ticks.x = element_blank(),axis.ticks.y = element_blank(),
    legend.title = element_blank(), axis.text.y =
     element_text(hjust = 0), axis.title.y =
     element_text(vjust = 3),
     legend.text = element_text(family = "Montserrat Alternates"))
     +
  labs(x="", y="Trend over the years")+
  # gganimate specific bits:
  transition_states(
    frame,
    transition_length = 3,
    state_length = 2
  ) +
  ease_aes('sine-in-out')

# Save at gif:
animate(myPlot, duration = 1, fps = 20, width =400, height =300,
    renderer = gifski_renderer())
anim_save("outpumarameot.gif")

```

Really hope someone can help me, I've already spent so many hours on this problem since yesterday.

Body:
I've built an animated barplot with ggplot and gganimate.
Nevertheless, I would like to add a title and description every time the graph moves, for example entering the year per each frame.

the actual code is the following:

library(ggplot2)
library(gganimate)
library(animation)
library(gifski)

a <- data.frame(group=df_AllYears$Teams, values=df_16$Average16,
       frame=rep('a',10))
b <- data.frame(group=df_AllYears$Teams, values=df_17$Average17,
       frame=rep('b',10))
c <- data.frame(group=df_AllYears$Teams, values=df_18$Average18,
       frame=rep('c',10))
d <- data.frame(group=df_AllYears$Teams, values=df_19$Average19,
       frame=rep('d',10))
e <- data.frame(group=df_AllYears$Teams, values=df_20$Average20,
       frame=rep('e',10))
f <- data.frame(group=df_AllYears$Teams, values=df_21$Average21,
       frame=rep('f',10))
g <- data.frame(group=df_AllYears$Teams, values=df_22$Average22,
       frame=rep('g',10))

data <- rbind(a,b,c,d,e,f,g)

ggplot(a, aes(x=group, y=values, fill=group)) +
  geom_bar(stat='identity')

myPlot<- ggplot(data, aes(x=group, y=values, fill=group)) +
  geom_bar(stat='identity',) +
  scale_fill_manual("legend", values = c("Ferrari"="#BC2129",
     "McLaren"="#FF8900", "Mercedes"="#029B95",
     "Toro Rosso"="#0D1623", "Renault"="#FFD503",
     "Red Bull"="#10233B", "Haas F1 Team"="#EA1A39",
     "Sauber"="#9E2233",
     "Force India"="#F8AFD2","Williams"="#00A1E4")) +
  theme_bw() +
  theme(axis.text.x = element_blank(), legend.position = "bottom",
    axis.ticks.x = element_blank(),axis.ticks.y = element_blank(),
    legend.title = element_blank(), axis.text.y =
     element_text(hjust = 0), axis.title.y =
     element_text(vjust = 3),
     legend.text = element_text(family = "Montserrat Alternates"))
     +
  labs(x="", y="Trend over the years")+
  # gganimate specific bits:
  transition_states(
    frame,
    transition_length = 3,
    state_length = 2
  ) +
  ease_aes('sine-in-out')

# Save at gif:
animate(myPlot, duration = 1, fps = 20, width =400, height =300,
    renderer = gifski_renderer())
anim_save("outpumarameot.gif")

Really hope someone can help me, I've already spent so many hours on this problem since yesterday.


问:
Combine multiple videos in one video in flutter app
I want to combine multiple videos that user uploads from gallery in Flutter app and merge them as one video before uploading to the server. Anyone can help me in this issue

I tried FFmpeg Cli and Ffmpeg


问:
No arguments were provided while testing a crypting static method
I'm trying to test a static crypting method in a public class, the method:

```<code> public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);
        }
</code>```

My Test:

```<code>[Test]
        public void EncryptStringTest(string key, string plainText, string expected)
        {
            string actual = CryptoHelper.EncryptString("amira", "amira");
            string expct = "amira";
            Assert.AreEqual(actual, expct);
        }
</code>```

I get an No arguments were provided error after executing the test

Body:
I'm trying to test a static crypting method in a public class, the method:

 public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);
        }

My Test:

[Test]
        public void EncryptStringTest(string key, string plainText, string expected)
        {
            string actual = CryptoHelper.EncryptString("amira", "amira");
            string expct = "amira";
            Assert.AreEqual(actual, expct);
        }

I get an No arguments were provided error after executing the test


问:
$filter ignored by OData when specifying additional parameters
When adding parameters to a call to an OData endpoint in my application like this

```<code>https://localhost:12345/TestServer/RequestDto
?$count=true&$orderby=TimeStamp%20desc
&$filter=(Ownername%20eq%20%27Baggins%2C%20Frodo%27)
&$skip=0&$top=26&userID=bt0388&showByAuthor=False
</code>```

the $filter seems to be getting ignored. userID and showByAuthor are the additional parameters.

The related endpoint looks like this.

```<code>public class RequestDtoController : ODataController
{
    // ...
    [EnableQuery]
    public IQueryable<DocumentRequestDTO> Get(string userID, bool showByAuthor)
    {
        // ...
    }
</code>```

It does get called with proper parameters. The data it returns is correct and complete.

I expect the OData layer to apply the filter, but it doesn't. This is the final result set:

```<code>{@odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto", @odata.count: 4,…}
@odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto"
@odata.count: 4
value:
    [{ID: "dc3a6999", AuthorID: "0388", Authorname: "Wonka, Willy",…},…]
    0:
        {ID: "dc3a6999", AuthorID: "0388", Authorname: "Wonka, Willy",…}
        Ownername: "Wonka, Willy"
        ...
    1:
        {ID: "685b7e33", AuthorID: "Test-Owner", Authorname: "Test, Owner",…}
        Ownername: "Wonka, Willy"
        ...
    2: {ID: "8192d591", AuthorID: "0003", Authorname: "Hedgehog, Sonic",…}
        Ownername: "Baggins, Frodo"
        ...
    3: {ID: "b56b7cfc", AuthorID: "0003", Authorname: "Hedgehog, Sonic",…}
        Ownername: "Baggins, Frodo"
        ...
</code>```

How would I need to go about fixing it?

Body:
When adding parameters to a call to an OData endpoint in my application like this

https://localhost:12345/TestServer/RequestDto
?$count=true&$orderby=TimeStamp%20desc
&$filter=(Ownername%20eq%20%27Baggins%2C%20Frodo%27)
&$skip=0&$top=26&userID=bt0388&showByAuthor=False

the $filter seems to be getting ignored. userID and showByAuthor are the additional parameters.

The related endpoint looks like this.

public class RequestDtoController : ODataController
{
    // ...
    [EnableQuery]
    public IQueryable<DocumentRequestDTO> Get(string userID, bool showByAuthor)
    {
        // ...
    }

It does get called with proper parameters. The data it returns is correct and complete.

I expect the OData layer to apply the filter, but it doesn't. This is the final result set:

{@odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto", @odata.count: 4,…}
@odata.context: "https://localhost:44393/DocServer2/$metadata#RequestDto"
@odata.count: 4
value:
    [{ID: "dc3a6999", AuthorID: "0388", Authorname: "Wonka, Willy",…},…]
    0:
        {ID: "dc3a6999", AuthorID: "0388", Authorname: "Wonka, Willy",…}
        Ownername: "Wonka, Willy"
        ...
    1:
        {ID: "685b7e33", AuthorID: "Test-Owner", Authorname: "Test, Owner",…}
        Ownername: "Wonka, Willy"
        ...
    2: {ID: "8192d591", AuthorID: "0003", Authorname: "Hedgehog, Sonic",…}
        Ownername: "Baggins, Frodo"
        ...
    3: {ID: "b56b7cfc", AuthorID: "0003", Authorname: "Hedgehog, Sonic",…}
        Ownername: "Baggins, Frodo"
        ...

How would I need to go about fixing it?


问:
Junit RunListener or Description or Result or Failure equivalent in Junit 5
Our test suite generates a very nice and beautiful HTML report. We use the org.junit.runner.notification.RunListener to achieve this.

The RunListener provides various methods which get org.junit.runner.Description org.junit.runner.Result as input which has a lot of useful methods and data required by us like getting annotations, name etc.

Is there an equivalent interface in Junit5 that we can use to get similar information?


问:
copy not blank row and paste in other worksheet
Can I hel me to modify this scritp to copy only not empty rows in a new worksheet ?

```<code>Sub Export_Basecosti()

Dim fd As Office.FileDialog
Dim fn As String
Dim FilePath, FileOnly, PathOnly As String
Dim ur As Long

FileOnly = ThisWorkbook.Name

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      .Title = "Scegli il file della Base Costi da Compilare"

      .Filters.Clear
      .Filters.Add "All Files", "*.*"

      If .Show = True Then

       fn = Empty
       fn = Dir(fd.SelectedItems(1))

      End If

   End With

    Windows(FileOnly).Activate
    Sheets("Base Costi").Select

    ur = Worksheets("Base Costi").Cells(Rows.Count, "C").End(xlUp).Row

    MsgBox ur

    'Copy A Range of Data
     Worksheets("Base Costi").Rows("2:" & ur).Copy
    ' Rows("2:252").Select
    ' Selection.Copy
    ' Selection.SpecialCells(xlCellTypeVisible).Copy

    Workbooks.Open (fn)

    Sheets("Bid COSTS - Link").Select

    'Clear
    Sheets("Bid COSTS - Link").Rows("8:508").ClearContents

    ' Range("A8").Select
    ' Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Bid COSTS - Link").Range("A8").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    ' ActiveWorkbook.CheckCompatibility = False
    ' ActiveWorkbook.Save

    'Dim ws As Worksheet
    'Set ws = ThisWorkbook.Sheets("Bid COSTS - Link")

    'ws.Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

    Workbooks(fn).Save
    Workbooks(fn).Close

    MsgBox "Base Costi Copiata"

End Sub
</code>```

i have tried to modify the code, but don't work..

Body:
Can I hel me to modify this scritp to copy only not empty rows in a new worksheet ?

Sub Export_Basecosti()

Dim fd As Office.FileDialog
Dim fn As String
Dim FilePath, FileOnly, PathOnly As String
Dim ur As Long

FileOnly = ThisWorkbook.Name

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      .Title = "Scegli il file della Base Costi da Compilare"

      .Filters.Clear
      .Filters.Add "All Files", "*.*"

      If .Show = True Then

       fn = Empty
       fn = Dir(fd.SelectedItems(1))

      End If

   End With

    Windows(FileOnly).Activate
    Sheets("Base Costi").Select

    ur = Worksheets("Base Costi").Cells(Rows.Count, "C").End(xlUp).Row

    MsgBox ur

    'Copy A Range of Data
     Worksheets("Base Costi").Rows("2:" & ur).Copy
    ' Rows("2:252").Select
    ' Selection.Copy
    ' Selection.SpecialCells(xlCellTypeVisible).Copy

    Workbooks.Open (fn)

    Sheets("Bid COSTS - Link").Select

    'Clear
    Sheets("Bid COSTS - Link").Rows("8:508").ClearContents

    ' Range("A8").Select
    ' Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Bid COSTS - Link").Range("A8").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    ' ActiveWorkbook.CheckCompatibility = False
    ' ActiveWorkbook.Save

    'Dim ws As Worksheet
    'Set ws = ThisWorkbook.Sheets("Bid COSTS - Link")

    'ws.Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

    Workbooks(fn).Save
    Workbooks(fn).Close

    MsgBox "Base Costi Copiata"

End Sub

i have tried to modify the code, but don't work..


问:
How to use multiple GPUs for training?
I am simply trying to understand how to format a config file to allow multiple GPUs/distributed training to take place via the "train" command.

The only clear tutorial out there is seemingly for much older versions of AllenNLP: Tutorial: How to train with multiple GPUs in AllenNLP and does not work as the "distributed" argument is now a Bool and will not accept a list of CUDA device IDs.

```<code>"trainer": {
        // Set use_amp to true to use automatic mixed-precision during training (if your GPU supports it)
        "use_amp": true,
        "cuda_devices": [7,8],
        "optimizer": {
            "type": "huggingface_adamw",
            "lr": 5e-5,
            "eps": 1e-06,
            "correct_bias": false,
            "weight_decay": 0.1,
            "parameter_groups": [
                // Apply weight decay to pre-trained params, excluding LayerNorm params and biases
                [["bias", "LayerNorm\\.weight", "layer_norm\\.weight"], {"weight_decay": 0}],
            ],
        },
        "callbacks":[{"type":'tensorboard'}],
        "num_epochs": 10,
        "checkpointer": {
            // A value of null or -1 will save the weights of the model at the end of every epoch
            "keep_most_recent_by_count": 2,
        },
        "grad_norm": 1.0,
        "learning_rate_scheduler": {
            "type": "slanted_triangular",
        },
        "distributed": {"cuda_devices": [7,8],},
        "world_size": 2,
    },
}
</code>```

Leads to:

```<code>    kwargs = create_kwargs(constructor_to_inspect, cls, params, **extras)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 206, in create_kwargs
    constructed_arg = pop_and_construct_arg(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 314, in pop_and_construct_arg
    return construct_arg(class_name, name, popped_params, annotation, default, **extras)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 363, in construct_arg
    raise TypeError(f"Expected {argument_name} to be a {annotation.__name__}.")
TypeError: Expected distributed to be a bool.
</code>```

Then trying to shift towards allennlp v2.10 by setting distributed to bool and providing the cuda_devices as a list leads to the following:

```<code>"trainer": {
        // Set use_amp to true to use automatic mixed-precision during training (if your GPU supports it)
        "use_amp": true,
        "cuda_devices": [7,8],
        "optimizer": {
            "type": "huggingface_adamw",
            "lr": 5e-5,
            "eps": 1e-06,
            "correct_bias": false,
            "weight_decay": 0.1,
            "parameter_groups": [
                // Apply weight decay to pre-trained params, excluding LayerNorm params and biases
                [["bias", "LayerNorm\\.weight", "layer_norm\\.weight"], {"weight_decay": 0}],
            ],
        },
        "callbacks":[{"type":'tensorboard'}],
        "num_epochs": 10,
        "checkpointer": {
            // A value of null or -1 will save the weights of the model at the end of every epoch
            "keep_most_recent_by_count": 2,
        },
        "grad_norm": 1.0,
        "learning_rate_scheduler": {
            "type": "slanted_triangular",
        },
        "distributed": true,
        "world_size": 2
    },
}
</code>```

With the following error:

```<code>  File "/home/niallt/DeCLUTR/allennlp/allennlp/commands/train.py", line 786, in from_partial_objects
    trainer_ = trainer.construct(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/lazy.py", line 82, in construct
    return self.constructor(**contructor_kwargs)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/lazy.py", line 66, in constructor_to_use
    return self._constructor.from_params(  # type: ignore[union-attr]
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 604, in from_params
    return retyped_subclass.from_params(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 638, in from_params
    return constructor_to_call(**kwargs)  # type: ignore
  File "/home/niallt/DeCLUTR/allennlp/allennlp/training/gradient_descent_trainer.py", line 1154, in from_partial_objects
    ddp_accelerator = TorchDdpAccelerator(cuda_device=cuda_device)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/nn/parallel/ddp_accelerator.py", line 138, in __init__
    super().__init__(local_rank=local_rank, world_size=world_size, cuda_device=cuda_device)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/nn/parallel/ddp_accelerator.py", line 102, in __init__
    self.local_rank: int = local_rank if local_rank is not None else dist.get_rank()
  File "/home/niallt/venvs/39_declutr/lib/python3.9/site-packages/torch/distributed/distributed_c10d.py", line 844, in get_rank
    default_pg = _get_default_group()
  File "/home/niallt/venvs/39_declutr/lib/python3.9/site-packages/torch/distributed/distributed_c10d.py", line 429, in _get_default_group
    raise RuntimeError(
RuntimeError: Default process group has not been initialized, please make sure to call init_process_group.
</code>```

I'm guessing I may just be missing some key arguments here - but struggling to determine what.

Any help would be much appreciated

```<code></code>```

Title: How to use multiple GPUs for training?

Body:
I am simply trying to understand how to format a config file to allow multiple GPUs/distributed training to take place via the "train" command.

The only clear tutorial out there is seemingly for much older versions of AllenNLP: Tutorial: How to train with multiple GPUs in AllenNLP and does not work as the "distributed" argument is now a Bool and will not accept a list of CUDA device IDs.

"trainer": {
        // Set use_amp to true to use automatic mixed-precision during training (if your GPU supports it)
        "use_amp": true,
        "cuda_devices": [7,8],
        "optimizer": {
            "type": "huggingface_adamw",
            "lr": 5e-5,
            "eps": 1e-06,
            "correct_bias": false,
            "weight_decay": 0.1,
            "parameter_groups": [
                // Apply weight decay to pre-trained params, excluding LayerNorm params and biases
                [["bias", "LayerNorm\\.weight", "layer_norm\\.weight"], {"weight_decay": 0}],
            ],
        },
        "callbacks":[{"type":'tensorboard'}],
        "num_epochs": 10,
        "checkpointer": {
            // A value of null or -1 will save the weights of the model at the end of every epoch
            "keep_most_recent_by_count": 2,
        },
        "grad_norm": 1.0,
        "learning_rate_scheduler": {
            "type": "slanted_triangular",
        },
        "distributed": {"cuda_devices": [7,8],},
        "world_size": 2,
    },
}

Leads to:

    kwargs = create_kwargs(constructor_to_inspect, cls, params, **extras)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 206, in create_kwargs
    constructed_arg = pop_and_construct_arg(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 314, in pop_and_construct_arg
    return construct_arg(class_name, name, popped_params, annotation, default, **extras)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 363, in construct_arg
    raise TypeError(f"Expected {argument_name} to be a {annotation.__name__}.")
TypeError: Expected distributed to be a bool.

Then trying to shift towards allennlp v2.10 by setting distributed to bool and providing the cuda_devices as a list leads to the following:

"trainer": {
        // Set use_amp to true to use automatic mixed-precision during training (if your GPU supports it)
        "use_amp": true,
        "cuda_devices": [7,8],
        "optimizer": {
            "type": "huggingface_adamw",
            "lr": 5e-5,
            "eps": 1e-06,
            "correct_bias": false,
            "weight_decay": 0.1,
            "parameter_groups": [
                // Apply weight decay to pre-trained params, excluding LayerNorm params and biases
                [["bias", "LayerNorm\\.weight", "layer_norm\\.weight"], {"weight_decay": 0}],
            ],
        },
        "callbacks":[{"type":'tensorboard'}],
        "num_epochs": 10,
        "checkpointer": {
            // A value of null or -1 will save the weights of the model at the end of every epoch
            "keep_most_recent_by_count": 2,
        },
        "grad_norm": 1.0,
        "learning_rate_scheduler": {
            "type": "slanted_triangular",
        },
        "distributed": true,
        "world_size": 2
    },
}

With the following error:

  File "/home/niallt/DeCLUTR/allennlp/allennlp/commands/train.py", line 786, in from_partial_objects
    trainer_ = trainer.construct(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/lazy.py", line 82, in construct
    return self.constructor(**contructor_kwargs)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/lazy.py", line 66, in constructor_to_use
    return self._constructor.from_params(  # type: ignore[union-attr]
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 604, in from_params
    return retyped_subclass.from_params(
  File "/home/niallt/DeCLUTR/allennlp/allennlp/common/from_params.py", line 638, in from_params
    return constructor_to_call(**kwargs)  # type: ignore
  File "/home/niallt/DeCLUTR/allennlp/allennlp/training/gradient_descent_trainer.py", line 1154, in from_partial_objects
    ddp_accelerator = TorchDdpAccelerator(cuda_device=cuda_device)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/nn/parallel/ddp_accelerator.py", line 138, in __init__
    super().__init__(local_rank=local_rank, world_size=world_size, cuda_device=cuda_device)
  File "/home/niallt/DeCLUTR/allennlp/allennlp/nn/parallel/ddp_accelerator.py", line 102, in __init__
    self.local_rank: int = local_rank if local_rank is not None else dist.get_rank()
  File "/home/niallt/venvs/39_declutr/lib/python3.9/site-packages/torch/distributed/distributed_c10d.py", line 844, in get_rank
    default_pg = _get_default_group()
  File "/home/niallt/venvs/39_declutr/lib/python3.9/site-packages/torch/distributed/distributed_c10d.py", line 429, in _get_default_group
    raise RuntimeError(
RuntimeError: Default process group has not been initialized, please make sure to call init_process_group.

I'm guessing I may just be missing some key arguments here - but struggling to determine what.

Any help would be much appreciated


问:
Is there a way to change location of a block in Wordpress?
I'm currently working on a product page in Wordpress.
The current theme I'm using allows my product image to be sticky throughout the webpage browsing.
However, the "Add to cart" and a "Price table" is located all the way at the bottom of the page.
I'm looking for a way to change that block over to underneath my sticky product image, so people could constantly see the price changing as they're choosing their options in the page.

I'm currently using Metro as a theme as YITH WooCommerce Add-ons & Extra Add-ons to display my product options.

Appreciate all the help I could get!

Image at the bottom of the product page

I've tried to look for the specific block on the Parent Theme of Metro and I've came to a conclusion:

I don't understand PHP enough to identify the exact block that's calling the price table & add-to-cart button.

Even if I thought I found something that could be it, I tinkered with the codes a bit, but there were absolutely no changes to the site, which led to my assumption that I'm editing the wrong one due to the different layouts the theme has.


问:
Flutter: Print PDF in a printer using IP address without preview
I need to print a pdf data in a wifi thermal printer from my android app. I have the ip address of the printer already, so I need to send the pdf data to the printer and print the data without the android preview

I have tried using the Printing package but cannot implement the system. Help me, thanks in advance

My code:

```<code>await Printing.layoutPdf(
    onLayout: (PdfPageFormat format) async => pdf.save());
</code>```

Body:
I need to print a pdf data in a wifi thermal printer from my android app. I have the ip address of the printer already, so I need to send the pdf data to the printer and print the data without the android preview

I have tried using the Printing package but cannot implement the system. Help me, thanks in advance

My code:

await Printing.layoutPdf(
    onLayout: (PdfPageFormat format) async => pdf.save());


问:
Warning: Header may not contain more than a single header, new line detected
I have updated my MySQL Update code as it was not working correctly and I am now getting the below error message after pressing the update record button and trying to load the next page.

Warning: Header may not contain more than a single header, new line detected in .... line 65

After I press the update asset button, I expect the asset display page to appear with a box confirming that it's been updated. It's just getting stuck on the update page and giving me the above error message and not loading the page as expected.

(asset = items we have)

My code is:

```<code>$stmt = $pdo->prepare('UPDATE assmgnt SET id = ?, name=?,manufacturer=?,model=?,description=?,type=?,size=?,consumable=?,serialnum=?,licnum=?,accdetails=?,fueltype=?,location=?,resperson=?,status=?,purchfrom=?,datepurch=?,price=?,quantity=?,fundsource=?,receipt=? WHERE id=?');
$stmt->execute([$id,$name,$manufacturer,$model,$description,$type,$size,$consumable,$serialnum,$licnum,$accdetails,$fueltype,$location,$resperson,$status,$purchfrom,$datepurch,$price,$quantity,$fundsource,$receipt,$_GET['id']]);
header('Location: display.php?id='.$id);
$_SESSION['status'] = "The asset information has been successfully updated.";
</code>```

Offending code

```<code>header('Location: display.php?id='.$id);
</code>```

The script is working fine on other update / insert scripts fine on my system and was working fine on this page on Friday.

After looking on SO, I have found that it could be because it's on multiple lines but it's on a single line.

Body:
I have updated my MySQL Update code as it was not working correctly and I am now getting the below error message after pressing the update record button and trying to load the next page.

Warning: Header may not contain more than a single header, new line detected in .... line 65

After I press the update asset button, I expect the asset display page to appear with a box confirming that it's been updated. It's just getting stuck on the update page and giving me the above error message and not loading the page as expected.

(asset = items we have)

My code is:

$stmt = $pdo->prepare('UPDATE assmgnt SET id = ?, name=?,manufacturer=?,model=?,description=?,type=?,size=?,consumable=?,serialnum=?,licnum=?,accdetails=?,fueltype=?,location=?,resperson=?,status=?,purchfrom=?,datepurch=?,price=?,quantity=?,fundsource=?,receipt=? WHERE id=?');
$stmt->execute([$id,$name,$manufacturer,$model,$description,$type,$size,$consumable,$serialnum,$licnum,$accdetails,$fueltype,$location,$resperson,$status,$purchfrom,$datepurch,$price,$quantity,$fundsource,$receipt,$_GET['id']]);
header('Location: display.php?id='.$id);
$_SESSION['status'] = "The asset information has been successfully updated.";

Offending code

header('Location: display.php?id='.$id);

The script is working fine on other update / insert scripts fine on my system and was working fine on this page on Friday.

After looking on SO, I have found that it could be because it's on multiple lines but it's on a single line.


问:
NestJs and Typeorm service/DTO/interceptor structure
Recently started using NestJs, and wondering how to structure data.

So my question is, where should I manipulate with the data?
In the service, or in the DTO using interceptor, or inside of the entity itself?

I have three different entities:

Food

```<code>@Entity("Food", { schema: "public" })
export class Food {
  @PrimaryGeneratedColumn({ type: "bigint", name: "FoodID" })
  foodId!: string;
  @Column("character varying", { name: "FoodName", length: 255 })
  FoodName!: string;
  @OneToMany(() => FoodWeight, (Food_weight) => Food_weight.ForFood2)
  Food_weights!: FoodWeight[];
  @OneToMany(() => FoodNutrient, (Food_Nutrient) => Food_Nutrient.ForFood2)
  Food_Nutrients!: FoodNutrient[];
}
</code>```

Food weight

```<code>export class FoodWeight{
  @Column("bigint", { primary: true, name: "ForFood" })
  ForFood!: string;

  @Column("smallint", { primary: true, name: "SortOrder" })
  SortOrder!: number;

  @Column("character varying", { name: "WeightName", length: 255 })
  name!: string;

  @Column("numeric", {
    name: "Weight",
    nullable: true,
    precision: 10,
    scale: 4,
  })
  weight!: string | null;

  @ManyToOne(() => Food, (Food) => Food.Food_weights, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "ForFood", referencedColumnName: "foodId" }])
  ForFood2!: Food;

}
</code>```

Nutrients

```<code>export class FoodNutrient {
  @Column("bigint", { primary: true, name: "ForFood" })
  ForFood!: string;

  @Column("smallint", { primary: true, name: "NutrientNo" })
  NutrientNo!: number;

  @Column("numeric", {
    name: "NutrientVal",
    nullable: true,
    precision: 10,
    scale: 4,
  })
  NutrientVal!: string | null;

  @ManyToOne(() => Food, (Food) => Food.Food_Nutrients, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "ForFood", referencedColumnName: "foodId" }])
  ForFood2!: Food;
}
</code>```

Service query is something like this:

```<code>const foods = await this.table
      .createQueryBuilder('food')
      .leftJoinAndSelect('food.Food_Weights', 'Food_Weights')
      .leftJoinAndSelect('food.Food_Nutrients', 'Food_Nutrients')
      .where(`food.foodId = ${id}`)
      .getOne();
</code>```

I have to retrieve response in this format, where nutrients vary based on foods weight:

```<code>{
 foodId: 123,
 foodName: 'food',
  FoodWeights: [
    {
      name: cup,
      "amount": 1,
      "weight": 151,
      "nutrients": [
        {
          "NutrientNo": 204,
          "NutrientVal": 1.2834999999999999
        }
      ]
    }
  ]
}
</code>```

Body:
Recently started using NestJs, and wondering how to structure data.

So my question is, where should I manipulate with the data?
In the service, or in the DTO using interceptor, or inside of the entity itself?

I have three different entities:

Food

@Entity("Food", { schema: "public" })
export class Food {
  @PrimaryGeneratedColumn({ type: "bigint", name: "FoodID" })
  foodId!: string;
  @Column("character varying", { name: "FoodName", length: 255 })
  FoodName!: string;
  @OneToMany(() => FoodWeight, (Food_weight) => Food_weight.ForFood2)
  Food_weights!: FoodWeight[];
  @OneToMany(() => FoodNutrient, (Food_Nutrient) => Food_Nutrient.ForFood2)
  Food_Nutrients!: FoodNutrient[];
}

Food weight

export class FoodWeight{
  @Column("bigint", { primary: true, name: "ForFood" })
  ForFood!: string;

  @Column("smallint", { primary: true, name: "SortOrder" })
  SortOrder!: number;

  @Column("character varying", { name: "WeightName", length: 255 })
  name!: string;

  @Column("numeric", {
    name: "Weight",
    nullable: true,
    precision: 10,
    scale: 4,
  })
  weight!: string | null;

  @ManyToOne(() => Food, (Food) => Food.Food_weights, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "ForFood", referencedColumnName: "foodId" }])
  ForFood2!: Food;

}

Nutrients

export class FoodNutrient {
  @Column("bigint", { primary: true, name: "ForFood" })
  ForFood!: string;

  @Column("smallint", { primary: true, name: "NutrientNo" })
  NutrientNo!: number;

  @Column("numeric", {
    name: "NutrientVal",
    nullable: true,
    precision: 10,
    scale: 4,
  })
  NutrientVal!: string | null;

  @ManyToOne(() => Food, (Food) => Food.Food_Nutrients, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "ForFood", referencedColumnName: "foodId" }])
  ForFood2!: Food;
}

Service query is something like this:

const foods = await this.table
      .createQueryBuilder('food')
      .leftJoinAndSelect('food.Food_Weights', 'Food_Weights')
      .leftJoinAndSelect('food.Food_Nutrients', 'Food_Nutrients')
      .where(`food.foodId = ${id}`)
      .getOne();

I have to retrieve response in this format, where nutrients vary based on foods weight:

{
 foodId: 123,
 foodName: 'food',
  FoodWeights: [
    {
      name: cup,
      "amount": 1,
      "weight": 151,
      "nutrients": [
        {
          "NutrientNo": 204,
          "NutrientVal": 1.2834999999999999
        }
      ]
    }
  ]
}


问:
Standard way to take multiple files as input in Java main class using docker
I am creating a Java Maven project with main class i.e. it is executable. I require multiple json files as input from user, these files could be in arbitrary amount (i.e. the number of files is not fixed).

Then I have to create a docker image of this project, how could I take these arbitrary number of json files from user and use it in the Java class using Docker.

Any help with suggestions/links would be very appreciated.


问:
Cargo can't initialize index under Windows
I have installed rust and cargo using rustup and I don't know why but somehow the cargo stopped working because it cannot initialize git index in hidden folder..

The problem is:

cargo run
> error: failed to get `reqwest` as a dependency of package `whatever 0.1.0 (C:\somewhere\in\windows\whatever)`
>
> Caused by:
>   failed to initialize index git repository (in "C:\\somewhere\\in\\windows\\.cargo\\registry\\index\\github.com-some1hash")
>
> Caused by:
>   failed to mark Git repository folder as hidden: ; class=0s (2)
```

It could be because our corp has decreased privileges of all users but this means I can't compile anything on Windows..

edit: The versions are cargo 1.65.0 and rustc 1.65.0 under Windows 10 Enterprise. All of the folders in path are created, but are empty as it fails on hiding the folder..

Body:
I have installed rust and cargo using rustup and I don't know why but somehow the cargo stopped working because it cannot initialize git index in hidden folder..

The problem is:

cargo run
> error: failed to get `reqwest` as a dependency of package `whatever 0.1.0 (C:\somewhere\in\windows\whatever)`
>
> Caused by:
>   failed to initialize index git repository (in "C:\\somewhere\\in\\windows\\.cargo\\registry\\index\\github.com-some1hash")
>
> Caused by:
>   failed to mark Git repository folder as hidden: ; class=0s (2)

It could be because our corp has decreased privileges of all users but this means I can't compile anything on Windows..

edit: The versions are cargo 1.65.0 and rustc 1.65.0 under Windows 10 Enterprise. All of the folders in path are created, but are empty as it fails on hiding the folder..


问:
Mac/iOS Corrupts Custom Icon Fonts in Firefox/Chrome
I have the bug that on Mac/iOS in Chrome and Firefox browser my custom icon font is suddenly cut off.

I created the font with icomoon.io because that actually worked quite well on different browsers so far.
The font loads without errors and the size is correct.

It is also not because there is a Div/Container ... over it the icons are on top.

Fun fact: If you change the fontsize to an enormous amount like 120px the Icons are fixed again

Is this a known bug, or is there a fix for it?

Example Img

Icon Call

```<code><i class="ke-icon-basket"></i>
</code>```

Applying the class

```<code>i[class^="ke-icon"], i[class^="ke-icon"] span {
  speak: never;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-family: KEIcons !important;
  font-size: 24px;
  font-style: normal;
  font-variant: normal;
  font-weight: 400;
  line-height: 1;
  text-transform: none;
}
</code>```

Font initalization

```<code>@font-face{
  font-display:swap;
  font-family:KEIcons;
  font-style:normal;
  font-weight:400;
  src:url(fonts/KEIcons/KEIcons.woff) format("woff"),url(fonts/KEIcons/KEIcons.woff2) format("woff2")
}
</code>```

Steps already done:

Changed to all kinds of font type

Resized icons in font

Disabled Apaches default cache function and all of the pagespeed modification which are supervised by hetzner

Body:
I have the bug that on Mac/iOS in Chrome and Firefox browser my custom icon font is suddenly cut off.

I created the font with icomoon.io because that actually worked quite well on different browsers so far.
The font loads without errors and the size is correct.

It is also not because there is a Div/Container ... over it the icons are on top.

Fun fact: If you change the fontsize to an enormous amount like 120px the Icons are fixed again

Is this a known bug, or is there a fix for it?

Example Img

Icon Call

Applying the class

i[class^="ke-icon"], i[class^="ke-icon"] span {
  speak: never;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-family: KEIcons !important;
  font-size: 24px;
  font-style: normal;
  font-variant: normal;
  font-weight: 400;
  line-height: 1;
  text-transform: none;
}

Font initalization

@font-face{
  font-display:swap;
  font-family:KEIcons;
  font-style:normal;
  font-weight:400;
  src:url(fonts/KEIcons/KEIcons.woff) format("woff"),url(fonts/KEIcons/KEIcons.woff2) format("woff2")
}

Steps already done:

Changed to all kinds of font type

Resized icons in font

Disabled Apaches default cache function and all of the pagespeed modification which are supervised by hetzner


问:
Set user for pushing from GitLab CI with project deploy key
I am currently working on integrating GitLab CI for automated releases with a shell-based runner.

After getting successful tests for my build, I generate a new release to push it back to the repository. To do so, a deploy key with write access is configured for the repository.

Commits are using author data specific to the runner host, configured globally on the runner host (the corresponding user does not exist at GitLab itself). If these changes are pushed, the Activity section of the repository shows that the actual push has been done by one of the instance administrators (who initially configured the admin-specific stuff).

How can I configure/change this behaviour to push from the runner-specific user instead?


问:
Using Python logging module, how to filter error level logs from all level log file and store it into file?
In Python application, I am storing all level of logs(info,warning,error) in a log file using logging module.
I have to filter only error logs from all level log file and store the error logs to a file and then I need upload only error logs file to AWS S3 bucket.

How to filter error logs from all level log file and store the error logs to a file?

My requirement is I should not use two log handlers.


问:
AttributeError: module 'tensorflow.compat.v2.__internal__.tracking' has no attribute 'TrackableSaver'
Attribute Error imageThe program used to work before with no issues, but I tried running it again with a different dataset and I receive this error. is it a TensorFlow version error? I have already upgraded the versions for Keras and TensorFlow and nothing happens.

I followed the code from the reference to study LSTM AEs*

https://towardsdatascience.com/lstm-autoencoder-for-anomaly-detection-e1f4f2ee7ccf

I tried a different dataset, the same code I had previously and now even the one that used to work does not work.


问:
It is possible to initialize reduce toolkit entityManager in action and use it?
I would like to initialize my EntityAdapter from an action an use it in the same action

I have an Order object with lines in my state. I want to use an entityAdapter for the lines but if the user don't start an order, Order is null

The order is not existing while the user don't press the add button

This is my code

Reducer action
`

```<code>export const addProductToCurrentOrderAction = (
  state: appState,
  action: PayloadAction<{ quantity: number; product: Product }>,
) => {
  const { quantity, product } = action.payload;

  // if order doen't exist, I create a new one with lines = orderLinesAdapter.getInitialState()
  if (state.currentOrder === null) {
    state.currentOrder = createOrderDoc(state.userState.user);
  }

  // check if the line already exist
  let orderLineTest = state.currentOrder.lines.entities[product.ean];
  if (!orderLineTest) {
    // if not I create a new orderLine
    orderLineTest = createOrderLineFromProduct(product, state.configState.config);
  }

  // set line quantity and line total
  orderLineTest.quantity = quantity;

  // add or update line
  orderLinesAdapter.addOne(state.currentOrder.lines, orderLineTest);
};
</code>```

`

This only work if the order is already created (on first run the line is not added to entityAdapter)

I'm supposed there is a tricky problem with the entityAdapter update outside the action

Maybe the way to do this is not really correct for redux-toolkit?

Body:
I would like to initialize my EntityAdapter from an action an use it in the same action

I have an Order object with lines in my state. I want to use an entityAdapter for the lines but if the user don't start an order, Order is null

The order is not existing while the user don't press the add button

This is my code

Reducer action
`

export const addProductToCurrentOrderAction = (
  state: appState,
  action: PayloadAction<{ quantity: number; product: Product }>,
) => {
  const { quantity, product } = action.payload;

  // if order doen't exist, I create a new one with lines = orderLinesAdapter.getInitialState()
  if (state.currentOrder === null) {
    state.currentOrder = createOrderDoc(state.userState.user);
  }

  // check if the line already exist
  let orderLineTest = state.currentOrder.lines.entities[product.ean];
  if (!orderLineTest) {
    // if not I create a new orderLine
    orderLineTest = createOrderLineFromProduct(product, state.configState.config);
  }

  // set line quantity and line total
  orderLineTest.quantity = quantity;

  // add or update line
  orderLinesAdapter.addOne(state.currentOrder.lines, orderLineTest);
};

`

This only work if the order is already created (on first run the line is not added to entityAdapter)

I'm supposed there is a tricky problem with the entityAdapter update outside the action

Maybe the way to do this is not really correct for redux-toolkit?


问:
Is possible in android to pan/drag a layout?
I am trying to pan a RelativeLayout with child Views, using gesture onScroll event, but I do not get the result that I desire.  I have tried to move the children, but nothing works.

Any suggestions?

ContentLicense: CC BY-SA 3.0


问:
Change system python to python 3.9 to install meson on linux
I am a total noob when it comes to working with os, so please go easy on me :)

Basically my end goal is "simple", I want to install qemu-7.0 in order to install Docker-desktop.

My os is Linux Mint 19.3
My default python3 is obviously "maxed out" at 3.6

I have already taken care of setting python 3.9 as default in the system
(in fact if I type python --version I get Python 3.9.16), however it seems like when it comes to installing packages it defaults to python 3.6

Like I said, I'm a total noob so I don't even know what kind of commands could be useful.

Something else I will add just in case is the which python command:
/usr/bin/python

I'm sorry if I did a poor job at presenting informations, but like I said I don't know where to look.

Hopefully I've made the end goal clear, really to just install docker-desktop, but following the procedure leads abck to the problem of not having qemu > 5.2, and installing qemu gives me the error that mason can't set up because my os python version is 3.6 and it needs 3.7 or above.

Thank you very much for any help and have a nice day :)


问:
Entity Framework API won't close some of the connections with phpmyadmin
I have frontend done with React and a backend .NET API that communicate between each other using fetch. My database is stored in phpmyadmin as this is what my university have given me and it is restricted to maximum 10 connections at a time. Now here is my problem, I have these opened connections every time I access a certain page  and I don't understand why it is happening. I am using Entity Framework and this is how each of my method is coded:

```<code>        public Game GetGame(int userID)
        {
            TyperacerContext context;
            Game g = null;
            using (context = new TyperacerContext())
            {
                try
                {
                     g = context.Games.First(p => p.Status == "Active" && p.User1ID == userID || p.User2ID == userID);
                }

                catch
                {

                }
            }
            context.Dispose();
            return g;
        }
    }
</code>```

I coded them with Using, so it can automatically close the connection and that is working for almost each method but I can see those opened connections (at first they are just two but each 4-5 seconds they multiply so I cannot test my application correctly).

My question is how can I find the problem and fix it? Can I kill all the sleeping connections automatically? Or maybe another way? I know it is hard to fix the problem but I just need some ideas what can I do.

Body:
I have frontend done with React and a backend .NET API that communicate between each other using fetch. My database is stored in phpmyadmin as this is what my university have given me and it is restricted to maximum 10 connections at a time. Now here is my problem, I have these opened connections every time I access a certain page  and I don't understand why it is happening. I am using Entity Framework and this is how each of my method is coded:

        public Game GetGame(int userID)
        {
            TyperacerContext context;
            Game g = null;
            using (context = new TyperacerContext())
            {
                try
                {
                     g = context.Games.First(p => p.Status == "Active" && p.User1ID == userID || p.User2ID == userID);
                }

                catch
                {

                }
            }
            context.Dispose();
            return g;
        }
    }

I coded them with Using, so it can automatically close the connection and that is working for almost each method but I can see those opened connections (at first they are just two but each 4-5 seconds they multiply so I cannot test my application correctly).

My question is how can I find the problem and fix it? Can I kill all the sleeping connections automatically? Or maybe another way? I know it is hard to fix the problem but I just need some ideas what can I do.


问:
Can't display my uploaded images in symfony
I need you. I'm trying to display my images stocked in DB postgres. But I can't cause when I'm trying, I have just an icon of unloaded image. I don't know Where is the problem. Here's my controller.

```<code>
    #[Route('/publication', name: 'publication')]
    public function temp(Environment $twig)
    {
        $drawRepository= $this->entityManager->getRepository(Draw::class);
        $draws = $drawRepository->findAll();
        return new Response($twig->render('draw/show.html.twig', [
            'draws'=>$draws

        ]));
    }

}
</code>```

and the part of my template

```<code>{% extends 'base.html.twig' %}

{% block body %}

    {% for draw  in draws %}
            <img src={{ asset("./public/uploads/draws/" ~ draw.post) }}/>
    {% endfor %}

{% endblock %}
</code>```

thanks in advance for your answers

Initially, I packed all features in one Method but finally I split  the recuperation and the submission of my images in two Methods as you can see. Unfortunately It didn't help me.

Body:
I need you. I'm trying to display my images stocked in DB postgres. But I can't cause when I'm trying, I have just an icon of unloaded image. I don't know Where is the problem. Here's my controller.

    #[Route('/publication', name: 'publication')]
    public function temp(Environment $twig)
    {
        $drawRepository= $this->entityManager->getRepository(Draw::class);
        $draws = $drawRepository->findAll();
        return new Response($twig->render('draw/show.html.twig', [
            'draws'=>$draws

        ]));
    }

}

and the part of my template

{% extends 'base.html.twig' %}

{% block body %}

    {% for draw  in draws %}

    {% endfor %}

{% endblock %}

thanks in advance for your answers

Initially, I packed all features in one Method but finally I split  the recuperation and the submission of my images in two Methods as you can see. Unfortunately It didn't help me.


问:
Amazon Chime(ReactNative): [AppInfo setAppVersionName:]: unrecognized selector sent to instance 0x281888aa0
I am facing issue in Amazon Chime, React Native SDK with bridging, It is working fine in Android crash is only in iOS when

```<code>NativeFunction.startMeeting(meetingResponse.JoinInfo.Meeting.Meeting, meetingResponse.JoinInfo.Attendee.Attendee);
</code>```

was called.
Crash log in XCode
Exception in ios device
Please find the below line of code mentied below where crash is happing.

```<code>-(void)startAudioVideo
{
   NSError* error = nil;
   BOOL started = [meetingSession.audioVideo startAndReturnError:&error];
   if (started && error == nil)
   {
     [logger infoWithMsg:@"RN meeting session was started successfully"];

     [meetingSession.audioVideo startRemoteVideo];
   }
   else
   {
     NSString *errorMsg = [NSString stringWithFormat:@"Failed to start meeting, error: %@", error.description];
     [logger errorWithMsg:errorMsg];

     // Handle missing permission error
     if ([error.domain isEqual:@"AmazonChimeSDK.PermissionError"])
     {
       AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
       if (permissionStatus == AVAudioSessionRecordPermissionUndetermined)
       {
         [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted)
         {
           if (granted)
           {
             [logger infoWithMsg:@"Audio permission granted"];
             // Retry after permission is granted
             [self startAudioVideo];
           }
           else
           {
             [logger infoWithMsg:@"Audio permission not granted"];
             [self sendEventWithName:kEventOnMeetingEnd body:nil];
           }
         }];
       }
       else if (permissionStatus == AVAudioSessionRecordPermissionDenied)
       {
         [logger errorWithMsg:@"User did not grant permission, should redirect to Settings"];
         [self sendEventWithName:kEventOnMeetingEnd body:nil];
       }
     }
     else
     {
       // Uncaught error
       [self sendEventWithName:kEventOnError body: errorMsg];
       [self sendEventWithName:kEventOnMeetingEnd body:nil];
     }
   }
}
</code>```

Could you please help me out.

Thanks and Regards, Pawan

Git hub link for the similar issue
I have tried that but it is not worked for me.

Body:
I am facing issue in Amazon Chime, React Native SDK with bridging, It is working fine in Android crash is only in iOS when

NativeFunction.startMeeting(meetingResponse.JoinInfo.Meeting.Meeting, meetingResponse.JoinInfo.Attendee.Attendee);

was called.
Crash log in XCode
Exception in ios device
Please find the below line of code mentied below where crash is happing.

-(void)startAudioVideo
{
   NSError* error = nil;
   BOOL started = [meetingSession.audioVideo startAndReturnError:&error];
   if (started && error == nil)
   {
     [logger infoWithMsg:@"RN meeting session was started successfully"];

     [meetingSession.audioVideo startRemoteVideo];
   }
   else
   {
     NSString *errorMsg = [NSString stringWithFormat:@"Failed to start meeting, error: %@", error.description];
     [logger errorWithMsg:errorMsg];

     // Handle missing permission error
     if ([error.domain isEqual:@"AmazonChimeSDK.PermissionError"])
     {
       AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
       if (permissionStatus == AVAudioSessionRecordPermissionUndetermined)
       {
         [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted)
         {
           if (granted)
           {
             [logger infoWithMsg:@"Audio permission granted"];
             // Retry after permission is granted
             [self startAudioVideo];
           }
           else
           {
             [logger infoWithMsg:@"Audio permission not granted"];
             [self sendEventWithName:kEventOnMeetingEnd body:nil];
           }
         }];
       }
       else if (permissionStatus == AVAudioSessionRecordPermissionDenied)
       {
         [logger errorWithMsg:@"User did not grant permission, should redirect to Settings"];
         [self sendEventWithName:kEventOnMeetingEnd body:nil];
       }
     }
     else
     {
       // Uncaught error
       [self sendEventWithName:kEventOnError body: errorMsg];
       [self sendEventWithName:kEventOnMeetingEnd body:nil];
     }
   }
}

Could you please help me out.

Thanks and Regards, Pawan

Git hub link for the similar issue
I have tried that but it is not worked for me.