问:
Entity framework migration return invalid reference column
I created a table using entity framework using migrations

Table:

```<code>public partial class Salary : BaseAuditModel, IEntity
    {
        public int ClientId { get; set; }
        public int ProfileId { get; set; }
        public decimal Amount { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual Profile Profile { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual Client Client{ get; set; }
</code>```

Context:

```<code>modelBuilder.Entity<Salary>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.Status).HasDefaultValueSql("((1))");

                entity.HasOne(d => d.Profile)
                    .WithMany(p => p.Salaries)
                    .HasForeignKey(d => d.ProfileId)
                    .HasConstraintName("FK__ProfileSalaries__ProfileId");

                entity.HasOne(d => d.Client)
                    .WithMany(p => p.Salaries)
                    .HasForeignKey(d => d.ClientId)
                    .HasConstraintName("FK__ClientSalaries__ClientId");

            });
</code>```

Migration:

```<code>migrationBuilder.CreateTable(
                name: "Salaries",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    CreatedByUserId = table.Column<int>(nullable: false),
                    CreatedDate = table.Column<DateTime>(nullable: false),
                    LastUpdatedUserId = table.Column<long>(nullable: true),
                    LastUpdatedDate = table.Column<DateTime>(nullable: true),
                    Status = table.Column<int>(nullable: false, defaultValueSql: "((1))"),
                    ClientId = table.Column<int>(nullable: false),
                    ProfileId = table.Column<int>(nullable: false),
                    Amount = table.Column<decimal>(nullable: false),
                    StartDate = table.Column<DateTime>(nullable: false),
                    EndDate = table.Column<DateTime>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Salaries", x => x.Id);
                    table.ForeignKey(
                        name: "FK__ClientSalaries__ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK__ProfileSalaries__ProfileId",
                        column: x => x.ProfileId,
                        principalTable: "Profiles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });
</code>```

This created the table with its foreign keys correctly. But now I want to add a new foreign key reference of another table, exactly the same as the Profile and Client, so I added it as:

```<code>public partial class Salary : BaseAuditModel, IEntity
    {
     //code here
     public int ProfileClientId { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual ProfileClient ProfileClient { get; set; }
    }
}
</code>```

Then in Context added as:

```<code>modelBuilder.Entity<Salary>(entity =>
        {
            //Code here

            entity.HasOne(d => d.ProfileClient)
                .WithMany(p => p.Salaries)
                .HasForeignKey(d => d.ProfileClientId)
                .HasConstraintName("FK__ProfileClientSalaries__ProfileClientId");
        });
</code>```

So I created the new migration for this column, ran it, and it threw the following error:

Foreign key 'FK__ProfileClientSalaries__ProfileClientId' references
invalid column 'ProfileClientId' in referencing table 'Salaries'.
Could not create constraint or index. See previous errors.

So I go to migration and search for FK__ProfileClientSalaries__ProfileClientId

```<code>protected override void Up(MigrationBuilder migrationBuilder)
        {
 migrationBuilder.AddForeignKey(
                name: "FK__ProfileClientSalaries__ProfileClientId",
                table: "Salaries",
                column: "ProfileClientId",
                principalTable: "ProfileClients",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);
     }

 protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK__ProfileClientSalaries__ProfileClientId",
                table: "Salaries");
        }
</code>```

That does not make sense to me because table creation was good, and I just want to add another column with same characteristics of other 2 foreign keys, but the table update is throwing that error. How can I solve this issue?

Body:
I created a table using entity framework using migrations

Table:

public partial class Salary : BaseAuditModel, IEntity
    {
        public int ClientId { get; set; }
        public int ProfileId { get; set; }
        public decimal Amount { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual Profile Profile { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual Client Client{ get; set; }

Context:

modelBuilder.Entity<Salary>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.Status).HasDefaultValueSql("((1))");

                entity.HasOne(d => d.Profile)
                    .WithMany(p => p.Salaries)
                    .HasForeignKey(d => d.ProfileId)
                    .HasConstraintName("FK__ProfileSalaries__ProfileId");

                entity.HasOne(d => d.Client)
                    .WithMany(p => p.Salaries)
                    .HasForeignKey(d => d.ClientId)
                    .HasConstraintName("FK__ClientSalaries__ClientId");

            });

Migration:

migrationBuilder.CreateTable(
                name: "Salaries",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    CreatedByUserId = table.Column<int>(nullable: false),
                    CreatedDate = table.Column<DateTime>(nullable: false),
                    LastUpdatedUserId = table.Column<long>(nullable: true),
                    LastUpdatedDate = table.Column<DateTime>(nullable: true),
                    Status = table.Column<int>(nullable: false, defaultValueSql: "((1))"),
                    ClientId = table.Column<int>(nullable: false),
                    ProfileId = table.Column<int>(nullable: false),
                    Amount = table.Column<decimal>(nullable: false),
                    StartDate = table.Column<DateTime>(nullable: false),
                    EndDate = table.Column<DateTime>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Salaries", x => x.Id);
                    table.ForeignKey(
                        name: "FK__ClientSalaries__ClientId",
                        column: x => x.ClientId,
                        principalTable: "Clients",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK__ProfileSalaries__ProfileId",
                        column: x => x.ProfileId,
                        principalTable: "Profiles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

This created the table with its foreign keys correctly. But now I want to add a new foreign key reference of another table, exactly the same as the Profile and Client, so I added it as:

public partial class Salary : BaseAuditModel, IEntity
    {
     //code here
     public int ProfileClientId { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public virtual ProfileClient ProfileClient { get; set; }
    }
}

Then in Context added as:

modelBuilder.Entity<Salary>(entity =>
        {
            //Code here

            entity.HasOne(d => d.ProfileClient)
                .WithMany(p => p.Salaries)
                .HasForeignKey(d => d.ProfileClientId)
                .HasConstraintName("FK__ProfileClientSalaries__ProfileClientId");
        });

So I created the new migration for this column, ran it, and it threw the following error:

Foreign key 'FK__ProfileClientSalaries__ProfileClientId' references
invalid column 'ProfileClientId' in referencing table 'Salaries'.
Could not create constraint or index. See previous errors.

So I go to migration and search for FK__ProfileClientSalaries__ProfileClientId

protected override void Up(MigrationBuilder migrationBuilder)
        {
 migrationBuilder.AddForeignKey(
                name: "FK__ProfileClientSalaries__ProfileClientId",
                table: "Salaries",
                column: "ProfileClientId",
                principalTable: "ProfileClients",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);
     }

 protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK__ProfileClientSalaries__ProfileClientId",
                table: "Salaries");
        }

That does not make sense to me because table creation was good, and I just want to add another column with same characteristics of other 2 foreign keys, but the table update is throwing that error. How can I solve this issue?


来源: stackexchange

问:
Error when using http in node_package_manager
I am not sure why I am getting this error message from npm, but it is saying that

error:

Error: While trying to resolve module http from file
C:\Users\path\node_modules\express\lib\request.js, the package
C:\Users\path\node_modules\http\package.json was successfully found.
However, this package itself specifies a main module field that
could not be resolved

(C:\Users\path\node_modules\http\index. Indeed, none of these files
exist:

The thing about this error messsage, it asked me before that http and path did not exist in my node_modules. So I installed those two packages to my npm. Now it is giving that error message and I am not sure how I can resolve this. Any idea how to fix this problem?

I have tried deleting the npm and then reinstalling back in and it again give me the same error.

I have also tried using

npx react-native start --reset-cache

and I am still facing the same error message.

ContentLicense: CC BY-SA 4.0


问:
model.fit instead of model.fit_generator (bug fixing of VGG16 neural network)
In building up a VGG16 neural network, I recycled some working code. But now, model.fit_generator is not supported any more. A simple substitution in "model.fit" does not work. Even though there are sources saying exactly that (compare: https://www.codesofinterest.com/2020/09/model-fit-vs-fit-generator-tfkeras.html).

Can anybody help me to deal with the issue?

I know the theoretical difference between "fit" and "fit_generator". I only have difficulties in coding.

I only used ImageDataGenerator for efficiently referring to my data basis. If there is a better way to bring the Simpsons Character Set in my model: highly welcome! I assume, < 50.000 should be able to be trained in my memory (MacBook Air 2018).

In the following, I will give the ERROR MESSAGE, OLD CODE, NEW CODE and COMPLETE PYTHON CODE.

ERROR MESSAGE

```<code>File /opt/anaconda3/envs/ROB43_T/lib/python3.10/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb
</code>```

OLD CODE

```<code>history = model.fit_generator(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    validation_data = validation_generator,
    validation_steps = nb_validation_samples // batch_size)
</code>```

NEW CODE (exactly the same except model.fit instead of model.fit_generator

```<code>history = model.fit(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    #validation_data = validation_generator,
    #validation_steps = nb_validation_samples // batch_size
    )
</code>```

My complete python code is:

```<code># Importe diverser Programmbibliotheken.
import numpy as np
import matplotlib.pyplot as plt
import keras

# Konvertierung eines Bildes in Array (tf.keras.utils.image_dataset_from_directory wäre vielleicht besser gewesen).
from keras.preprocessing.image import ImageDataGenerator

# Import des Modells.
from keras.models import Sequential

# Import der Schichten.
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPool2D

# Modul zur Nutzung von Betriebssystemfunktionalität (z. B. Dateien laden). In Python bereits integriert.
import os

# Definition der Klassen zur Klassifizierung.
num_classes = 20

# Definition der Bildgröße.
img_rows, img_cols = 32, 32

# Definition der Stapelverarbeitung.
batch_size = 16

# Definition der Ordner für Trainings- und Testdaten.
train_data_dir = r'/Users/holger.kiefer/simpsons_archive/simpsons_dataset'
test_data_dir = r'/Users/holger.kiefer/simpsons_archive/kaggle_simpson_testset'

# Normalisierung der Trainings- und Testdaten auf Skala von 0 bis 1 statt von 0 bis 255 (RGB-Farben).
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

# Trainingsdaten laden aus Verzeichnis.
train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_rows, img_cols),
        batch_size=batch_size,
        class_mode='categorical')

# Testdaten laden aus Verzeichnis.
test_generator = test_datagen.flow_from_directory(
        test_data_dir,
        target_size=(img_rows, img_cols),
        batch_size=batch_size,
        class_mode='categorical')

# Definition des Modells. Aufbau des Algorithmus VGG16 mit 5 Stufen und Abschluss.
model = Sequential()

# padding="same" bedeutet, Nullen als "Rahmen" um Input zu legen, so dass In- & Output strukturell identisch sind.
# activation überall relu außer softmax ganz am Ende.
# kernel_size überall (3,3), strides überall (2,2), nach jeder Stufe BatchNormalization.

# Stufe 1 (3 in input_shape ergänzt wg. RGB-Farben.
model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu", input_shape=(img_rows,img_cols,3)))
model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 2
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 3
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 4
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 5
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Abschluss
# Dropout als Schutz vor Überanpassung. Ein paar Layers werden nicht verwendet.
# https://www.kdnuggets.com/2018/09/dropout-convolutional-networks.html
# Dort Empfehlung nur BatchNormalization nach jeder Schicht und unten nichts mehr machen.
# Für VGG16 jedoch ggf. beibehalten, da recht ursprüngliches Modell und keine CNN-Weiterentwicklung.
model.add(Flatten())
model.add(Dense(units=4096,activation="relu"))
# 0.5 eigentlich nur Startpunkt, zu reduzieren bis optimale Performance erreicht ist.
model.add(Dropout(0.5))
model.add(Dense(units=4096,activation="relu"))
# 0.5 eigentlich nur Startpunkt, zu reduzieren bis optimale Performance erreicht ist.
model.add(Dropout(0.5))
# Reduktion auf 20 Klassen (d. h. zu unterscheidende Charaktere)
model.add(Dense(units=num_classes, activation="softmax"))

# Ausgabe des Modells
model.summary()

# Importe der Optimierer (durchforsten, ob alles nötig).
from keras.optimizers import Adam, RMSprop, SGD

# Importe der Callbacks (durchforsten, ob alles nötig).
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau

# Checkpoint erstellten mit h5-Datei. Wenn alle Epochen durchlaufen sind Abspeicherung der besten Epoche.
# TESTEN AUF KORREKTEN PFAD UND ANLAGE DER DATEI.
checkpoint = ModelCheckpoint(r'/Users/holger.kiefer/simpsons_archive/simpsons_dataset/ROB43_Assignment.h5',
                             monitor="val_loss",
                             mode="min",
                             save_best_only = True,
                             verbose=1)

# Verfrühtes Ende, wenn 3x hintereinander zu wenig Veränderung beobachtbar ist.
earlystop = EarlyStopping(monitor = 'val_loss',
                          min_delta = 0,
                          patience = 3,
                          verbose = 1,
                          restore_best_weights = True)

# Reduzierung der Lernrate.
reduce_lr = ReduceLROnPlateau(monitor = 'val_loss',
                              factor = 0.2,
                              patience = 3,
                              verbose = 1,
                              min_delta = 0.00001)

# Liste an Callbacks.
callbacks = [earlystop,checkpoint, reduce_lr]

# Modell kompilieren.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Definition der Trainings- und Testdatenanzahl sowie der Epochen.
nb_train_samples = 41866
nb_test_samples = 990
epochs = 20

history = model.fit(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    #validation_data = validation_generator,
    #validation_steps = nb_validation_samples // batch_size
    )
</code>```

Body:
In building up a VGG16 neural network, I recycled some working code. But now, model.fit_generator is not supported any more. A simple substitution in "model.fit" does not work. Even though there are sources saying exactly that (compare: https://www.codesofinterest.com/2020/09/model-fit-vs-fit-generator-tfkeras.html).

Can anybody help me to deal with the issue?

I know the theoretical difference between "fit" and "fit_generator". I only have difficulties in coding.

I only used ImageDataGenerator for efficiently referring to my data basis. If there is a better way to bring the Simpsons Character Set in my model: highly welcome! I assume, < 50.000 should be able to be trained in my memory (MacBook Air 2018).

In the following, I will give the ERROR MESSAGE, OLD CODE, NEW CODE and COMPLETE PYTHON CODE.

ERROR MESSAGE

File /opt/anaconda3/envs/ROB43_T/lib/python3.10/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

OLD CODE

history = model.fit_generator(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    validation_data = validation_generator,
    validation_steps = nb_validation_samples // batch_size)

NEW CODE (exactly the same except model.fit instead of model.fit_generator

history = model.fit(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    #validation_data = validation_generator,
    #validation_steps = nb_validation_samples // batch_size
    )

My complete python code is:

# Importe diverser Programmbibliotheken.
import numpy as np
import matplotlib.pyplot as plt
import keras

# Konvertierung eines Bildes in Array (tf.keras.utils.image_dataset_from_directory wäre vielleicht besser gewesen).
from keras.preprocessing.image import ImageDataGenerator

# Import des Modells.
from keras.models import Sequential

# Import der Schichten.
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPool2D

# Modul zur Nutzung von Betriebssystemfunktionalität (z. B. Dateien laden). In Python bereits integriert.
import os

# Definition der Klassen zur Klassifizierung.
num_classes = 20

# Definition der Bildgröße.
img_rows, img_cols = 32, 32

# Definition der Stapelverarbeitung.
batch_size = 16

# Definition der Ordner für Trainings- und Testdaten.
train_data_dir = r'/Users/holger.kiefer/simpsons_archive/simpsons_dataset'
test_data_dir = r'/Users/holger.kiefer/simpsons_archive/kaggle_simpson_testset'

# Normalisierung der Trainings- und Testdaten auf Skala von 0 bis 1 statt von 0 bis 255 (RGB-Farben).
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

# Trainingsdaten laden aus Verzeichnis.
train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_rows, img_cols),
        batch_size=batch_size,
        class_mode='categorical')

# Testdaten laden aus Verzeichnis.
test_generator = test_datagen.flow_from_directory(
        test_data_dir,
        target_size=(img_rows, img_cols),
        batch_size=batch_size,
        class_mode='categorical')

# Definition des Modells. Aufbau des Algorithmus VGG16 mit 5 Stufen und Abschluss.
model = Sequential()

# padding="same" bedeutet, Nullen als "Rahmen" um Input zu legen, so dass In- & Output strukturell identisch sind.
# activation überall relu außer softmax ganz am Ende.
# kernel_size überall (3,3), strides überall (2,2), nach jeder Stufe BatchNormalization.

# Stufe 1 (3 in input_shape ergänzt wg. RGB-Farben.
model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu", input_shape=(img_rows,img_cols,3)))
model.add(Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 2
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 3
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 4
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Stufe 5
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(BatchNormalization())

# Abschluss
# Dropout als Schutz vor Überanpassung. Ein paar Layers werden nicht verwendet.
# https://www.kdnuggets.com/2018/09/dropout-convolutional-networks.html
# Dort Empfehlung nur BatchNormalization nach jeder Schicht und unten nichts mehr machen.
# Für VGG16 jedoch ggf. beibehalten, da recht ursprüngliches Modell und keine CNN-Weiterentwicklung.
model.add(Flatten())
model.add(Dense(units=4096,activation="relu"))
# 0.5 eigentlich nur Startpunkt, zu reduzieren bis optimale Performance erreicht ist.
model.add(Dropout(0.5))
model.add(Dense(units=4096,activation="relu"))
# 0.5 eigentlich nur Startpunkt, zu reduzieren bis optimale Performance erreicht ist.
model.add(Dropout(0.5))
# Reduktion auf 20 Klassen (d. h. zu unterscheidende Charaktere)
model.add(Dense(units=num_classes, activation="softmax"))

# Ausgabe des Modells
model.summary()

# Importe der Optimierer (durchforsten, ob alles nötig).
from keras.optimizers import Adam, RMSprop, SGD

# Importe der Callbacks (durchforsten, ob alles nötig).
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau

# Checkpoint erstellten mit h5-Datei. Wenn alle Epochen durchlaufen sind Abspeicherung der besten Epoche.
# TESTEN AUF KORREKTEN PFAD UND ANLAGE DER DATEI.
checkpoint = ModelCheckpoint(r'/Users/holger.kiefer/simpsons_archive/simpsons_dataset/ROB43_Assignment.h5',
                             monitor="val_loss",
                             mode="min",
                             save_best_only = True,
                             verbose=1)

# Verfrühtes Ende, wenn 3x hintereinander zu wenig Veränderung beobachtbar ist.
earlystop = EarlyStopping(monitor = 'val_loss',
                          min_delta = 0,
                          patience = 3,
                          verbose = 1,
                          restore_best_weights = True)

# Reduzierung der Lernrate.
reduce_lr = ReduceLROnPlateau(monitor = 'val_loss',
                              factor = 0.2,
                              patience = 3,
                              verbose = 1,
                              min_delta = 0.00001)

# Liste an Callbacks.
callbacks = [earlystop,checkpoint, reduce_lr]

# Modell kompilieren.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Definition der Trainings- und Testdatenanzahl sowie der Epochen.
nb_train_samples = 41866
nb_test_samples = 990
epochs = 20

history = model.fit(
    train_generator,
    steps_per_epoch = nb_train_samples // batch_size,
    epochs = epochs,
    callbacks = callbacks,
    #validation_data = validation_generator,
    #validation_steps = nb_validation_samples // batch_size
    )


问:
Why display :initial; is display :block ;when using flex but the default value of initial value is inline how it behaves?
From mdn i learned if property value is inherited by default then the propety tooks :root element means the propety tooks by default css value e.g
the propety of display is inline by default but when i give a parent display flex or display grid then the initial value of the child is display block how it behaves</p>
```<code>    <div class="parent">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, maxime?</p>
    </div>

    /* The result of p tag is block */
    .parent { display: flex; }
    p { display: initial; }

    /* The result of p tag is inline */
    p { display: initial; }
</code>```

Body:
From mdn i learned if property value is inherited by default then the propety tooks :root element means the propety tooks by default css value e.g
the propety of display is inline by default but when i give a parent display flex or display grid then the initial value of the child is display block how it behaves

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, maxime?

    /* The result of p tag is block */
    .parent { display: flex; }
    p { display: initial; }

    /* The result of p tag is inline */
    p { display: initial; }


问:
What should I use instead of textContent?
I am trying to send a message through facebook website using js console. I can send a message but I cannot change it using textContent. When I type something on chatbox it creates a span I want to change this span text. As you see on the output, after using textContent  it still outputs previous element. It means span element was not updated.

```<code>element=document.querySelector("#mount_0_0_wY > div > div:nth-child(1) > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x5yr21d.x1n2onr6.xh8yej3.x1t2pt76.x1plvlek.xryxfnj > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x2lah0s.x1nhvcw1.x1qjc9v5.xozqiw3.x1q0g3np.x78zum5.x1iyjqo2.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x1n2onr6.x1ja2u2z.xdt5ytf.x193iq5w.xeuugli.x1r8uery.x1iyjqo2.xs83m0k.x78zum5.x1t2pt76 > div > div > div > div > div > div > div.x1uvtmcs.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj > div > div > div:nth-child(2) > div > div > div.x78zum5.x1iyjqo2.x6q2ic0 > div.xmjcpbm.x107yiy2.xv8uw2v.x1tfwpuw.x2g32xy.x9f619.x1iyjqo2.xeuugli > div > div > div > p > span");
console.log(element);
console.log(element.textContent);
element.textContent="Enes";
console.log(element);
//document.querySelector("#mount_0_0_wY > div > div:nth-child(1) > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x5yr21d.x1n2onr6.xh8yej3.x1t2pt76.x1plvlek.xryxfnj > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x2lah0s.x1nhvcw1.x1qjc9v5.xozqiw3.x1q0g3np.x78zum5.x1iyjqo2.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x1n2onr6.x1ja2u2z.xdt5ytf.x193iq5w.xeuugli.x1r8uery.x1iyjqo2.xs83m0k.x78zum5.x1t2pt76 > div > div > div > div > div > div > div.x1uvtmcs.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj > div > div > div:nth-child(2) > div > span.x4k7w5x.x1h91t0o.x1h9r5lt.xv2umb2.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1qrby5j.x3nfvp2 > div").click();
</code>```

Body:
I am trying to send a message through facebook website using js console. I can send a message but I cannot change it using textContent. When I type something on chatbox it creates a span I want to change this span text. As you see on the output, after using textContent  it still outputs previous element. It means span element was not updated.

element=document.querySelector("#mount_0_0_wY > div > div:nth-child(1) > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x5yr21d.x1n2onr6.xh8yej3.x1t2pt76.x1plvlek.xryxfnj > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x2lah0s.x1nhvcw1.x1qjc9v5.xozqiw3.x1q0g3np.x78zum5.x1iyjqo2.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x1n2onr6.x1ja2u2z.xdt5ytf.x193iq5w.xeuugli.x1r8uery.x1iyjqo2.xs83m0k.x78zum5.x1t2pt76 > div > div > div > div > div > div > div.x1uvtmcs.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj > div > div > div:nth-child(2) > div > div > div.x78zum5.x1iyjqo2.x6q2ic0 > div.xmjcpbm.x107yiy2.xv8uw2v.x1tfwpuw.x2g32xy.x9f619.x1iyjqo2.xeuugli > div > div > div > p > span");
console.log(element);
console.log(element.textContent);
element.textContent="Enes";
console.log(element);
//document.querySelector("#mount_0_0_wY > div > div:nth-child(1) > div > div.x9f619.x1n2onr6.x1ja2u2z > div > div > div.x5yr21d.x1n2onr6.xh8yej3.x1t2pt76.x1plvlek.xryxfnj > div > div > div.x78zum5.xdt5ytf.x10cihs4.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x2lah0s.x1nhvcw1.x1qjc9v5.xozqiw3.x1q0g3np.x78zum5.x1iyjqo2.x1t2pt76.x1n2onr6.x1ja2u2z > div.x9f619.x1n2onr6.x1ja2u2z.xdt5ytf.x193iq5w.xeuugli.x1r8uery.x1iyjqo2.xs83m0k.x78zum5.x1t2pt76 > div > div > div > div > div > div > div.x1uvtmcs.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj > div > div > div:nth-child(2) > div > span.x4k7w5x.x1h91t0o.x1h9r5lt.xv2umb2.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1qrby5j.x3nfvp2 > div").click();


问:
How do you type hint overriding a built in axios method that returns a promise?
I've been trying to add a caching layer to apisauce.
I followed a guide on https://techblog.geekyants.com/a-guide-to-react-native-offline-support which gave me the following code:

```<code>import {create} from 'apisauce';

import cache from '../utility/cache';

const apiClient = create({
  baseURL: 'https://randomuser.me',
});

const get = apiClient.get;

//^ altering the get()
apiClient.get = async (url, params, axiosConfig) => {
  const response = await get(url, params, axiosConfig);

  if (response.ok) {
    await cache.store(url, response.data); //* caching the response
    return response;
  }

  const data = await cache.get(url); //* retrieving the data from the cache
  return data ? {ok: true, data} : response;
};

export default apiClient;
</code>```

This code works perfectly, however it throws errors which I cannot figure out how to resolve.

The specific error that I'm getting is:

src/api/client.tsx:39:1 - error TS2322: Type '<T, U = T>(url:
string, params: {} | undefined, axiosConfig: AxiosRequestConfig |
undefined) => Promise<ApiErrorResponse |
ApiOkResponse | { ...; }>' is not assignable to type '<T, U =
T>(url: string, params?: {} | undefined, axiosConfig?:
AxiosRequestConfig | undefined) => Promise<ApiResponse<T, U>>'.
Type 'Promise<ApiErrorResponse | ApiOkResponse | { ok: true; data: never; }>' is not assignable to type
'Promise<ApiResponse<T, U>>'.
Type 'ApiErrorResponse | ApiOkResponse | { ok: true; data: never; }' is not assignable to type 'ApiResponse<T,
U>'.
Type 'ApiErrorResponse' is not assignable to type 'ApiResponse<T, U>'.
Type 'ApiErrorResponse' is not assignable to type 'ApiErrorResponse'.
Type 'unknown' is not assignable to type 'U'.
'U' could be instantiated with an arbitrary type which could be unrelated to 'unknown'.

```<code>39 apiClient.get = async (url, params, axiosConfig) => {
</code>```

I have tried to add in more type hinting and return types.
However, I can't figure out how to return as the following type: ApiResponse<T, U> | PromiseLike<ApiResponse<T, U>>

```<code>const get = apiClient.get
apiClient.get = async <T, U = T>(
  url: string,
  params?: {},
  axiosConfig?: AxiosRequestConfig
): Promise<ApiResponse<T, U>> => {
  const response = await get(url, params, axiosConfig)

  if (response.ok) {
    cache.store(url, response.data)
    return new Promise((resolve, reject) => {
      resolve(ApiOkResponse<response.data>)
    })
  }

  const data = await cache.get(url)
  return new Promise((resolve, reject) => {
    if (data) {
      resolve({ ok: true, data })
    }

    reject(response)
  })
}
</code>```

Body:
I've been trying to add a caching layer to apisauce.
I followed a guide on https://techblog.geekyants.com/a-guide-to-react-native-offline-support which gave me the following code:

import {create} from 'apisauce';

import cache from '../utility/cache';

const apiClient = create({
  baseURL: 'https://randomuser.me',
});

const get = apiClient.get;

//^ altering the get()
apiClient.get = async (url, params, axiosConfig) => {
  const response = await get(url, params, axiosConfig);

  if (response.ok) {
    await cache.store(url, response.data); //* caching the response
    return response;
  }

  const data = await cache.get(url); //* retrieving the data from the cache
  return data ? {ok: true, data} : response;
};

export default apiClient;

This code works perfectly, however it throws errors which I cannot figure out how to resolve.

The specific error that I'm getting is:

src/api/client.tsx:39:1 - error TS2322: Type '<T, U = T>(url:
string, params: {} | undefined, axiosConfig: AxiosRequestConfig |
undefined) => Promise<ApiErrorResponse |
ApiOkResponse | { ...; }>' is not assignable to type '<T, U =
T>(url: string, params?: {} | undefined, axiosConfig?:
AxiosRequestConfig | undefined) => Promise<ApiResponse<T, U>>'.
Type 'Promise<ApiErrorResponse | ApiOkResponse | { ok: true; data: never; }>' is not assignable to type
'Promise<ApiResponse<T, U>>'.
Type 'ApiErrorResponse | ApiOkResponse | { ok: true; data: never; }' is not assignable to type 'ApiResponse<T,
U>'.
Type 'ApiErrorResponse' is not assignable to type 'ApiResponse<T, U>'.
Type 'ApiErrorResponse' is not assignable to type 'ApiErrorResponse'.
Type 'unknown' is not assignable to type 'U'.
'U' could be instantiated with an arbitrary type which could be unrelated to 'unknown'.

39 apiClient.get = async (url, params, axiosConfig) => {

I have tried to add in more type hinting and return types.
However, I can't figure out how to return as the following type: ApiResponse<T, U> | PromiseLike<ApiResponse<T, U>>

const get = apiClient.get
apiClient.get = async <T, U = T>(
  url: string,
  params?: {},
  axiosConfig?: AxiosRequestConfig
): Promise<ApiResponse<T, U>> => {
  const response = await get(url, params, axiosConfig)

  if (response.ok) {
    cache.store(url, response.data)
    return new Promise((resolve, reject) => {
      resolve(ApiOkResponse<response.data>)
    })
  }

  const data = await cache.get(url)
  return new Promise((resolve, reject) => {
    if (data) {
      resolve({ ok: true, data })
    }

    reject(response)
  })
}


问:
Established term for trivial "full" cache?
The simplest-possible cache works like this:

It makes sure it has got enough memory to hold the entire data structure to be cached, which lives on some slower medium.

It eagerly copies the entire data structure to memory.

It serves all requests from memory, without caring about cache misses and thus without having to access the original data structure any more.

Is there a common name for this trivial kind of cache?

I've searched for terms like "mirroring cache", "full cache", "eager cache", and "memory proxy", but didn't find anything.


问:
how to set source directory to be the downloaded artifact obtained using actions/download-artifact@v2?
```<code>deploy-windows:
    name: Deploy Windows Release
    runs-on: ubuntu-latest
    needs: build-windows
    steps:
      # checkout repository
      - uses: actions/checkout@v3
      # download release folder from artifacts
      - name: Download Windows Release
        uses: actions/download-artifact@v2
        id: download
        with:
          name: xenmusic
      - name: Pushes to another repository
        uses: vinayb21/github-action-push-to-another-repo@master
        env:
          API_TOKEN_GITHUB: ${{ secrets.API_TOKEN_GITHUB }}
        with:
          source-directory: << want to set the source dir to be the downloaded artifact folder >>
          destination-github-username: xyz
          destination-repository-name: repoB
          user-email: xyz@gmail.com
</code>```

I want to set the source directory to be the downloaded artifact folder.

I want to set the source directory to be the downloaded artifact folder.

Body:
deploy-windows:
    name: Deploy Windows Release
    runs-on: ubuntu-latest
    needs: build-windows
    steps:
      # checkout repository
      - uses: actions/checkout@v3
      # download release folder from artifacts
      - name: Download Windows Release
        uses: actions/download-artifact@v2
        id: download
        with:
          name: xenmusic
      - name: Pushes to another repository
        uses: vinayb21/github-action-push-to-another-repo@master
        env:
          API_TOKEN_GITHUB: ${{ secrets.API_TOKEN_GITHUB }}
        with:
          source-directory: << want to set the source dir to be the downloaded artifact folder >>
          destination-github-username: xyz
          destination-repository-name: repoB
          user-email: xyz@gmail.com

I want to set the source directory to be the downloaded artifact folder.

I want to set the source directory to be the downloaded artifact folder.


问:
Can't get CKEditor5 build from source working with Shakapacker, Rails 6, Vue 3
I'm trying to implement CKEditor5 (building from source) into my application. I'm using Vuejs 3 frontend, Rails 6 backend, and Shakapacker.I haven't been able to find any documentation on CKEditor5 support for Shakapacker. I tried following the Webpack guide on the official CKEditor5 documentation, but I am getting 46 errors when running bin/webpack.The errors are all related to CKEditor CSS files. Does anyone know if there is a way to get CKEditor5 to work with Shakapacker? Thank you

webpack.config.js

custom.js

package.json image 1

package.json image 2

package.json image 3

I tried following the Webpack guide on the official CKEditor5 build from source documentation: https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/alternative-setups/integrating-from-source.html I am getting 46 errors when running bin/webpack. The errors are all related to CKEditor CSS files.

the errors


问:
Wait for event.on() function to complete?
I have this code, and the function I essentially want is to run the function, and have all my code wait until the function has finished executing before continuing to execute the switch. Is there any way to wait until the promise or .on() statement is actually triggered before going to the switch statement? Currently, it will execute itself with the promise pending, not waiting for it to be fulfilled. I'm using node.js, socket.io and express currently. If this is not possible, then another node plugin would be appreciated that would enable this to work.

I'm making a poker web app btw so each turn is dependant upon the last player's turn.

```<code>_bettingPhase() {

    var index = 0;
    var pArray = this._playerArray;
    var standingBet = 0;

    async function getAction(index, playerArray) {
        var turn = null;
      let myPromise = new Promise(function(resolve) {
            playerArray[index].id.once('turn', (turn) => {
            resolve(turn);
            })
      });
      turn = await myPromise;
      console.log('getAction run');
      return(turn);
    }

    this._playerArray[index].action = getAction(index, pArray);

    switch(this._playerArray[index].action) {

        case 'raise':
            this._playerArray[index].money -= this._playerArray[index].amount + standingBet;
            standingBet = this._playerArray[index].amount;
        case 'call':
            this._playerArray[index].money -= this._playerArray[index].amount;
    }
</code>```

Body:
I have this code, and the function I essentially want is to run the function, and have all my code wait until the function has finished executing before continuing to execute the switch. Is there any way to wait until the promise or .on() statement is actually triggered before going to the switch statement? Currently, it will execute itself with the promise pending, not waiting for it to be fulfilled. I'm using node.js, socket.io and express currently. If this is not possible, then another node plugin would be appreciated that would enable this to work.

I'm making a poker web app btw so each turn is dependant upon the last player's turn.

_bettingPhase() {

    var index = 0;
    var pArray = this._playerArray;
    var standingBet = 0;

    async function getAction(index, playerArray) {
        var turn = null;
      let myPromise = new Promise(function(resolve) {
            playerArray[index].id.once('turn', (turn) => {
            resolve(turn);
            })
      });
      turn = await myPromise;
      console.log('getAction run');
      return(turn);
    }

    this._playerArray[index].action = getAction(index, pArray);

    switch(this._playerArray[index].action) {

        case 'raise':
            this._playerArray[index].money -= this._playerArray[index].amount + standingBet;
            standingBet = this._playerArray[index].amount;
        case 'call':
            this._playerArray[index].money -= this._playerArray[index].amount;
    }


问:
How can I create an array from a CSV column encoded as a string using Polars in Rust?
I'm trying to write a Rust program which uses Polars to read a CSV. This particular CSV encodes an array of floats as a string.

In my program, I want to load the CSV into a DataFrame and then parse this column into an array of floats. In Python you might write code that looks like this:

df = pd.read_csv("...")
df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)
```
<p>However in my Rust program it's not clear how to go about this. I could take an approach like this:</p>
<pre class="lang-rust prettyprint-override"><code>let mut df = CsvReader::from_path("...")?
    .has_header(true)
    .finish()?;

df.apply("babbage_search", parse_vector)?;
</code>```

However the parse_vector  function is not really clear. I might write something like this, but this won't compile:

fn parse_vector(series: &Series) -> Series {
    series
        .utf8()
        .unwrap()
        .into_iter()
        .map(|opt_v| match opt_v {
            Some(v) => {
                let vec: Vec<f64> = serde_json::from_str(v).unwrap();
                let series: Series = vec.iter().collect();
                series.f64().unwrap().to_owned() as ChunkedArray<Float64Type>
            }

            None => ChunkedArray::<Float64Type>::default(),
        })
        .collect()
}

```

I'd appreciate any help in figuring this out.

Body:
I'm trying to write a Rust program which uses Polars to read a CSV. This particular CSV encodes an array of floats as a string.

In my program, I want to load the CSV into a DataFrame and then parse this column into an array of floats. In Python you might write code that looks like this:

df = pd.read_csv("...")
df["babbage_search"] = df.babbage_search.apply(eval).apply(np.array)

However in my Rust program it's not clear how to go about this. I could take an approach like this:

let mut df = CsvReader::from_path("...")?
    .has_header(true)
    .finish()?;

df.apply("babbage_search", parse_vector)?;

However the parse_vector  function is not really clear. I might write something like this, but this won't compile:

fn parse_vector(series: &Series) -> Series {
    series
        .utf8()
        .unwrap()
        .into_iter()
        .map(|opt_v| match opt_v {
            Some(v) => {
                let vec: Vec<f64> = serde_json::from_str(v).unwrap();
                let series: Series = vec.iter().collect();
                series.f64().unwrap().to_owned() as ChunkedArray<Float64Type>
            }

            None => ChunkedArray::<Float64Type>::default(),
        })
        .collect()
}

I'd appreciate any help in figuring this out.


问:
How to get the first name and display it instead of the email in the Angular Template of ASP.NET Core in Visual Studio 2022?
I created a new solution in Visual Studio 2022 using the template "ASP.NET Core with Angular", .NET 7, and Individual Authentication. When I run the application and test it by registering a new user after extending the IdentityUser with a new class based on that to add First Name and Last Name:

```<code>public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
}
</code>```

Then when I log in, the app shows the email instead of the First Name and Last Name.

This app is configured to get the user as follows from the front end in the authorize.service.ts:

```<code>  public async completeSignIn(url: string): Promise<IAuthenticationResult> {
    try {
      await this.ensureUserManagerInitialized();
      const user = await this.userManager!.signinCallback(url);
      this.userSubject.next(user && user.profile);
      return this.success(user && user.state);
    } catch (error) {
      console.log('There was an error signing in: ', error);
      return this.error('There was an error signing in.');
    }
  }
</code>```

In the component login-menu the username is gotten as follows:

```<code>  ngOnInit() {
    this.isAuthenticated = this.authorizeService.isAuthenticated();
    this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
  }
</code>```

My question is: How can I get the FirstName and LastName in the client app? And then in the login-menu.html show that instead of the email.

Body:
I created a new solution in Visual Studio 2022 using the template "ASP.NET Core with Angular", .NET 7, and Individual Authentication. When I run the application and test it by registering a new user after extending the IdentityUser with a new class based on that to add First Name and Last Name:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
}

Then when I log in, the app shows the email instead of the First Name and Last Name.

This app is configured to get the user as follows from the front end in the authorize.service.ts:

  public async completeSignIn(url: string): Promise<IAuthenticationResult> {
    try {
      await this.ensureUserManagerInitialized();
      const user = await this.userManager!.signinCallback(url);
      this.userSubject.next(user && user.profile);
      return this.success(user && user.state);
    } catch (error) {
      console.log('There was an error signing in: ', error);
      return this.error('There was an error signing in.');
    }
  }

In the component login-menu the username is gotten as follows:

  ngOnInit() {
    this.isAuthenticated = this.authorizeService.isAuthenticated();
    this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
  }

My question is: How can I get the FirstName and LastName in the client app? And then in the login-menu.html show that instead of the email.


问:
How do you use the Facebook Marketing API sandbox to retrieve simulated insights?
I’m working on an application that is going to leverage the Facebook (Meta) Marketing API to retrieve ad campaign insights. I don’t have any real life data to work with so I was hoping to use ‘simulated insights’ aka mock data which was referred to as a future feature in a 2017 article about the Marketing API sandbox mode. Has anybody been able to get simulated insights working? I’ve setup a sandbox account and don’t receive any insights which I somewhat expected without any special arguments or specific endpoint to call. Any help is greatly appreciated</p>


问:
QT Designer Not Allowing Top Center Alignment - Python
So I'm trying to center a simple text widget in QT Designer and I can't seem to align it to the top center.

When pressing 'View Code', I noticed the following parameter was set to 'Center' in the UI file so I manually changed it to 'Top'. This did not work.

self.label.setAlignment(Qt.AlignTop)

I tried to edit the Python code by adding the following script to no avail:

```<code><layout class="QVBoxLayout" name="propertiesLayout">
 <property name="alignment">
  <set>Qt::AlignTop</set>
 </property>
</code>```

Every solution I can find says you should be able to just righ-click and choose "Top alignment" but there is no option available to do so.

HELP!

I also noticed that no matter what you change the parameter fields to, the preview doesn't seem to render it correctly in QT.

Body:
So I'm trying to center a simple text widget in QT Designer and I can't seem to align it to the top center.

When pressing 'View Code', I noticed the following parameter was set to 'Center' in the UI file so I manually changed it to 'Top'. This did not work.

self.label.setAlignment(Qt.AlignTop)

I tried to edit the Python code by adding the following script to no avail:

<layout class="QVBoxLayout" name="propertiesLayout">
 <property name="alignment">
  <set>Qt::AlignTop</set>
 </property>

Every solution I can find says you should be able to just righ-click and choose "Top alignment" but there is no option available to do so.

HELP!

I also noticed that no matter what you change the parameter fields to, the preview doesn't seem to render it correctly in QT.


问:
Tried to commit to GithHub directly from Xcode 14 and keep getting error message, but when I check GitHub everything commits perfectly fine?
So I've been trying to get my code onto GitHub after accidentally deleting one of my projects. I went into Xcode settings and connected my GitHub account under source control accounts. Then I went to source control > commit[Source Control SS](https://i.stack.imgur.com/myVQC.png) and I just keep getting the error message "Authentication failed because the credentials were rejected. Credentials SS But when I go to GitHub and check my repositories, I see all of my changes and everything has committed just fine. So why do I keep getting the error even though it commits like it's supposed to?

I tried updating my GitHub personal access token, but every time Xcode would continue to insist that my credentials were wrong. Previously I would get a popup that says please sign in again and it required me to put in my access token again, but I no longer see that popup and I only get the error message (even though everything commits perfectly fine).


问:
keras binary_crossentropy loss works well even with a shape mismatch in y_true and y_pred, while it throws error if from_logits = True?

import numpy as np
fake_preds = np.random.rand(10,768)  # assuming predictions of some model (10 examples)

fake_labels = np.random.rand(10,1)   # fake labels for 10 examples

loss1 = tf.keras.losses.BinaryCrossentropy(from_logits=True)

print(loss1(fake_labels, fake_preds).numpy())
```
<p>--> Throws shape mismatch error:</p>
```ValueError: `logits` and `labels` must have the same shape, received ((10, 768) vs (10, 1)).

loss2 = tf.keras.losses.BinaryCrossentopy(from_logits=False)

print(loss2(fake_labels, fake_preds),numpy())
```

--> 0.998 (some value for random labels and preds), works well!

Why???

Keras Documentation statest the shape of  logits and targets must be same for loss functions to work properly. Then why is it that there is no shape mismatch error on from_logits = False!

Body:
import numpy as np
fake_preds = np.random.rand(10,768)  # assuming predictions of some model (10 examples)

fake_labels = np.random.rand(10,1)   # fake labels for 10 examples

loss1 = tf.keras.losses.BinaryCrossentropy(from_logits=True)

print(loss1(fake_labels, fake_preds).numpy())

--> Throws shape mismatch error:

ValueError: `logits` and `labels` must have the same shape, received ((10, 768) vs (10, 1)).

loss2 = tf.keras.losses.BinaryCrossentopy(from_logits=False)

print(loss2(fake_labels, fake_preds),numpy())

--> 0.998 (some value for random labels and preds), works well!

Why???

Keras Documentation statest the shape of  logits and targets must be same for loss functions to work properly. Then why is it that there is no shape mismatch error on from_logits = False!


问:
Discord Oauth2 not redirecting
I'm trying to set up discord Oauth2 and have a proper url, and have it authenticating properly, but then I'm getting stuck on the below screen, rather than it redirecting to my specified url.

The URL I have in settings (this part should be correct because when it doesn't match my redirect_uri I get an invalid error, and when they do match I'm able to authenticate):

http://localhost:3000/api/auth/callback/discord

The URL I'm using to authenticate:

https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot&permissions=274878023680&redirect_uri=http%3A%2F%2Flocalhost%3A300

I visit that URL, give access to my account on a specific server, then it shows that auth succeeded, but there's no redirect, and the server running in the background doesn't receive any requests. When I paste my redirect url into my browser to test that it works manually, it loads as expected.

References:

https://discord.com/developers/docs/topics/oauth2

https://discordapi.com/permissions.html#274878023680

Title: Discord Oauth2 not redirecting


问:
How to cycle through images on Django website
I have built a photo gallery and I when an image is opened I would like to add to buttons ( Previous & Next) Which will cycle through my images based on their id/pk.

Models.py

```<code>class PostImage(models.Model):
    image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png")
    image_title = models.CharField(max_length=100, null=False, blank=False, default="")

    def __str__(self):
        return self.image_title

    class Meta:
            verbose_name_plural = 'PostImage'
</code>```

Views.py

```<code>        def galleryPage(request):
    images = PostImage.objects.all()
    context = {'images':images}

    return render(request, 'gallery.html', context)

def viewImage(request, pk):
    photo = PostImage.objects.get(id=pk)
    return render(request, 'viewimage.html', {'photo': photo})
</code>```

HTML

```<code>    <div class="image-container">
      <div class="image-post">
        <a href="{% url 'gallery' %}"
          ><img class="photo-img" src="{{photo.image.url}}"
        /></a>
        <h2 class="photo-title">{{photo.image_title}}</h2>
        <p class="contact">
          Interested in purchasing this as a print? Contact me for more
          information regarding price and sizes.
        </p>
        <a href="{% url 'contact' %}" class="btn btn-secondary" type="button"
          >Contact</a
        >
      </div>
    </div>
  </body>
</html>
</code>```

Body:
I have built a photo gallery and I when an image is opened I would like to add to buttons ( Previous & Next) Which will cycle through my images based on their id/pk.

Models.py

class PostImage(models.Model):
    image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png")
    image_title = models.CharField(max_length=100, null=False, blank=False, default="")

    def __str__(self):
        return self.image_title

    class Meta:
            verbose_name_plural = 'PostImage'

Views.py

        def galleryPage(request):
    images = PostImage.objects.all()
    context = {'images':images}

    return render(request, 'gallery.html', context)

def viewImage(request, pk):
    photo = PostImage.objects.get(id=pk)
    return render(request, 'viewimage.html', {'photo': photo})

HTML

{{photo.image_title}}

          Interested in purchasing this as a print? Contact me for more
          information regarding price and sizes.

        Contact


问:
Using ionic-native Facebook plugin in Browser
I have created a new Ionic (Capacitor) app and I want to use the native facebook plugin, The plugin documentation says that is supported in the Android, iOS and Browser platforms, but when I run the app in the browser I get a Native: tried calling Facebook.login, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator error.

How can I run the facebook plugin from the browser?


问:
How to format Code in Visual Studio Code?
Is it possible to format all of the code in Visual Studio Code to my specific prefrences.

I want the formatter to leave a space before any brackets and go onto a new line before and after any curly braces.

I do not want the formatter to format the code in any other way. I only want to format the code in these two ways.

This format should be applied automatically to any code I write after I hit save.

I have looked online and found the Prettier extension. Hovewer, this extension also formats the code in many other ways. I only want the code formatter to leave a space before any brackets and go onto a new line before and after any curly braces.


问:
Node.js readable maximize throughput/performance for compute intense readable - Writable doesn't pull data fast enough

General setup

I developed an application using AWS Lambda node.js 14.
I use a custom Readable implementation FrameCreationStream that uses node-canvas to draw images, svgs and more on a canvas. This result is then extracted as a raw image buffer in BGRA. A single image buffer contains 1920 * 1080 * 4 Bytes = 8294400 Bytes ~8 MB.
This is then piped to stdin of a child_process running ffmpeg.
The highWaterMark of my Readable in objectMode:true is set to 25 so that the internal buffer can use up to 8 MB * 25  = 200 MB.

All this works fine and also doesn't contain too much RAM. But I noticed after some time, that the performance is not ideally.

Performance not optimal

I have an example input that generates a video of 315 frames. If I set highWaterMark to a value above 25 the performance increases to the point, when I set to a value of 315 or above.

For some reason ffmpeg doesn't start to pull any data until highWaterMark is reached. Obviously thats not what I want. ffmpeg should always consume data if minimum 1 frame is cached in the Readable and if it has finished processing the frame before. And the Readable should produce more frames as long highWaterMark isn't reached or the last frame has been reached. So ideally the Readable and the Writeable are busy all the time.

I found another way to improve the speed. If I add a timeout in the _read() method of the Readable after let's say every tenth frame for 100 ms. Then the ffmpeg-Writable will use this timeout to write some frames to ffmpeg.

It seems like frames aren't passed to ffmpeg during frame creation because some node.js main thread is busy?

The fastest result I have if I increase highWaterMark above the amount of frames - which doesn't work for longer videos as this would make the AWS Lambda RAM explode. And this makes the whole streaming idea useless. Using timeouts always gives me stomach pain. Also depending on the execution on different environments a good fitting timeout might differ. Any ideas?

FrameCreationStream

```<code>import canvas from 'canvas';
import {Readable} from 'stream';
import {IMAGE_STREAM_BUFFER_SIZE, PerformanceUtil, RenderingLibraryError, VideoRendererInput} from 'vm-rendering-backend-commons';
import {AnimationAssets, BufferType, DrawingService, FullAnimationData} from 'vm-rendering-library';

/**
 * This is a proper back pressure compatible implementation of readable for a having a stream to read single frames from.
 * Whenever read() is called a new frame is created and added to the stream.
 * read() will be called internally until options.highWaterMark has been reached.
 * then calling read will be paused until one frame is read from the stream.
 */
export class FrameCreationStream extends Readable {

    drawingService: DrawingService;
    endFrameIndex: number;
    currentFrameIndex: number = 0;
    startFrameIndex: number;
    frameTimer: [number, number];
    readTimer: [number, number];
    fullAnimationData: FullAnimationData;

    constructor(animationAssets: AnimationAssets, fullAnimationData: FullAnimationData, videoRenderingInput: VideoRendererInput, frameTimer: [number, number]) {
        super({highWaterMark: IMAGE_STREAM_BUFFER_SIZE, objectMode: true});

        this.frameTimer = frameTimer;
        this.readTimer = PerformanceUtil.startTimer();

        this.fullAnimationData = fullAnimationData;

        this.startFrameIndex = Math.floor(videoRenderingInput.startFrameId);
        this.currentFrameIndex = this.startFrameIndex;
        this.endFrameIndex = Math.floor(videoRenderingInput.endFrameId);

        this.drawingService = new DrawingService(animationAssets, fullAnimationData, videoRenderingInput, canvas);
        console.time("read");
    }

    /**
     * this method is only overwritten for debugging
     * @param size
     */
    read(size?: number): string | Buffer {

        console.log("read("+size+")");
        const buffer = super.read(size);
        console.log(buffer);
        console.log(buffer?.length);
        if(buffer) {
            console.timeLog("read");
        }
        return buffer;
    }

    // _read() will be called when the stream wants to pull more data in.
    // _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. https://nodejs.org/api/stream.html#readable_readsize
    // this way it is ensured, that even though this.createImageBuffer() is async, only one frame is created at a time and the order is kept
    _read(): void {
        // as frame numbers are consecutive and unique, we have to draw each frame number (also the first and the last one)
        if (this.currentFrameIndex <= this.endFrameIndex) {
            PerformanceUtil.logTimer(this.readTimer, 'WAIT   -> READ\t');
            this.createImageBuffer()
                 .then(buffer => this.optionalTimeout(buffer))
                // push means adding a buffered raw frame to the stream
                .then((buffer: Buffer) => {
                    this.readTimer = PerformanceUtil.startTimer();
                    // the following two frame numbers start with 1 as first value
                    const processedFrameNumberOfScene = 1 + this.currentFrameIndex - this.startFrameIndex;
                    const totalFrameNumberOfScene = 1 + this.endFrameIndex - this.startFrameIndex;
                    // the overall frameId or frameIndex starts with frameId 0
                    const processedFrameIndex = this.currentFrameIndex;
                    this.currentFrameIndex++;
                    this.push(buffer); // nothing besides logging should happen after calling this.push(buffer)
                    console.log(processedFrameNumberOfScene + ' of ' + totalFrameNumberOfScene + ' processed - full video frameId: ' + processedFrameIndex + ' - buffered frames: ' + this.readableLength);
                })
                .catch(err => {
                    // errors will be finally handled, when subscribing to frameCreation stream in ffmpeg service
                    // this log is just generated for tracing errors and if for some reason the handling in ffmpeg service doesn't work
                    console.log("createImageBuffer: ", err);
                    this.emit("error", err);
                });
        } else {
            // push(null) makes clear that this stream has ended
            this.push(null);
            PerformanceUtil.logTimer(this.frameTimer, 'FRAME_STREAM');
        }
    }

    private optionalTimeout(buffer: Buffer): Promise<Buffer> {
        if(this.currentFrameIndex % 10 === 0) {
            return new Promise(resolve => setTimeout(() => resolve(buffer), 140));
        }
        return Promise.resolve(buffer);
    }

    // prevent memory leaks - without this lambda memory will increase with every call
    _destroy(): void {
        this.drawingService.destroyStage();
    }

    /**
     * This creates a raw pixel buffer that contains a single frame of the video drawn by the rendering library
     *
     */
    public async createImageBuffer(): Promise<Buffer> {

        const drawTimer = PerformanceUtil.startTimer();
        try {
            await this.drawingService.drawForFrame(this.currentFrameIndex);
        } catch (err: any) {
            throw new RenderingLibraryError(err);
        }

        PerformanceUtil.logTimer(drawTimer, 'DRAW   -> FRAME\t');

        const bufferTimer = PerformanceUtil.startTimer();
        // Creates a raw pixel buffer, containing simple binary data
        // the exact same information (BGRA/screen ratio) has to be provided to ffmpeg, because ffmpeg cannot detect format for raw input
        const buffer = await this.drawingService.toBuffer(BufferType.RAW);
        PerformanceUtil.logTimer(bufferTimer, 'CANVAS -> BUFFER');

        return buffer;
    }
}
</code>```

FfmpegService

```<code>import {ChildProcess, execFile} from 'child_process';
import {Readable} from 'stream';
import {FPS, StageSize} from 'vm-rendering-library';
import {
    FfmpegError,
    LOCAL_MERGE_VIDEOS_TEXT_FILE, LOCAL_SOUND_FILE_PATH,
    LOCAL_VIDEO_FILE_PATH,
    LOCAL_VIDEO_SOUNDLESS_MERGE_FILE_PATH
} from "vm-rendering-backend-commons";

/**
 * This class bundles all ffmpeg usages for rendering one scene.
 * FFmpeg is a console program which can transcode nearly all types of sounds, images and videos from one to another.
 */
export class FfmpegService {

    ffmpegPath: string = null;

    constructor(ffmpegPath: string) {
        this.ffmpegPath = ffmpegPath;
    }

    /**
     * Convert a stream of raw images into an .mp4 video using the command line program ffmpeg.
     *
     * @param inputStream an input stream containing images in raw format BGRA
     * @param stageSize the size of a single frame in pixels (minimum is 2*2)
     * @param outputPath the filepath to write the resulting video to
     */
    public imageToVideo(inputStream: Readable, stageSize: StageSize, outputPath: string): Promise<void> {
        const args: string[] = [
            '-f',
            'rawvideo',
            '-r',
            `${FPS}`,
            '-pix_fmt',
            'bgra',
            '-s',
            `${stageSize.width}x${stageSize.height}`,
            '-i',
            // input "-" means input will be passed via pipe (streamed)
            '-',
            // codec that also QuickTime player can understand
            '-vcodec',
            'libx264',
            '-pix_fmt',
            'yuv420p',
            /*
                * "-movflags faststart":
                * metadata at beginning of file
                * needs more RAM
                * file will be broken, if not finished properly
                * higher application compatibility
                * better for browser streaming
            */
            '-movflags',
            'faststart',
            // "-preset ultrafast", //use this to speed up compression, but quality/compression ratio gets worse
            // don't overwrite an existing file here,
            // but delete file in the beginning of execution index.ts
            // (this is better for local testing believe me)
            outputPath
        ];

        return this.execFfmpegPromise(args, inputStream);
    }

    private execFfmpegPromise(args: string[], inputStream?: Readable): Promise<void> {
        const ffmpegServiceSelf = this;
        return new Promise(function (resolve, reject) {
            const executionProcess: ChildProcess = execFile(ffmpegServiceSelf.ffmpegPath, args, (err) => {
                if (err) {
                    reject(new FfmpegError(err));
                } else {
                    console.log('ffmpeg finished');
                    resolve();
                }
            });
            if (inputStream) {
                // it's important to listen on errors of input stream before piping it into the write stream
                // if we don't do this here, we get an unhandled promise exception for every issue in the input stream
                inputStream.on("error", err => {
                    reject(err);
                });
                // don't reject promise here as the error will also be thrown inside execFile and will contain more debugging info
                // this log is just generated for tracing errors and if for some reason the handling in execFile doesn't work
                inputStream.pipe(executionProcess.stdin).on("error", err => console.log("pipe stream: " , err));
            }
        });
    }
}
</code>```

Body:
General setup

I developed an application using AWS Lambda node.js 14.
I use a custom Readable implementation FrameCreationStream that uses node-canvas to draw images, svgs and more on a canvas. This result is then extracted as a raw image buffer in BGRA. A single image buffer contains 1920 * 1080 * 4 Bytes = 8294400 Bytes ~8 MB.
This is then piped to stdin of a child_process running ffmpeg.
The highWaterMark of my Readable in objectMode:true is set to 25 so that the internal buffer can use up to 8 MB * 25  = 200 MB.

All this works fine and also doesn't contain too much RAM. But I noticed after some time, that the performance is not ideally.

Performance not optimal

I have an example input that generates a video of 315 frames. If I set highWaterMark to a value above 25 the performance increases to the point, when I set to a value of 315 or above.

For some reason ffmpeg doesn't start to pull any data until highWaterMark is reached. Obviously thats not what I want. ffmpeg should always consume data if minimum 1 frame is cached in the Readable and if it has finished processing the frame before. And the Readable should produce more frames as long highWaterMark isn't reached or the last frame has been reached. So ideally the Readable and the Writeable are busy all the time.

I found another way to improve the speed. If I add a timeout in the _read() method of the Readable after let's say every tenth frame for 100 ms. Then the ffmpeg-Writable will use this timeout to write some frames to ffmpeg.

It seems like frames aren't passed to ffmpeg during frame creation because some node.js main thread is busy?

The fastest result I have if I increase highWaterMark above the amount of frames - which doesn't work for longer videos as this would make the AWS Lambda RAM explode. And this makes the whole streaming idea useless. Using timeouts always gives me stomach pain. Also depending on the execution on different environments a good fitting timeout might differ. Any ideas?

FrameCreationStream

import canvas from 'canvas';
import {Readable} from 'stream';
import {IMAGE_STREAM_BUFFER_SIZE, PerformanceUtil, RenderingLibraryError, VideoRendererInput} from 'vm-rendering-backend-commons';
import {AnimationAssets, BufferType, DrawingService, FullAnimationData} from 'vm-rendering-library';

/**
 * This is a proper back pressure compatible implementation of readable for a having a stream to read single frames from.
 * Whenever read() is called a new frame is created and added to the stream.
 * read() will be called internally until options.highWaterMark has been reached.
 * then calling read will be paused until one frame is read from the stream.
 */
export class FrameCreationStream extends Readable {

    drawingService: DrawingService;
    endFrameIndex: number;
    currentFrameIndex: number = 0;
    startFrameIndex: number;
    frameTimer: [number, number];
    readTimer: [number, number];
    fullAnimationData: FullAnimationData;

    constructor(animationAssets: AnimationAssets, fullAnimationData: FullAnimationData, videoRenderingInput: VideoRendererInput, frameTimer: [number, number]) {
        super({highWaterMark: IMAGE_STREAM_BUFFER_SIZE, objectMode: true});

        this.frameTimer = frameTimer;
        this.readTimer = PerformanceUtil.startTimer();

        this.fullAnimationData = fullAnimationData;

        this.startFrameIndex = Math.floor(videoRenderingInput.startFrameId);
        this.currentFrameIndex = this.startFrameIndex;
        this.endFrameIndex = Math.floor(videoRenderingInput.endFrameId);

        this.drawingService = new DrawingService(animationAssets, fullAnimationData, videoRenderingInput, canvas);
        console.time("read");
    }

    /**
     * this method is only overwritten for debugging
     * @param size
     */
    read(size?: number): string | Buffer {

        console.log("read("+size+")");
        const buffer = super.read(size);
        console.log(buffer);
        console.log(buffer?.length);
        if(buffer) {
            console.timeLog("read");
        }
        return buffer;
    }

    // _read() will be called when the stream wants to pull more data in.
    // _read() will be called again after each call to this.push(dataChunk) once the stream is ready to accept more data. https://nodejs.org/api/stream.html#readable_readsize
    // this way it is ensured, that even though this.createImageBuffer() is async, only one frame is created at a time and the order is kept
    _read(): void {
        // as frame numbers are consecutive and unique, we have to draw each frame number (also the first and the last one)
        if (this.currentFrameIndex <= this.endFrameIndex) {
            PerformanceUtil.logTimer(this.readTimer, 'WAIT   -> READ\t');
            this.createImageBuffer()
                 .then(buffer => this.optionalTimeout(buffer))
                // push means adding a buffered raw frame to the stream
                .then((buffer: Buffer) => {
                    this.readTimer = PerformanceUtil.startTimer();
                    // the following two frame numbers start with 1 as first value
                    const processedFrameNumberOfScene = 1 + this.currentFrameIndex - this.startFrameIndex;
                    const totalFrameNumberOfScene = 1 + this.endFrameIndex - this.startFrameIndex;
                    // the overall frameId or frameIndex starts with frameId 0
                    const processedFrameIndex = this.currentFrameIndex;
                    this.currentFrameIndex++;
                    this.push(buffer); // nothing besides logging should happen after calling this.push(buffer)
                    console.log(processedFrameNumberOfScene + ' of ' + totalFrameNumberOfScene + ' processed - full video frameId: ' + processedFrameIndex + ' - buffered frames: ' + this.readableLength);
                })
                .catch(err => {
                    // errors will be finally handled, when subscribing to frameCreation stream in ffmpeg service
                    // this log is just generated for tracing errors and if for some reason the handling in ffmpeg service doesn't work
                    console.log("createImageBuffer: ", err);
                    this.emit("error", err);
                });
        } else {
            // push(null) makes clear that this stream has ended
            this.push(null);
            PerformanceUtil.logTimer(this.frameTimer, 'FRAME_STREAM');
        }
    }

    private optionalTimeout(buffer: Buffer): Promise<Buffer> {
        if(this.currentFrameIndex % 10 === 0) {
            return new Promise(resolve => setTimeout(() => resolve(buffer), 140));
        }
        return Promise.resolve(buffer);
    }

    // prevent memory leaks - without this lambda memory will increase with every call
    _destroy(): void {
        this.drawingService.destroyStage();
    }

    /**
     * This creates a raw pixel buffer that contains a single frame of the video drawn by the rendering library
     *
     */
    public async createImageBuffer(): Promise<Buffer> {

        const drawTimer = PerformanceUtil.startTimer();
        try {
            await this.drawingService.drawForFrame(this.currentFrameIndex);
        } catch (err: any) {
            throw new RenderingLibraryError(err);
        }

        PerformanceUtil.logTimer(drawTimer, 'DRAW   -> FRAME\t');

        const bufferTimer = PerformanceUtil.startTimer();
        // Creates a raw pixel buffer, containing simple binary data
        // the exact same information (BGRA/screen ratio) has to be provided to ffmpeg, because ffmpeg cannot detect format for raw input
        const buffer = await this.drawingService.toBuffer(BufferType.RAW);
        PerformanceUtil.logTimer(bufferTimer, 'CANVAS -> BUFFER');

        return buffer;
    }
}

FfmpegService

import {ChildProcess, execFile} from 'child_process';
import {Readable} from 'stream';
import {FPS, StageSize} from 'vm-rendering-library';
import {
    FfmpegError,
    LOCAL_MERGE_VIDEOS_TEXT_FILE, LOCAL_SOUND_FILE_PATH,
    LOCAL_VIDEO_FILE_PATH,
    LOCAL_VIDEO_SOUNDLESS_MERGE_FILE_PATH
} from "vm-rendering-backend-commons";

/**
 * This class bundles all ffmpeg usages for rendering one scene.
 * FFmpeg is a console program which can transcode nearly all types of sounds, images and videos from one to another.
 */
export class FfmpegService {

    ffmpegPath: string = null;

    constructor(ffmpegPath: string) {
        this.ffmpegPath = ffmpegPath;
    }

    /**
     * Convert a stream of raw images into an .mp4 video using the command line program ffmpeg.
     *
     * @param inputStream an input stream containing images in raw format BGRA
     * @param stageSize the size of a single frame in pixels (minimum is 2*2)
     * @param outputPath the filepath to write the resulting video to
     */
    public imageToVideo(inputStream: Readable, stageSize: StageSize, outputPath: string): Promise<void> {
        const args: string[] = [
            '-f',
            'rawvideo',
            '-r',
            `${FPS}`,
            '-pix_fmt',
            'bgra',
            '-s',
            `${stageSize.width}x${stageSize.height}`,
            '-i',
            // input "-" means input will be passed via pipe (streamed)
            '-',
            // codec that also QuickTime player can understand
            '-vcodec',
            'libx264',
            '-pix_fmt',
            'yuv420p',
            /*
                * "-movflags faststart":
                * metadata at beginning of file
                * needs more RAM
                * file will be broken, if not finished properly
                * higher application compatibility
                * better for browser streaming
            */
            '-movflags',
            'faststart',
            // "-preset ultrafast", //use this to speed up compression, but quality/compression ratio gets worse
            // don't overwrite an existing file here,
            // but delete file in the beginning of execution index.ts
            // (this is better for local testing believe me)
            outputPath
        ];

        return this.execFfmpegPromise(args, inputStream);
    }

    private execFfmpegPromise(args: string[], inputStream?: Readable): Promise<void> {
        const ffmpegServiceSelf = this;
        return new Promise(function (resolve, reject) {
            const executionProcess: ChildProcess = execFile(ffmpegServiceSelf.ffmpegPath, args, (err) => {
                if (err) {
                    reject(new FfmpegError(err));
                } else {
                    console.log('ffmpeg finished');
                    resolve();
                }
            });
            if (inputStream) {
                // it's important to listen on errors of input stream before piping it into the write stream
                // if we don't do this here, we get an unhandled promise exception for every issue in the input stream
                inputStream.on("error", err => {
                    reject(err);
                });
                // don't reject promise here as the error will also be thrown inside execFile and will contain more debugging info
                // this log is just generated for tracing errors and if for some reason the handling in execFile doesn't work
                inputStream.pipe(executionProcess.stdin).on("error", err => console.log("pipe stream: " , err));
            }
        });
    }
}


问:
how to solve origin 'http://127.0.0.1:9000' has been blocked by CORS policy
Access to font at 'https://fra1.digitaloceanspaces.com/ewan-space/ewan/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://127.0.0.1:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

i see tihis erorr in django admin  when i collect my static in digitalochenspace , and it's work fine in when collect static in localhost,

this is my code

settings

```<code>#installed apps
 "corsheaders",

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",]

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL=True
</code>```

django 3.2

python 3.8

how to solve this problem ?

Body:
Access to font at 'https://fra1.digitaloceanspaces.com/ewan-space/ewan/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://127.0.0.1:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

i see tihis erorr in django admin  when i collect my static in digitalochenspace , and it's work fine in when collect static in localhost,

this is my code

settings

#installed apps
 "corsheaders",

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",]

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL=True

django 3.2

python 3.8

how to solve this problem ?


问:
delayChildren is being applied to child elements hover animation
I am stumbling across some weird behavior. When my parent variant has a transition for delayChildren + staggerChildren, my child element's animation when un-hovering is having the delayChildren being applied.

Is that the normal behavior? I've recreated a sandbox. Hover over the element and you see.

https://codesandbox.io/s/framer-motion-bug-cn2y5c?file=/src/App.js


问:
How can I display an image using Springboot-Thymeleaf
I am new to Spring boot, and I am trying to display an image from mySQL (Blob) using thymeleaf, saving to the database as a byte array was no problem, however I am having trouble on how to display it on my html page how should I go about this? Im trying to display the images on the home page

My Entity Class

@Entity
@Table(name = "posts")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

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

    @Lob
    @Column(name = "img")
    private byte[] image;

    @OneToOne(cascade = {CascadeType.DETACH,
                        CascadeType.MERGE,
                        CascadeType.PERSIST,
                        CascadeType.REFRESH})
    @JoinColumn(name = "category_id")
    private Category category;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", text='" + text + '\'' +
                ", image=" + Arrays.toString(image) +
                ", category=" + category +
                '}';
    }```
</div>
</div>
</p>
<p>My Controller</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    @Autowired
    ItemService itemService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    EmailSenderService senderService;

    @GetMapping("/home")
    public String index(Model model){
        List<Item> headwearItems = itemService.findAllHeadwear();

        model.addAttribute("clothes", headwearItems);
        return "index";
    }</code>```

Html file attempting to display it

Headwear

```

Result is a blank image Icon

Link to github repository https://github.com/crisncris0000/BeginnerSideWork/tree/main/ShoppingSite

Body:
I am new to Spring boot, and I am trying to display an image from mySQL (Blob) using thymeleaf, saving to the database as a byte array was no problem, however I am having trouble on how to display it on my html page how should I go about this? Im trying to display the images on the home page

My Entity Class

@Entity
@Table(name = "posts")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

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

    @Lob
    @Column(name = "img")
    private byte[] image;

    @OneToOne(cascade = {CascadeType.DETACH,
                        CascadeType.MERGE,
                        CascadeType.PERSIST,
                        CascadeType.REFRESH})
    @JoinColumn(name = "category_id")
    private Category category;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", text='" + text + '\'' +
                ", image=" + Arrays.toString(image) +
                ", category=" + category +
                '}';
    }

My Controller

    @Autowired
    ItemService itemService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    EmailSenderService senderService;

    @GetMapping("/home")
    public String index(Model model){
        List<Item> headwearItems = itemService.findAllHeadwear();

        model.addAttribute("clothes", headwearItems);
        return "index";
    }

Html file attempting to display it

Headwear

Result is a blank image Icon

Link to github repository https://github.com/crisncris0000/BeginnerSideWork/tree/main/ShoppingSite


问:
Why is nothing being printed onto the file?
I have two arrays which I am reusing. I found that if I don't use memset, the content from the previous loop will stay in the array, messing up my output. The problem now is that when I try to print the content of the array, it won't print a thing, even though the array is not empty. What could it be causing it and how could i fix it? Thanks in advance.
`

```<code>else{
    while (!feof(fit)){
        fgets(text, MAX, fit);
        xifrar_frase(text, m_clau, text_xifrat);
        fprintf(fit_x, "%s\n", text_xifrat);
        memset(text, '\0', sizeof(text));
        memset(text_xifrat, '\0', sizeof(text));
    }
}
</code>```

`

I have debugged the code and seen that the mistake is not in the arrays being empty. I am using memset because I found it was the first method that cleared the arrays, if you have a better method I'll happily change it.

Body:
I have two arrays which I am reusing. I found that if I don't use memset, the content from the previous loop will stay in the array, messing up my output. The problem now is that when I try to print the content of the array, it won't print a thing, even though the array is not empty. What could it be causing it and how could i fix it? Thanks in advance.
`

else{
    while (!feof(fit)){
        fgets(text, MAX, fit);
        xifrar_frase(text, m_clau, text_xifrat);
        fprintf(fit_x, "%s\n", text_xifrat);
        memset(text, '\0', sizeof(text));
        memset(text_xifrat, '\0', sizeof(text));
    }
}

`

I have debugged the code and seen that the mistake is not in the arrays being empty. I am using memset because I found it was the first method that cleared the arrays, if you have a better method I'll happily change it.


问:
Stumped. How do I convert my datetime format to an acceptable format for pandas and mplfinance?
I am trying to use various charting packages for ohlc bar charting.  Some success but I keep getting stuck on "TypeError: Expect data.index as DatetimeIndex".  The samples that I copy work perfectly fine, like this below:

import yfinance as yf
import mplfinance as mpf
symbol = 'AAPL'
df = yf.download(symbol, period='6mo')
mpf.plot(df, type='candle')

```
<p>which has the following type of index for the df :</p>
<pre class="lang-py prettyprint-override"><code>DatetimeIndex(['2022-06-30', '2022-07-01', '2022-07-05', '2022-07-06',
               '2022-12-29', '2022-12-30'],
              dtype='datetime64[ns]', name='Date', length=128, freq=None)

</code>```

So I am trying to get my dataframe index to look the same, with a DatetimeIndex format.  My index looks like this:

0       2022-11-09 14:30:00+00:00
1       2022-11-09 14:35:00+00:00
2       2022-11-09 14:40:00+00:00
3       2022-11-09 14:45:00+00:00
4       2022-11-09 14:50:00+00:00
                  ...
2299    2022-12-21 20:35:00+00:00
2300    2022-12-21 20:40:00+00:00
2301    2022-12-21 20:45:00+00:00
2302    2022-12-21 20:50:00+00:00
2303    2022-12-21 20:55:00+00:00
Name: date, Length: 2304, dtype: object
```
<p>Note the default integer index on left.   I believe that I dont need to format it exactly the same, as long the internal datatype being datetime64 in a DatetimeIndex form.</p>
<p>thanks for any help.</p>
<p>So I tried this ( and whole lot of other ideas)</p>
<pre class="lang-py prettyprint-override"><code>    df['timestamp'] = pd.to_datetime(df.date)
    new = pd.DataFrame(index=[df.timestamp])

</code>```

which gives

MultiIndex([('2022-11-09 14:30:00+00:00',),
            ...
            ('2022-12-21 20:55:00+00:00',)],
           names=['timestamp'], length=2304)

```
<p>as well as this:</p>
<pre class="lang-py prettyprint-override"><code> df['timestamp'] = mpl_dates.datestr2num(df.date)

</code>```

which gives:

MultiIndex([(19305.604166666668,),
            ( 19305.60763888889,),

            (19347.868055555555,),
            (19347.871527777777,)],
           names=['timestamp'], length=2304)
```

and neither work.

Am I on the right track, and what is the correct way to do this? How do I get rid of the MultiIndex? And how do I get it to be of type DatetimeIndex?

responding to the question on source of data, its from IBKR, using API routines and I am storing the data in an intermediary CSV file.  It has the following format:

,date,open,high,low,close,volume,barCount,average 0,2022-11-09
14:30:00+00:00,174.44,174.44,173.8,174.05,994,64,174.408 1,2022-11-09
14:35:00+00:00,174.11,174.38,173.58,173.62,160,123,173.95 2,2022-11-09
14:40:00+00:00,173.59,173.6,173.14,173.56,98,73,173.363 3,2022-11-09
14:45:00+00:00,173.55,174.02,173.52,173.96,88,53,173.716

I was reading in with the following:
`bars = pd.read_csv(name, header=0, index_col=0, sep=",")

Body:
I am trying to use various charting packages for ohlc bar charting.  Some success but I keep getting stuck on "TypeError: Expect data.index as DatetimeIndex".  The samples that I copy work perfectly fine, like this below:

import yfinance as yf
import mplfinance as mpf
symbol = 'AAPL'
df = yf.download(symbol, period='6mo')
mpf.plot(df, type='candle')

which has the following type of index for the df :

DatetimeIndex(['2022-06-30', '2022-07-01', '2022-07-05', '2022-07-06',
               '2022-12-29', '2022-12-30'],
              dtype='datetime64[ns]', name='Date', length=128, freq=None)

So I am trying to get my dataframe index to look the same, with a DatetimeIndex format.  My index looks like this:

0       2022-11-09 14:30:00+00:00
1       2022-11-09 14:35:00+00:00
2       2022-11-09 14:40:00+00:00
3       2022-11-09 14:45:00+00:00
4       2022-11-09 14:50:00+00:00
                  ...
2299    2022-12-21 20:35:00+00:00
2300    2022-12-21 20:40:00+00:00
2301    2022-12-21 20:45:00+00:00
2302    2022-12-21 20:50:00+00:00
2303    2022-12-21 20:55:00+00:00
Name: date, Length: 2304, dtype: object

Note the default integer index on left.   I believe that I dont need to format it exactly the same, as long the internal datatype being datetime64 in a DatetimeIndex form.

thanks for any help.

So I tried this ( and whole lot of other ideas)

    df['timestamp'] = pd.to_datetime(df.date)
    new = pd.DataFrame(index=[df.timestamp])

which gives

MultiIndex([('2022-11-09 14:30:00+00:00',),
            ...
            ('2022-12-21 20:55:00+00:00',)],
           names=['timestamp'], length=2304)

as well as this:

 df['timestamp'] = mpl_dates.datestr2num(df.date)

which gives:

MultiIndex([(19305.604166666668,),
            ( 19305.60763888889,),

            (19347.868055555555,),
            (19347.871527777777,)],
           names=['timestamp'], length=2304)

and neither work.

Am I on the right track, and what is the correct way to do this? How do I get rid of the MultiIndex? And how do I get it to be of type DatetimeIndex?

responding to the question on source of data, its from IBKR, using API routines and I am storing the data in an intermediary CSV file.  It has the following format:

,date,open,high,low,close,volume,barCount,average 0,2022-11-09
14:30:00+00:00,174.44,174.44,173.8,174.05,994,64,174.408 1,2022-11-09
14:35:00+00:00,174.11,174.38,173.58,173.62,160,123,173.95 2,2022-11-09
14:40:00+00:00,173.59,173.6,173.14,173.56,98,73,173.363 3,2022-11-09
14:45:00+00:00,173.55,174.02,173.52,173.96,88,53,173.716

I was reading in with the following:
`bars = pd.read_csv(name, header=0, index_col=0, sep=",")


问:
How to display window overtop toolbar in a Mac Catalyst app similar to modal presentations?
In an iOS app, you can display a window overtop everything (navigation bar, tab bar, etc) by simply adding a subview to your key UIWindow. You can build a custom alert or loading view with a dim overlay using this approach.

If you try this in a Mac Catalyst app, it will cover up your main interface and the sidebar, but it will not cover up the toolbar. I've also tried creating a new UIWindow but it too doesn't overlay the toolbar.

```<code>if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
    let newWindow = UIWindow(windowScene: windowScene)
    newWindow?.windowLevel = .alert + 100
    newWindow?.backgroundColor = .black.withAlphaComponent(0.5)
    newWindow?.makeKeyAndVisible()
}
</code>```

How can you create a UIWindow to appear overtop your NSToolbar in a Mac Catalyst app, similar to how modal form sheet presentations cover up the entire window?

Body:
In an iOS app, you can display a window overtop everything (navigation bar, tab bar, etc) by simply adding a subview to your key UIWindow. You can build a custom alert or loading view with a dim overlay using this approach.

If you try this in a Mac Catalyst app, it will cover up your main interface and the sidebar, but it will not cover up the toolbar. I've also tried creating a new UIWindow but it too doesn't overlay the toolbar.

if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
    let newWindow = UIWindow(windowScene: windowScene)
    newWindow?.windowLevel = .alert + 100
    newWindow?.backgroundColor = .black.withAlphaComponent(0.5)
    newWindow?.makeKeyAndVisible()
}

How can you create a UIWindow to appear overtop your NSToolbar in a Mac Catalyst app, similar to how modal form sheet presentations cover up the entire window?