问:
How to use ValidationPipe to transform json to objcet from body while using FileInterceptor to upload file?
I using the below code to do file upload.But seem the @Body('body') createFileDto: CreateFileDto can't be proccess by ValidationPipe and throw error: an unknown value was passed to the validate function.

@Controller('files')
export class FilesController {
  constructor(private readonly filesService: FilesService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFileToServer(
    @UploadedFile() file: Express.Multer.File,
    @Body('body') createFileDto: CreateFileDto,
    @ActiveUser() user: ActiveUserType,
  ) {
    console.log(createFileDto);
    return this.filesService.create(createFileDto, file, user);
  }
}
```
<pre class="lang-js prettyprint-override"><code>async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });
  app.useLogger(app.select(LoggerModule).get(CustomLogger));
  const configService = app.get(ConfigService);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      enableDebugMessages: true,
      // forbidUnknownValues: false,
    }),
  );
  app.listen(configService.get<number>('appPort'), () => {
    const logger = new Logger('Bootstrap');
    logger.log(
      `${configService.get<string>(
        'appName',
      )} service is running on port:${configService.get<number>('appPort')}`,
    );
  });
}
</code>```

export class CreateFileDto {
  fileName?: string;

  expirationTime?: number;
}
```
<p>I expecting ValidationPipe can process json parese and the transform just like others. Now I try to use custom pipe to do with it.</p>
<pre class="lang-js prettyprint-override"><code>@Injectable()
export class JsonParsePipe implements PipeTransform {
  transform(value: any) {
    try {
      const obj = JSON.parse(value);
      return obj;
    } catch (err) {
      throw new BadRequestException(err.message);
    }
  }
}
</code>```

@Injectable()
export class TransformPipe implements PipeTransform {
  constructor(private logger: CustomLogger) {}
  transform(obj: any, metadata: ArgumentMetadata) {
    let tarnsFormObj: any = undefined;
    if (this.isConstructor(metadata.metatype)) {
      tarnsFormObj = new metadata.metatype();
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          tarnsFormObj[key] = obj[key];
        }
      }
    } else {
      this.logger.warn(`TransformPipe not transform the object`, TransformPipe.name, obj);
    }
    return tarnsFormObj ?? obj;
  }
  private isConstructor(f: any): f is Constructor {
    try {
      Reflect.construct(String, [], f);
    } catch (e) {
      return false;
    }
    return true;
  }
}
```
<pre class="lang-js prettyprint-override"><code>  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFileToServer(
    @UploadedFile() file: Express.Multer.File,
    @Body('body', JsonParsePipe, TransformPipe) _createFileDto: CreateFileDto,
    @ActiveUser() user: ActiveUserType,
  ) {
    return this.filesService.create(_createFileDto, file, user);
  }
</code>```

Body:
I using the below code to do file upload.But seem the @Body('body') createFileDto: CreateFileDto can't be proccess by ValidationPipe and throw error: an unknown value was passed to the validate function.

@Controller('files')
export class FilesController {
  constructor(private readonly filesService: FilesService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFileToServer(
    @UploadedFile() file: Express.Multer.File,
    @Body('body') createFileDto: CreateFileDto,
    @ActiveUser() user: ActiveUserType,
  ) {
    console.log(createFileDto);
    return this.filesService.create(createFileDto, file, user);
  }
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });
  app.useLogger(app.select(LoggerModule).get(CustomLogger));
  const configService = app.get(ConfigService);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      enableDebugMessages: true,
      // forbidUnknownValues: false,
    }),
  );
  app.listen(configService.get<number>('appPort'), () => {
    const logger = new Logger('Bootstrap');
    logger.log(
      `${configService.get<string>(
        'appName',
      )} service is running on port:${configService.get<number>('appPort')}`,
    );
  });
}

export class CreateFileDto {
  fileName?: string;

  expirationTime?: number;
}

I expecting ValidationPipe can process json parese and the transform just like others. Now I try to use custom pipe to do with it.

@Injectable()
export class JsonParsePipe implements PipeTransform {
  transform(value: any) {
    try {
      const obj = JSON.parse(value);
      return obj;
    } catch (err) {
      throw new BadRequestException(err.message);
    }
  }
}

@Injectable()
export class TransformPipe implements PipeTransform {
  constructor(private logger: CustomLogger) {}
  transform(obj: any, metadata: ArgumentMetadata) {
    let tarnsFormObj: any = undefined;
    if (this.isConstructor(metadata.metatype)) {
      tarnsFormObj = new metadata.metatype();
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          tarnsFormObj[key] = obj[key];
        }
      }
    } else {
      this.logger.warn(`TransformPipe not transform the object`, TransformPipe.name, obj);
    }
    return tarnsFormObj ?? obj;
  }
  private isConstructor(f: any): f is Constructor {
    try {
      Reflect.construct(String, [], f);
    } catch (e) {
      return false;
    }
    return true;
  }
}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFileToServer(
    @UploadedFile() file: Express.Multer.File,
    @Body('body', JsonParsePipe, TransformPipe) _createFileDto: CreateFileDto,
    @ActiveUser() user: ActiveUserType,
  ) {
    return this.filesService.create(_createFileDto, file, user);
  }


来源: stackexchange

问:
Infer object with Pothos without to call implement
I have a z object created like this:

```<code>import z from 'zod';
import { ObjectId } from 'mongodb';

interface IAppMenuItem {
    folder: string;
    unit: string;
    items: IAppMenuItem[];
}

const zAppMenuItem: z.ZodType<IAppMenuItem> = z.lazy(() =>
    z.object({
        folder: z.string().trim().min(1).max(20),
        unit: z.string().trim().min(1).max(20),
        items: z.array(zAppMenuItem)
    })
);

export const zApp = z.object({
    orgId: z.instanceof(ObjectId),
    name: z.string().trim().min(1).max(50),
    caption: z.string().trim().min(1).max(50),
    menu: z.array(zAppMenuItem).optional(),
});
</code>```

....

```<code>import { z } from 'zod';
import { zApp } from '../validators';
import { ChangeLog } from './ChangeLog';

export type App = z.infer<typeof zApp> & { changeLog: ChangeLog };
</code>```

then I have a builder file

```<code>const builder = new SchemaBuilder<{
    Objects: {
        AppObject: WithId<App>;
    };
    Scalars: {
        Id: { Input: Id; Output: Id };
        Date: { Input: Date; Output: Date };
        DateTime: { Input: Date; Output: Date };
    };
    Context: Context;
}>({});

export const AppObject = builder.objectRef<WithId<App>>('App');
export const ChangeLogObject = builder.objectRef<ChangeLog>('ChangeLog');

ChangeLogObject.implement({
  fields: t => ({
    createdAt: t.expose('createdAt', { type: 'DateTime', nullable: true }),
    createdById: t.expose('createdById', { type: 'Id', nullable: true }),
    createdByName: t.expose('createdByName', { type: 'String', nullable: true }),
    updatedAt: t.expose('updatedAt', { type: 'DateTime', nullable: true }),
    updatedById: t.expose('updatedById', { type: 'Id', nullable: true }),
    updatedByName: t.expose('updatedByName', { type: 'String', nullable: true })
  })
</code>```

});

```<code>AppObject.implement({
    fields: t => ({
        _id: t.expose('_id', { type: 'Id' }),
        orgId: t.expose('orgId', { type: 'Id' }),
        name: t.expose('name', { type: 'String' }),
        caption: t.expose('caption', { type: 'String' }),
        // menu should be implemented here...
        changeLog: t.expose('changeLog', { type: ChangeLogObject })
    })
});

export { builder };
</code>```

Because the zApp object will have even more nested objects like menu and units, it's not practical to implement for each the corresponding model under pothos.

Is there any way to infer the App type, so that Pothos will understand the model?

ContentLicense: CC BY-SA 4.0

Body:
I have a z object created like this:

import z from 'zod';
import { ObjectId } from 'mongodb';

interface IAppMenuItem {
    folder: string;
    unit: string;
    items: IAppMenuItem[];
}

const zAppMenuItem: z.ZodType<IAppMenuItem> = z.lazy(() =>
    z.object({
        folder: z.string().trim().min(1).max(20),
        unit: z.string().trim().min(1).max(20),
        items: z.array(zAppMenuItem)
    })
);

export const zApp = z.object({
    orgId: z.instanceof(ObjectId),
    name: z.string().trim().min(1).max(50),
    caption: z.string().trim().min(1).max(50),
    menu: z.array(zAppMenuItem).optional(),
});

....

import { z } from 'zod';
import { zApp } from '../validators';
import { ChangeLog } from './ChangeLog';

export type App = z.infer<typeof zApp> & { changeLog: ChangeLog };

then I have a builder file

const builder = new SchemaBuilder<{
    Objects: {
        AppObject: WithId<App>;
    };
    Scalars: {
        Id: { Input: Id; Output: Id };
        Date: { Input: Date; Output: Date };
        DateTime: { Input: Date; Output: Date };
    };
    Context: Context;
}>({});

export const AppObject = builder.objectRef<WithId<App>>('App');
export const ChangeLogObject = builder.objectRef<ChangeLog>('ChangeLog');

ChangeLogObject.implement({
  fields: t => ({
    createdAt: t.expose('createdAt', { type: 'DateTime', nullable: true }),
    createdById: t.expose('createdById', { type: 'Id', nullable: true }),
    createdByName: t.expose('createdByName', { type: 'String', nullable: true }),
    updatedAt: t.expose('updatedAt', { type: 'DateTime', nullable: true }),
    updatedById: t.expose('updatedById', { type: 'Id', nullable: true }),
    updatedByName: t.expose('updatedByName', { type: 'String', nullable: true })
  })

});

AppObject.implement({
    fields: t => ({
        _id: t.expose('_id', { type: 'Id' }),
        orgId: t.expose('orgId', { type: 'Id' }),
        name: t.expose('name', { type: 'String' }),
        caption: t.expose('caption', { type: 'String' }),
        // menu should be implemented here...
        changeLog: t.expose('changeLog', { type: ChangeLogObject })
    })
});

export { builder };

Because the zApp object will have even more nested objects like menu and units, it's not practical to implement for each the corresponding model under pothos.

Is there any way to infer the App type, so that Pothos will understand the model?


问:
Adjusting Plotly graph objects to cleanup my wafer map
Okay, I am trying to build out a heat map that looks at etch depth on Si wafer. I have successfully generated the graph and have been playing with several of the 'options' but visually it still looks like trash.

Wafer Map

A few questions:

How to make the data squares actual squares or possibly even another shape (like a filled circle).

I have data that drives up and down both axes (28-30 points total) that are very, very, thin rectangles. How can I turn these guys into squares as well?

Last item. I know by using 'xgap' and 'ygap' I can help some of the dead areas by overlap. Is there a better/simpler way to do this? You lose a little bit of data with the overlap.

Here is the code for reference:

```<code>import csv
import plotly.graph_objects as go

# Open the CSV file
with open('MyCSV.csv', 'r') as f:
  # Read the CSV file using a dict reader
  reader = csv.DictReader(f)

  # Extract the x, y, and third columns
  coords = [(float(row['X(mm)']), float(row['Y(mm)']), float(row['Delta Thick (nm)'])) for row in reader]

# Extract the x and y coordinates and the third column values
x, y, z = zip(*coords)

# Create the heatmap
fig = go.Figure(data=go.Heatmap(
                   x=x,
                   y=y,
                   z=z,
                   xgap=30,
                   ygap=30,
                   colorscale=[[0, 'rgb(255, 0, 0)'], [0.5, 'rgb(255, 255, 0)'], [1, 'rgb(0, 255, 0)']]))

# Set the aspect ratio of the x and y axes
fig.update_layout(
    width=800,
    height=800
)

# Set the limits of the x and y axes
fig.update_layout(xaxis=dict(range=[-80, 80]), yaxis=dict(range=[-80, 80]))

# Add a circle to the heat map
fig.add_shape(
    type='circle',
    xref='x',
    yref='y',
    x0=-75,
    y0=-75,
    x1=75,
    y1=75,
    fillcolor='rgba(0,0,0,0)',
    line_color='black',
    line_width=2)

# Show the plot
fig.show()

</code>```

Thanks all!

I've tried adjusting xgap and ygap, tried changing position of the squares, and have tried using an entirely different heatmap config to no avail.

Body:
Okay, I am trying to build out a heat map that looks at etch depth on Si wafer. I have successfully generated the graph and have been playing with several of the 'options' but visually it still looks like trash.

Wafer Map

A few questions:

How to make the data squares actual squares or possibly even another shape (like a filled circle).

I have data that drives up and down both axes (28-30 points total) that are very, very, thin rectangles. How can I turn these guys into squares as well?

Last item. I know by using 'xgap' and 'ygap' I can help some of the dead areas by overlap. Is there a better/simpler way to do this? You lose a little bit of data with the overlap.

Here is the code for reference:

import csv
import plotly.graph_objects as go

# Open the CSV file
with open('MyCSV.csv', 'r') as f:
  # Read the CSV file using a dict reader
  reader = csv.DictReader(f)

  # Extract the x, y, and third columns
  coords = [(float(row['X(mm)']), float(row['Y(mm)']), float(row['Delta Thick (nm)'])) for row in reader]

# Extract the x and y coordinates and the third column values
x, y, z = zip(*coords)

# Create the heatmap
fig = go.Figure(data=go.Heatmap(
                   x=x,
                   y=y,
                   z=z,
                   xgap=30,
                   ygap=30,
                   colorscale=[[0, 'rgb(255, 0, 0)'], [0.5, 'rgb(255, 255, 0)'], [1, 'rgb(0, 255, 0)']]))

# Set the aspect ratio of the x and y axes
fig.update_layout(
    width=800,
    height=800
)

# Set the limits of the x and y axes
fig.update_layout(xaxis=dict(range=[-80, 80]), yaxis=dict(range=[-80, 80]))

# Add a circle to the heat map
fig.add_shape(
    type='circle',
    xref='x',
    yref='y',
    x0=-75,
    y0=-75,
    x1=75,
    y1=75,
    fillcolor='rgba(0,0,0,0)',
    line_color='black',
    line_width=2)

# Show the plot
fig.show()

Thanks all!

I've tried adjusting xgap and ygap, tried changing position of the squares, and have tried using an entirely different heatmap config to no avail.


问:
Using trailing return type to prevent function template instantiation?
While toying with crude reproductions of some of C++17 if constexpr functionalities, I encountered an issue where using auto seems to trigger the instantiation of a template.

The function template in question contains an assertion which fails as expected when its parameters have certain properties (say sizeof).

In C++17 you could trivially use the if constexpr to protect against instantiating the wrong template in favor of a more appropriate one. This is the behavior I seek to reproduce. And I would like to understand why the trailing return type of the Working() template below does the trick but not the NotWorking() template.

The code is available at: https://godbolt.org/z/7he9hPMaM

As noted @LanguageLawyer, the code can be further reduced to:

```<code>template <typename T>
auto* NotWorking() {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

template <typename T>
auto Working() -> T* {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

#define PRODUCE_ERROR

template <typename T>
void not_called_closure_operator(T) {
#if defined(PRODUCE_ERROR)
    NotWorking<long>();
#else
    Working<long>();
#endif
}
</code>```

Code available at: https://godbolt.org/z/oGqb5v9j4

Body:
While toying with crude reproductions of some of C++17 if constexpr functionalities, I encountered an issue where using auto seems to trigger the instantiation of a template.

The function template in question contains an assertion which fails as expected when its parameters have certain properties (say sizeof).

In C++17 you could trivially use the if constexpr to protect against instantiating the wrong template in favor of a more appropriate one. This is the behavior I seek to reproduce. And I would like to understand why the trailing return type of the Working() template below does the trick but not the NotWorking() template.

The code is available at: https://godbolt.org/z/7he9hPMaM

As noted @LanguageLawyer, the code can be further reduced to:

template <typename T>
auto* NotWorking() {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

template <typename T>
auto Working() -> T* {
    static_assert(sizeof(T) <= 4, "");
    return static_cast<T*>(nullptr);
}

#define PRODUCE_ERROR

template <typename T>
void not_called_closure_operator(T) {
#if defined(PRODUCE_ERROR)
    NotWorking<long>();
#else
    Working<long>();
#endif
}

Code available at: https://godbolt.org/z/oGqb5v9j4


问:
`Exception: Range not found` in function to get a users email and the date on edit of specific column's rows
I am trying to write a google scripts app that picks up on a gsheets users email whilst they fill in a value into a row of a cell (promotion cell) in A and writes the email to the email cell (B) then the date they filled it in into the Date cell (C).

Promotion Cell
Email
Date

1
johndoe@gmail
2022-10-10

The idea is that using the onEdit I can get a users email and the date automatically in rows B and C. But for some reason, my code is not working the error being on the range variable in the fillEmailAndDate function. I am not sure why this is not executing.

```<code>function onEdit(e) {
  Logger.info(e)
  // get the active sheet
  sheet = e.source.getActiveSheet()

  // Get the active cell
  var cell = e.source.getActiveCell();

  // Get the row and column of the active cell
  var row = cell.getRow(); //1.0 clicking on cell 1 of promotion cell
  var col = cell.getColumn(); // 1.0
  // Get the letter of the promotion column
  var promotionColumn = 'C';

  // Get the letters of the email and date columns
  var emailColumn = 'E';
  var dateColumn = 'F';

  // If the active cell is in the promotion column
  if (Math.round(col) == getNumber(promotionColumn)) {

    // Run the fillEmailAndDate function
    fillEmailAndDate(e, coverage_sheet, promotionColumn, emailColumn, dateColumn, row);
  }
}

function fillEmailAndDate(e, sheet, promotionColumn, emailColumn, dateColumn, lastRow) {
  // Get the range of cells to be checked
  var range = sheet.getRange(promotionColumn + "2:" + promotionColumn + lastRow);

  // Use the onEdit trigger to detect when a cell in the promotion column is edited
  sheet.getRange(range).setOnEdit(function(e) {
    // Get the active cell
    var cell = e.source.getActiveCell();

    // Get the row and column of the active cell
    var row = cell.getRow();
    var col = cell.getColumn();

    // If the active cell is in the promotion column
    if (col == promotionColumn) {
      // Get the email and date columns for the active row
      var emailCell = sheet.getRange(emailColumn + row);
      var dateCell = sheet.getRange(dateColumn + row);

      // Get the user's email address from the email column
      var email = Session.getActiveUser().getEmail();

      // Fill in the email and date cells with the user's email address and the current date
      emailCell.setValue(email);
      dateCell.setValue(new Date());
    }
  });
}
function getNumber(letter) {
  // Make sure letter is uppercase
  letter = letter.toUpperCase();
  // Convert letter to a character code and return the corresponding number
  return letter.charCodeAt(0) - 64;
}
</code>```

Body:
I am trying to write a google scripts app that picks up on a gsheets users email whilst they fill in a value into a row of a cell (promotion cell) in A and writes the email to the email cell (B) then the date they filled it in into the Date cell (C).

Promotion Cell
Email
Date

1
johndoe@gmail
2022-10-10

The idea is that using the onEdit I can get a users email and the date automatically in rows B and C. But for some reason, my code is not working the error being on the range variable in the fillEmailAndDate function. I am not sure why this is not executing.

function onEdit(e) {
  Logger.info(e)
  // get the active sheet
  sheet = e.source.getActiveSheet()

  // Get the active cell
  var cell = e.source.getActiveCell();

  // Get the row and column of the active cell
  var row = cell.getRow(); //1.0 clicking on cell 1 of promotion cell
  var col = cell.getColumn(); // 1.0
  // Get the letter of the promotion column
  var promotionColumn = 'C';

  // Get the letters of the email and date columns
  var emailColumn = 'E';
  var dateColumn = 'F';

  // If the active cell is in the promotion column
  if (Math.round(col) == getNumber(promotionColumn)) {

    // Run the fillEmailAndDate function
    fillEmailAndDate(e, coverage_sheet, promotionColumn, emailColumn, dateColumn, row);
  }
}

function fillEmailAndDate(e, sheet, promotionColumn, emailColumn, dateColumn, lastRow) {
  // Get the range of cells to be checked
  var range = sheet.getRange(promotionColumn + "2:" + promotionColumn + lastRow);

  // Use the onEdit trigger to detect when a cell in the promotion column is edited
  sheet.getRange(range).setOnEdit(function(e) {
    // Get the active cell
    var cell = e.source.getActiveCell();

    // Get the row and column of the active cell
    var row = cell.getRow();
    var col = cell.getColumn();

    // If the active cell is in the promotion column
    if (col == promotionColumn) {
      // Get the email and date columns for the active row
      var emailCell = sheet.getRange(emailColumn + row);
      var dateCell = sheet.getRange(dateColumn + row);

      // Get the user's email address from the email column
      var email = Session.getActiveUser().getEmail();

      // Fill in the email and date cells with the user's email address and the current date
      emailCell.setValue(email);
      dateCell.setValue(new Date());
    }
  });
}
function getNumber(letter) {
  // Make sure letter is uppercase
  letter = letter.toUpperCase();
  // Convert letter to a character code and return the corresponding number
  return letter.charCodeAt(0) - 64;
}


问:
av::av_encode_video produces blurred video from crisp files
I am using the av::av_encode_video() function to produce a .mp4 video from png files, as in this answer. I pay special attention for the png files to be perfectly crisp, i.e. I plot matrices to png with exactly the same dimensions, so that every matrix cell maps to one cell in the png. Here is code to illustrate what I mean:

```<code>library(av)

n.times <- 24*10
n.row <- 50
n.col <- 26

out.dir <- "/Users/Abdirizak/Documents/some/directory/"

for (i in 1:n.times) {

   current.mat <- matrix(data = rnorm(n.row*n.col), nrow = n.row, ncol = n.col)

   setwd(out.dir)
   png(filename = paste0(i, ".png"), width = n.row, height = n.col)

   par(mar = rep(0,4))
   image(current.mat)

   dev.off()

}

setwd(out.dir)
png.files <- paste0(out.dir, list.files(pattern = ".png$"))

av::av_encode_video(input = png.files, output = "000.mp4", framerate = 24)
</code>```

Now, even though my input .png files are perfectly crisp, the output .mp4 video is blurry. How can I prevent that from happening? I.e. how can I get a perfectly crisp video? (I am aware that this will likely inflate the file size of the .mp4 file)

I already digged a bit into the vfilter argument of av_encode_video() and the underlying ffmpeg filter graphs on here, but could not yet really get the hang on it.

I am looking at the .mp4 file through QuickTime Player on MacOS Ventura 13.0.1, and using R version 4.2.2 through RStudio 2022.12.0.353

Edit 9.1.2023:

To further clarify, here is an example screenshot of a png image (not the original png file because that one appears too small here):

As I said, a perfectly crisp image.

On the other hand, a screenshot of the .mp4 movie looks like this:

Somewhat unsatisfactory. Any suggestions are welcome.

Body:
I am using the av::av_encode_video() function to produce a .mp4 video from png files, as in this answer. I pay special attention for the png files to be perfectly crisp, i.e. I plot matrices to png with exactly the same dimensions, so that every matrix cell maps to one cell in the png. Here is code to illustrate what I mean:

library(av)

n.times <- 24*10
n.row <- 50
n.col <- 26

out.dir <- "/Users/Abdirizak/Documents/some/directory/"

for (i in 1:n.times) {

   current.mat <- matrix(data = rnorm(n.row*n.col), nrow = n.row, ncol = n.col)

   setwd(out.dir)
   png(filename = paste0(i, ".png"), width = n.row, height = n.col)

   par(mar = rep(0,4))
   image(current.mat)

   dev.off()

}

setwd(out.dir)
png.files <- paste0(out.dir, list.files(pattern = ".png$"))

av::av_encode_video(input = png.files, output = "000.mp4", framerate = 24)

Now, even though my input .png files are perfectly crisp, the output .mp4 video is blurry. How can I prevent that from happening? I.e. how can I get a perfectly crisp video? (I am aware that this will likely inflate the file size of the .mp4 file)

I already digged a bit into the vfilter argument of av_encode_video() and the underlying ffmpeg filter graphs on here, but could not yet really get the hang on it.

I am looking at the .mp4 file through QuickTime Player on MacOS Ventura 13.0.1, and using R version 4.2.2 through RStudio 2022.12.0.353

Edit 9.1.2023:

To further clarify, here is an example screenshot of a png image (not the original png file because that one appears too small here):

As I said, a perfectly crisp image.

On the other hand, a screenshot of the .mp4 movie looks like this:

Somewhat unsatisfactory. Any suggestions are welcome.


问:
Vuetify nested v-menu, when submenu opens parent menu closes
I have nested menus in Vuetify. They are opened via hover (not via click). And when a submenu has hovered, because the mouse leaves the parent menu, the whole menu closes.

https://ibb.co/xYH0ZxT

So I need to implement this: As long as the mouse stays in any of the submenus the whole menu should remain open. As soon as the mouse leaves the menu area the menu should be closed.


问:
when I try to get data from prisma on a dynamic page, I get an error
I am creating a test website next js 13 and trying to deploy it using docker. Everything is fine in development mode, but when I use docker, I get an error. I noticed that in normal pages I can easily get data from the database, but when I try to get them in dynamic pages, I immediately get an error

here is a code

dynamic page

```<code>export default async function TypePage({ params }){

    const { type } = params
    let personality = await getTypeByName(type)
    let users = await getUsers()
    let comments = await getComments(type)
    let likes = await getLikes()
    likes = likes.likes
    users = users.users
    comments = comments.comments

    const slugPath = `./posts/${type}.md`
    let content1
    try {
        const fileContents = fs.readFileSync(slugPath, 'utf8')
        let { data: frontmatter, content } = matter(fileContents)
        console.log(personality)
        content1 = md().render(content)
    } catch (error) {
        console.log( 'ERROR IN MD' ,error)
        content1 = undefined
    }

    let color

    if (/NT/.test(personality.name)) {
        color = '#9075A0'
    }

    if (/NF/.test(personality.name)) {
        color = '#738D57'
    }

    if (/S/.test(personality.name) && /J/.test(personality.name)) {
        color = '#51A9AB'
    }

    if (/S/.test(personality.name) && /P/.test(personality.name)) {
        color = '#CCAD14'
    }

    return (
        <div className="type-page">
            {personality.name === undefined ? <div>undefined</div> : personality.name}
            <TypeBlock color={color} personality={personality} content={content1}/>
            <Comments comments={comments} type={type} users={users} likes={likes}/>
        </div>
    )
}
</code>```

prisma

```<code>export async function getTypeByName(typeName) {
    try {
        const type = await prisma.type.findUnique({
            where: {
                name: typeName.toString()
            }
        })
        return type
    }
    catch (error) {
        console.log('ERROR IN GETTYPEBYNAME' ,error)
    }
}
</code>```
```<code>
model Type {
  id String @id @default(uuid())
  name String
  body String
  img String
  @@unique([name])
}
</code>```

dockerfile

```<code># Install dependencies only when needed
FROM node:18-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN npm i

# RUN npx prisma migrate deploy
RUN npx prisma generate
# RUN npm install next-auth @prisma/client @next-auth/prisma-adapter
# RUN npx prisma db pull

RUN npm run build --prod
# If using npm comment out above and use below instead
# RUN npm run build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder /app/posts ./posts

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]
</code>```

error

```<code>ERROR IN GETTYPEBYNAME PrismaClientKnownRequestError:
Invalid `prisma.type.findUnique()` invocation:

The table `main.Type` does not exist in the current database.
    at RequestHandler.handleRequestError (/app/node_modules/@prisma/client/runtime/index.js:35024:13)
    at RequestHandler.handleAndLogRequestError (/app/node_modules/@prisma/client/runtime/index.js:34996:12)
    at RequestHandler.request (/app/node_modules/@prisma/client/runtime/index.js:34991:12)
    at async PrismaClient._request (/app/node_modules/@prisma/client/runtime/index.js:36082:16)
    at async getTypeByName (/app/.next/server/chunks/719.js:43:22)
    at async TypePage (/app/.next/server/app/type/[type]/page.js:783:23) {
  code: 'P2021',
  clientVersion: '4.8.1',
  meta: { table: 'main.Type' },
  batchRequestIdx: undefined
}
undefined
TypeError: Cannot read properties of undefined (reading 'name')
    at TypePage (/app/.next/server/app/type/[type]/page.js:809:31)
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '3508705048'
}
</code>```

I spent two days to solve the problem, but in the end I didn't find anything

I tried to get data from different pages and everything was fine everywhere except for dynamic ones, I think the problem is in next js 13 because everything seems to be fine with docker and prism

Can someone help me please, what am i supposed to do??

Body:
I am creating a test website next js 13 and trying to deploy it using docker. Everything is fine in development mode, but when I use docker, I get an error. I noticed that in normal pages I can easily get data from the database, but when I try to get them in dynamic pages, I immediately get an error

here is a code

dynamic page

export default async function TypePage({ params }){

    const { type } = params
    let personality = await getTypeByName(type)
    let users = await getUsers()
    let comments = await getComments(type)
    let likes = await getLikes()
    likes = likes.likes
    users = users.users
    comments = comments.comments

    const slugPath = `./posts/${type}.md`
    let content1
    try {
        const fileContents = fs.readFileSync(slugPath, 'utf8')
        let { data: frontmatter, content } = matter(fileContents)
        console.log(personality)
        content1 = md().render(content)
    } catch (error) {
        console.log( 'ERROR IN MD' ,error)
        content1 = undefined
    }

    let color

    if (/NT/.test(personality.name)) {
        color = '#9075A0'
    }

    if (/NF/.test(personality.name)) {
        color = '#738D57'
    }

    if (/S/.test(personality.name) && /J/.test(personality.name)) {
        color = '#51A9AB'
    }

    if (/S/.test(personality.name) && /P/.test(personality.name)) {
        color = '#CCAD14'
    }

    return (

            {personality.name === undefined ?
undefined
 : personality.name}
            <TypeBlock color={color} personality={personality} content={content1}/>
            <Comments comments={comments} type={type} users={users} likes={likes}/>

    )
}

prisma

export async function getTypeByName(typeName) {
    try {
        const type = await prisma.type.findUnique({
            where: {
                name: typeName.toString()
            }
        })
        return type
    }
    catch (error) {
        console.log('ERROR IN GETTYPEBYNAME' ,error)
    }
}

model Type {
  id String @id @default(uuid())
  name String
  body String
  img String
  @@unique([name])
}

dockerfile

# Install dependencies only when needed
FROM node:18-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN npm i

# RUN npx prisma migrate deploy
RUN npx prisma generate
# RUN npm install next-auth @prisma/client @next-auth/prisma-adapter
# RUN npx prisma db pull

RUN npm run build --prod
# If using npm comment out above and use below instead
# RUN npm run build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder /app/posts ./posts

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]

error

ERROR IN GETTYPEBYNAME PrismaClientKnownRequestError:
Invalid `prisma.type.findUnique()` invocation:

The table `main.Type` does not exist in the current database.
    at RequestHandler.handleRequestError (/app/node_modules/@prisma/client/runtime/index.js:35024:13)
    at RequestHandler.handleAndLogRequestError (/app/node_modules/@prisma/client/runtime/index.js:34996:12)
    at RequestHandler.request (/app/node_modules/@prisma/client/runtime/index.js:34991:12)
    at async PrismaClient._request (/app/node_modules/@prisma/client/runtime/index.js:36082:16)
    at async getTypeByName (/app/.next/server/chunks/719.js:43:22)
    at async TypePage (/app/.next/server/app/type/[type]/page.js:783:23) {
  code: 'P2021',
  clientVersion: '4.8.1',
  meta: { table: 'main.Type' },
  batchRequestIdx: undefined
}
undefined
TypeError: Cannot read properties of undefined (reading 'name')
    at TypePage (/app/.next/server/app/type/[type]/page.js:809:31)
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '3508705048'
}

I spent two days to solve the problem, but in the end I didn't find anything

I tried to get data from different pages and everything was fine everywhere except for dynamic ones, I think the problem is in next js 13 because everything seems to be fine with docker and prism

Can someone help me please, what am i supposed to do??


问:
an error about ffmpeg：maybe incorrect parameters such as bit_rate, rate, width or height？
```<code>subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '300x300', '-pix_fmt', 'rgba', '-r', '20', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-y', './save/humanml_trans_enc_512/samples_humanml_trans_enc_512_000200000_seed10/sample00_rep00.mp4']' returned non-zero exit status 1.
</code>```

this is the error when I running a python script:

```<code>Traceback (most recent call last):
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/rob/motion-diffusion-model/sample/generate.py", line 256, in <module>
    main()
  File "/home/rob/motion-diffusion-model/sample/generate.py", line 189, in main
    plot_3d_motion(animation_save_path, skeleton, motion, dataset=args.dataset, title=caption, fps=fps)
  File "/home/rob/motion-diffusion-model/data_loaders/humanml/utils/plot_script.py", line 128, in plot_3d_motion
    ani.save(save_path, fps=fps)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 1156, in save
    writer.grab_frame(**savefig_kwargs)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 232, in saving
    self.finish()
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 367, in finish
    self.cleanup()
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 411, in cleanup
    self._proc.returncode, self._proc.args, out, err)
subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '300x300', '-pix_fmt', 'rgba', '-r', '20', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-y', './save/humanml_trans_enc_512/samples_humanml_trans_enc_512_000200000_seed10/sample00_rep00.mp4']' returned non-zero exit status 1.
</code>```

Thanks for you help very much!!!

I tried to run the command alone, then for a long time the program did not return, and after using ctrl+c it reported the following error：

```<code>[libopenh264 @ 0x555582eec100] Incorrect library version loaded
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
</code>```

Body:
subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '300x300', '-pix_fmt', 'rgba', '-r', '20', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-y', './save/humanml_trans_enc_512/samples_humanml_trans_enc_512_000200000_seed10/sample00_rep00.mp4']' returned non-zero exit status 1.

this is the error when I running a python script:

Traceback (most recent call last):
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/rob/motion-diffusion-model/sample/generate.py", line 256, in <module>
    main()
  File "/home/rob/motion-diffusion-model/sample/generate.py", line 189, in main
    plot_3d_motion(animation_save_path, skeleton, motion, dataset=args.dataset, title=caption, fps=fps)
  File "/home/rob/motion-diffusion-model/data_loaders/humanml/utils/plot_script.py", line 128, in plot_3d_motion
    ani.save(save_path, fps=fps)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 1156, in save
    writer.grab_frame(**savefig_kwargs)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 232, in saving
    self.finish()
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 367, in finish
    self.cleanup()
  File "/home/rob/anaconda3/envs/mdm/lib/python3.7/site-packages/matplotlib/animation.py", line 411, in cleanup
    self._proc.returncode, self._proc.args, out, err)
subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '300x300', '-pix_fmt', 'rgba', '-r', '20', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-y', './save/humanml_trans_enc_512/samples_humanml_trans_enc_512_000200000_seed10/sample00_rep00.mp4']' returned non-zero exit status 1.

Thanks for you help very much!!!

I tried to run the command alone, then for a long time the program did not return, and after using ctrl+c it reported the following error：

[libopenh264 @ 0x555582eec100] Incorrect library version loaded
Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height


问:
I have nodejs project, which allows users to upload photos. How can I host them. I need an example
Users should upload photos.
They should be hosted somewhere else.
Only the photo hosting, no photo transformation needed.
What should I use, and how to use it.

Cloudinary.
It works, but I need a very simple solution


问:
Selenium: web application dead and not running launched with Selenium using C#
I am new to automation, I just learned about Selenium for 3 days and built a simple C# console application with Selenium which trying to automate "sell" request on a trading website.

I noticed when I login the trading website with normal Chrome, the site is working as normal. But when I launch it with my C# console app, it seems like the trading website is not functioning as normal, seems dead.

Here I attached with both developer console picture as reference.

Normal Chrome browser:
enter image description here

Launched with C# console app:
enter image description here

Am I missing any part of my code, and cause the launched Chrome is being "locked".

Please help me

below is my code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

namespace ii.tfxBot
{
    class Program
    {

        static void Main(string[] args)
        {
            string ExecuteUrl = "https://tex.tfxi.com/#/exchange/tfx_usdt";

            Console.WriteLine("test case started ");
            //create the reference for the browser
            //new DriverManager().SetUpDriver(new ChromeConfig());

            var ccOptions = new ChromeOptions();
            ccOptions.LeaveBrowserRunning = true;

            //ccOptions.AttachToEdgeChrome = true;
            //change the path accordingly
            //ccOptions.EdgeExecutablePath = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe";
            new DriverManager().SetUpDriver(new ChromeConfig());

            var driver = new ChromeDriver(@"C:\WebDriver\bin", ccOptions);

            // navigate to URL
            driver.Navigate().GoToUrl("https://tex.tfxi.com/#/login");
            Thread.Sleep(2000);
            // identify the Google search text box
            //IWebElement ele = driver.FindElement(By.Name("q"));
            ////enter the value in the google search text box
            //ele.SendKeys("javatpoint tutorials");
            //Thread.Sleep(2000);
            ////identify the google search button
            //IWebElement ele1 = driver.FindElement(By.Name("btnK"));
            //// click on the Google search button
            //ele1.Click();
            bool isUrl = false;
            while (isUrl == false)
            {
                if (driver.Url == ExecuteUrl)
                {
                    StartExecution(driver);
                    break;
                }
                Console.WriteLine("Execute Url not matched... try again in 1 second");
                Thread.Sleep(5000);
            }

            //close the browser
            //driver.Close();
            Thread.Sleep(8000000);
            Console.WriteLine("test case ended ");

        }

        private static void StartExecution(ChromeDriver driver)
        {

            var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));
            int i = 0;

            foreach (var inputElement in inputElements)
            {
                Console.WriteLine("input count " + i.ToString() + " : " + inputElement.GetAttribute("placeholder").ToString());

                string plText = inputElement.GetAttribute("placeholder").ToString();

                if (plText == "出售數量")
                {
                    Console.WriteLine("found the input number: " + i.ToString());

                }
                else
                {
                    //inputElement.SendKeys("28000");
                }
                i++;
            }

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));
            IWebElement divLimit;
            bool found = false;
            while (found == false)
            {
                //divLimit = driver.FindElement(By.ClassName("bd bd_limited"));
                //divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("bd bd_limited")));
                divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".bd.bd_limited"))); ;

                if (divLimit != null)
                {
                    Console.WriteLine("item found, proceed to get selling price!");
                    GetSellingPrice(divLimit);
                    break;
                }

                Console.WriteLine("item NOT found!");
                Thread.Sleep(300);

            }

            int tfxBal = GetTfxBalance(driver);
            WaitforElement(driver, By.CssSelector(".mask2"), tfxBal);

        }

        public static int GetTfxBalance(ChromeDriver driver)
        {
            int TfxBal = 0;
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));

            IWebElement divHdLogin;
            divHdLogin = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".hd.hd_login")));

            //(IWebElement)driver.FindElements(By.CssSelector(".hd.hd_login"));

            var targetKeys = divHdLogin.FindElements(By.TagName("span"));

            Console.WriteLine("targetKeys 0 : " + targetKeys[0].Text);
            Console.WriteLine("targetKeys 1 : " + targetKeys[1].Text);
            Console.WriteLine("targetKeys 2 : " + targetKeys[2].Text);
            decimal o = Convert.ToDecimal(targetKeys[1].Text);

            if (targetKeys[1].Text.Contains("."))
            {
                var a = targetKeys[1].Text.Split('.');
                TfxBal = Convert.ToInt32(a[0]);
            }
            else
            {
                TfxBal = Convert.ToInt32(targetKeys[1].Text);
            }
            return TfxBal;
        }

        public static void GetSellingPrice(IWebElement divLimit)
        {
            IWebElement divFormContent = divLimit.FindElement(By.CssSelector(".ivu-form-item-content"));
            IWebElement ipSellPrice = divFormContent.FindElement(By.CssSelector(".ivu-input.ivu-input-default"));
            Console.WriteLine(ipSellPrice.GetAttribute("value"));
        }

        public static bool Elexists(By by, WebDriver driver)
        {
            try
            {
                driver.FindElement(by);
                IWebElement divPopup = driver.FindElement(by);
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));

                // textLeft countNumber
                IWebElement divcountNumber;
                divcountNumber = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".textLeft.countNumber")));

                //Console.WriteLine("count number: " + divcountNumber.Text);
                string popupStyle = divPopup.GetAttribute("style");
                //Console.WriteLine("div Popup Style : " + popupStyle);
                if (popupStyle == "display: none;")
                {
                    //Console.WriteLine("No Pop up..");
                    return false;
                }
                else
                {
                    Console.WriteLine("Pop up display has changed!");
                    return true;
                }
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

        public static void WaitforElement(WebDriver driver, By by, int tfxBalance = 0)
        {
            // waitforMin = 2 hours
            int waitforMin = 60 * 1000 * 2 * 2 * 2;

            for (int i = 0; i < waitforMin; i++)
            {
                System.Threading.Thread.Sleep(250);
                if (Elexists(by, driver))
                {
                    Console.WriteLine("Pop up appears! Performing selling now");

                    var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));

                    IWebElement SellBtn = driver.FindElement(By.CssSelector(".bg-red.ivu-btn.ivu-btn-default.ivu-btn-long"));
                    foreach (var inputElement in inputElements)
                    {

                        string plText = inputElement.GetAttribute("placeholder").ToString();

                        if (plText == "出售數量")
                        {
                            Console.WriteLine("found the input box");
                            inputElement.SendKeys("28000");
                            SellBtn.Click();
                        }
                    }
                    break;
                }
                Console.Write(".");
            }
        }

        public static void SellTfx()
        {
            //
        }
    }
}

</code>```

I am expecting some solution to fix my code

Body:
I am new to automation, I just learned about Selenium for 3 days and built a simple C# console application with Selenium which trying to automate "sell" request on a trading website.

I noticed when I login the trading website with normal Chrome, the site is working as normal. But when I launch it with my C# console app, it seems like the trading website is not functioning as normal, seems dead.

Here I attached with both developer console picture as reference.

Normal Chrome browser:
enter image description here

Launched with C# console app:
enter image description here

Am I missing any part of my code, and cause the launched Chrome is being "locked".

Please help me

below is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;

namespace ii.tfxBot
{
    class Program
    {

        static void Main(string[] args)
        {
            string ExecuteUrl = "https://tex.tfxi.com/#/exchange/tfx_usdt";

            Console.WriteLine("test case started ");
            //create the reference for the browser
            //new DriverManager().SetUpDriver(new ChromeConfig());

            var ccOptions = new ChromeOptions();
            ccOptions.LeaveBrowserRunning = true;

            //ccOptions.AttachToEdgeChrome = true;
            //change the path accordingly
            //ccOptions.EdgeExecutablePath = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe";
            new DriverManager().SetUpDriver(new ChromeConfig());

            var driver = new ChromeDriver(@"C:\WebDriver\bin", ccOptions);

            // navigate to URL
            driver.Navigate().GoToUrl("https://tex.tfxi.com/#/login");
            Thread.Sleep(2000);
            // identify the Google search text box
            //IWebElement ele = driver.FindElement(By.Name("q"));
            ////enter the value in the google search text box
            //ele.SendKeys("javatpoint tutorials");
            //Thread.Sleep(2000);
            ////identify the google search button
            //IWebElement ele1 = driver.FindElement(By.Name("btnK"));
            //// click on the Google search button
            //ele1.Click();
            bool isUrl = false;
            while (isUrl == false)
            {
                if (driver.Url == ExecuteUrl)
                {
                    StartExecution(driver);
                    break;
                }
                Console.WriteLine("Execute Url not matched... try again in 1 second");
                Thread.Sleep(5000);
            }

            //close the browser
            //driver.Close();
            Thread.Sleep(8000000);
            Console.WriteLine("test case ended ");

        }

        private static void StartExecution(ChromeDriver driver)
        {

            var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));
            int i = 0;

            foreach (var inputElement in inputElements)
            {
                Console.WriteLine("input count " + i.ToString() + " : " + inputElement.GetAttribute("placeholder").ToString());

                string plText = inputElement.GetAttribute("placeholder").ToString();

                if (plText == "出售數量")
                {
                    Console.WriteLine("found the input number: " + i.ToString());

                }
                else
                {
                    //inputElement.SendKeys("28000");
                }
                i++;
            }

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));
            IWebElement divLimit;
            bool found = false;
            while (found == false)
            {
                //divLimit = driver.FindElement(By.ClassName("bd bd_limited"));
                //divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("bd bd_limited")));
                divLimit = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".bd.bd_limited"))); ;

                if (divLimit != null)
                {
                    Console.WriteLine("item found, proceed to get selling price!");
                    GetSellingPrice(divLimit);
                    break;
                }

                Console.WriteLine("item NOT found!");
                Thread.Sleep(300);

            }

            int tfxBal = GetTfxBalance(driver);
            WaitforElement(driver, By.CssSelector(".mask2"), tfxBal);

        }

        public static int GetTfxBalance(ChromeDriver driver)
        {
            int TfxBal = 0;
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));

            IWebElement divHdLogin;
            divHdLogin = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".hd.hd_login")));

            //(IWebElement)driver.FindElements(By.CssSelector(".hd.hd_login"));

            var targetKeys = divHdLogin.FindElements(By.TagName("span"));

            Console.WriteLine("targetKeys 0 : " + targetKeys[0].Text);
            Console.WriteLine("targetKeys 1 : " + targetKeys[1].Text);
            Console.WriteLine("targetKeys 2 : " + targetKeys[2].Text);
            decimal o = Convert.ToDecimal(targetKeys[1].Text);

            if (targetKeys[1].Text.Contains("."))
            {
                var a = targetKeys[1].Text.Split('.');
                TfxBal = Convert.ToInt32(a[0]);
            }
            else
            {
                TfxBal = Convert.ToInt32(targetKeys[1].Text);
            }
            return TfxBal;
        }

        public static void GetSellingPrice(IWebElement divLimit)
        {
            IWebElement divFormContent = divLimit.FindElement(By.CssSelector(".ivu-form-item-content"));
            IWebElement ipSellPrice = divFormContent.FindElement(By.CssSelector(".ivu-input.ivu-input-default"));
            Console.WriteLine(ipSellPrice.GetAttribute("value"));
        }

        public static bool Elexists(By by, WebDriver driver)
        {
            try
            {
                driver.FindElement(by);
                IWebElement divPopup = driver.FindElement(by);
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(300));

                // textLeft countNumber
                IWebElement divcountNumber;
                divcountNumber = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(".textLeft.countNumber")));

                //Console.WriteLine("count number: " + divcountNumber.Text);
                string popupStyle = divPopup.GetAttribute("style");
                //Console.WriteLine("div Popup Style : " + popupStyle);
                if (popupStyle == "display: none;")
                {
                    //Console.WriteLine("No Pop up..");
                    return false;
                }
                else
                {
                    Console.WriteLine("Pop up display has changed!");
                    return true;
                }
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

        public static void WaitforElement(WebDriver driver, By by, int tfxBalance = 0)
        {
            // waitforMin = 2 hours
            int waitforMin = 60 * 1000 * 2 * 2 * 2;

            for (int i = 0; i < waitforMin; i++)
            {
                System.Threading.Thread.Sleep(250);
                if (Elexists(by, driver))
                {
                    Console.WriteLine("Pop up appears! Performing selling now");

                    var inputElements = driver.FindElements(By.CssSelector(".ivu-input.ivu-input-default"));

                    IWebElement SellBtn = driver.FindElement(By.CssSelector(".bg-red.ivu-btn.ivu-btn-default.ivu-btn-long"));
                    foreach (var inputElement in inputElements)
                    {

                        string plText = inputElement.GetAttribute("placeholder").ToString();

                        if (plText == "出售數量")
                        {
                            Console.WriteLine("found the input box");
                            inputElement.SendKeys("28000");
                            SellBtn.Click();
                        }
                    }
                    break;
                }
                Console.Write(".");
            }
        }

        public static void SellTfx()
        {
            //
        }
    }
}

I am expecting some solution to fix my code


问:
Making bootstrap5 scrip logo appear in the centre on mobile
I have coded a very basic blog script it's nothing elaborate but does the job (built-in bootstrap 5 & PHP), everything is working as it should in desktop and mobile view, the only small thing I'm not sure about is, when I view the site in mobile view the image (logo) appears to the left-hand side (while in mobile view), I think it would look better in the centre.

Image of what I see:

The script is located at: https://www.the-golfer-guys.com/

It's not a big deal, but I'm not sure the best way to make it appear in the centre (while only in mobile view).

my navbar code:

```<code><nav class="navbar navbar-expand-lg border-bottom navbar-white bg-white padding-bottom" id="mainNav">

    <div class="container-fluid">

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
            <i class="fas fa-bars"></i>
        </button>

        <!-- mobile -->
        <div class="collapse navbar-collapse w-100 justify-content-center" id="collapsibleNavbar">

            <a class="navbar-brand" href="<?= urlFull(); ?>"><img src="<?= urlFull(); ?><?= getHeaderImage(); ?>" alt="<?= urlFull(); ?>"></a>

            <ul class="nav nav-pills nav-fill ms-auto">
                <li class="nav-item"><a href="<?= urlFull(); ?>" class="nav-link <?= ($_SERVER['PHP_SELF'] == "/index.php") ? "active" : ""; ?>">Home</a></li>

                <?php $pages = DB::getInstance()->select("SELECT * FROM `pages`"); ?>
                <?php foreach($pages as $page) { ?>

                <li class="nav-item"><a href="<?= urlFull(); ?>page.php?page=<?= $page['page_slug']; ?>" class="nav-link <?= ($_SERVER['REQUEST_URI'] == "/page.php?page={$page['page_slug']}") ? "active" : ""; ?>"><?= $page['page_name']; ?></a></li>

                <?php } ?>

                <li class="nav-item"><a href="<?= urlFull(); ?>contact.php" class="nav-link <?= ($_SERVER['PHP_SELF'] == "/contact.php") ? "active" : ""; ?>">Contact</a></li>
            </ul>

            <ul class="nav navbar-nav ms-auto" style="padding-top: 10px;">
                <li>
                    <form class="d-flex" action="<?= urlFull(); ?>search.php" method="get">
                        <input class="form-control me-2" type="search" name="s" placeholder="Search ..." aria-label="Search" required>
                        <button type="submit" class="btn btn-success"><i class="fas fa-search"></i></button>
                    </form>
                </li>
            </ul>

        </div>

    </div>

</nav>
</code>```

Any advice or help would be appreciated, it's more my design OCD than anything.

Body:
I have coded a very basic blog script it's nothing elaborate but does the job (built-in bootstrap 5 & PHP), everything is working as it should in desktop and mobile view, the only small thing I'm not sure about is, when I view the site in mobile view the image (logo) appears to the left-hand side (while in mobile view), I think it would look better in the centre.

Image of what I see:

The script is located at: https://www.the-golfer-guys.com/

It's not a big deal, but I'm not sure the best way to make it appear in the centre (while only in mobile view).

my navbar code:

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">

        </button>

            <a class="navbar-brand" href="<?= urlFull(); ?>"><img src="<?= urlFull(); ?><?= getHeaderImage(); ?>" alt="<?= urlFull(); ?>">

<a href="<?= urlFull(); ?>" class="nav-link <?= ($_SERVER['PHP_SELF'] == "/index.php") ? "active" : ""; ?>">Home

                <?php $pages = DB::getInstance()->select("SELECT * FROM `pages`"); ?>
                <?php foreach($pages as $page) { ?>

<a href="<?= urlFull(); ?>page.php?page=<?= $page['page_slug']; ?>" class="nav-link <?= ($_SERVER['REQUEST_URI'] == "/page.php?page={$page['page_slug']}") ? "active" : ""; ?>"><?= $page['page_name']; ?>

                <?php } ?>

<a href="<?= urlFull(); ?>contact.php" class="nav-link <?= ($_SERVER['PHP_SELF'] == "/contact.php") ? "active" : ""; ?>">Contact

                    <form class="d-flex" action="<?= urlFull(); ?>search.php" method="get">
                        <input class="form-control me-2" type="search" name="s" placeholder="Search ..." aria-label="Search" required>
                        <button type="submit" class="btn btn-success"></button>
                    </form>

Any advice or help would be appreciated, it's more my design OCD than anything.


问:
Python Import Metatrader 5 crashes
On Anaconda3 shell I have installed Metatrader 5 package using pipenv. My Python script does an import Metatrader 5; and immediately the program crashes (as seen from pdb step line by line). Windows Event log has the below, apparently pointing to some math libaries:

```<code>- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Application Error" />
  <EventID Qualifiers="0">1000</EventID>
  <Version>0</Version>
  <Level>2</Level>
  <Task>100</Task>
  <Opcode>0</Opcode>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2023-01-07T08:41:12.7808684Z" />
  <EventRecordID>2741</EventRecordID>
  <Correlation />
  <Execution ProcessID="0" ThreadID="0" />
  <Channel>Application</Channel>
  <Computer>DESKTOP-FTG6RSN</Computer>
  <Security />
  </System>
- <EventData>
  <Data>python.exe</Data>
  <Data>3.9.12150.1013</Data>
  <Data>624ac9fe</Data>
  <Data>_multiarray_umath.cp39-win32.pyd</Data>
  <Data>0.0.0.0</Data>
  <Data>63a91ba6</Data>
  <Data>c000001d</Data>
  <Data>000269c9</Data>
  <Data>2660</Data>
  <Data>01d92273cb431db6</Data>
  <Data>C:\Users\acer\anaconda3\python.exe</Data>
  <Data>C:\Users\acer\anaconda3\lib\site-packages\numpy\core\_multiarray_umath.cp39-win32.pyd</Data>
  <Data>7729512c-4535-4138-a1e7-770ed4ec6ef8</Data>
  <Data />
  <Data />
  </EventData>
  </Event>
</code>```

I have Metatrader5 package 5.0.37, Python 3.9.12 and Windows 10 32 bit.
Any help on how to resolve this is much appreciated and please do so before I shoot myself.

Title: Python Import Metatrader 5 crashes

Body:
On Anaconda3 shell I have installed Metatrader 5 package using pipenv. My Python script does an import Metatrader 5; and immediately the program crashes (as seen from pdb step line by line). Windows Event log has the below, apparently pointing to some math libaries:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="Application Error" />
  <EventID Qualifiers="0">1000</EventID>
  <Version>0</Version>
  <Level>2</Level>
  <Task>100</Task>
  <Opcode>0</Opcode>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2023-01-07T08:41:12.7808684Z" />
  <EventRecordID>2741</EventRecordID>
  <Correlation />
  <Execution ProcessID="0" ThreadID="0" />
  <Channel>Application</Channel>
  <Computer>DESKTOP-FTG6RSN</Computer>
  <Security />
  </System>
- <EventData>
  <Data>python.exe</Data>
  <Data>3.9.12150.1013</Data>
  <Data>624ac9fe</Data>
  <Data>_multiarray_umath.cp39-win32.pyd</Data>
  <Data>0.0.0.0</Data>
  <Data>63a91ba6</Data>
  <Data>c000001d</Data>
  <Data>000269c9</Data>
  <Data>2660</Data>
  <Data>01d92273cb431db6</Data>
  <Data>C:\Users\acer\anaconda3\python.exe</Data>
  <Data>C:\Users\acer\anaconda3\lib\site-packages\numpy\core\_multiarray_umath.cp39-win32.pyd</Data>
  <Data>7729512c-4535-4138-a1e7-770ed4ec6ef8</Data>
  <Data />
  <Data />
  </EventData>
  </Event>

I have Metatrader5 package 5.0.37, Python 3.9.12 and Windows 10 32 bit.
Any help on how to resolve this is much appreciated and please do so before I shoot myself.


问:
How can I disable the bodyparser for one API route method, but enable it for another?
As the question states, how can I disable the bodyparser for one API route method, but enable it for another?

Here's part of my API route:

```<code>const handler = async (req, res) => {
    if (req.method === "POST") {
            ...
    } else if (req.method === "DELETE") {
            ...
    } else {
        res.status(405).json({
            data: null,
            error: "Method not allowed."
        });
        return;
    };
};

export const config = {
    api: {
        bodyParser: false,
    },
};

export default handler;
</code>```

You'll see at the bottom of the code block that the body parser applies to both methods at the moment. I need to use the body parser for the DELETE method so that I can access a variable set within the body, but it needs to be disabled for the POST method (handling of multipart forms for image uploads).

I've thought about splitting these into two different files as follows:

Current setup:

/api/advert/[advertId]/image/index.jsx

Potential setup:

/api/advert/[advertId]/image/post.jsx

/api/advert/[advertId]/image/delete.jsx

While this would work, it would deviate the structure from the rest of my code and so I was wondering if there is a cleaner way to achieve this? (Preferably without the use of additional middleware)

Thanks

Body:
As the question states, how can I disable the bodyparser for one API route method, but enable it for another?

Here's part of my API route:

const handler = async (req, res) => {
    if (req.method === "POST") {
            ...
    } else if (req.method === "DELETE") {
            ...
    } else {
        res.status(405).json({
            data: null,
            error: "Method not allowed."
        });
        return;
    };
};

export const config = {
    api: {
        bodyParser: false,
    },
};

export default handler;

You'll see at the bottom of the code block that the body parser applies to both methods at the moment. I need to use the body parser for the DELETE method so that I can access a variable set within the body, but it needs to be disabled for the POST method (handling of multipart forms for image uploads).

I've thought about splitting these into two different files as follows:

Current setup:

/api/advert/[advertId]/image/index.jsx

Potential setup:

/api/advert/[advertId]/image/post.jsx

/api/advert/[advertId]/image/delete.jsx

While this would work, it would deviate the structure from the rest of my code and so I was wondering if there is a cleaner way to achieve this? (Preferably without the use of additional middleware)

Thanks


问:
Firebase console error - signInWithEmailAndPassword
Im using Firebase for my backend solution with Angular.
Im using signInWithEmailAndPassword from Firebase to log in the users.
When a non valid user tries to log in i get some nasty console errors that it seems im not able to catch. I also tried using try-catch.

AuthService:

```<code>  loginWithUserPassword(user: string, password: string): Promise<any> {
return this.afAuth.signInWithEmailAndPassword(user, password)
  .then(() => {
    return true;
  })
  .catch((err) => {});}
</code>```

The errors i get after wrong user in the console:

POST 400 webpack: zone.js:1518
https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[ApiKey]

webpack: core.mjs:9171

```<code>ERROR Error: Uncaught (in promise): FirebaseError: Firebase: The password is invalid or the user does not have a password. (auth/wrong-password).

at createErrorInternal (index-c6def6da.js:474:41)
at _fail (index-c6def6da.js:445:11)
at index-c6def6da.js:976:17
at Generator.next (<anonymous>)
at asyncGeneratorStep (asyncToGenerator.js:3:1)
at _next (asyncToGenerator.js:25:1)
at _ZoneDelegate.invoke (zone.js:372:26)
at Object.onInvoke (core.mjs:26274:33)
at _ZoneDelegate.invoke (zone.js:371:52)
at Zone.run (zone.js:134:43)
at resolvePromise (zone.js:1211:31)
at resolvePromise (zone.js:1165:17)
at zone.js:1278:17
at _ZoneDelegate.invokeTask (zone.js:406:31)
at Object.onInvokeTask (core.mjs:26261:33)
at _ZoneDelegate.invokeTask (zone.js:405:60)
at Zone.runTask (zone.js:178:47)
at drainMicroTaskQueue (zone.js:585:35)
</code>```

Body:
Im using Firebase for my backend solution with Angular.
Im using signInWithEmailAndPassword from Firebase to log in the users.
When a non valid user tries to log in i get some nasty console errors that it seems im not able to catch. I also tried using try-catch.

AuthService:

  loginWithUserPassword(user: string, password: string): Promise<any> {
return this.afAuth.signInWithEmailAndPassword(user, password)
  .then(() => {
    return true;
  })
  .catch((err) => {});}

The errors i get after wrong user in the console:

POST 400 webpack: zone.js:1518
https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[ApiKey]

webpack: core.mjs:9171

ERROR Error: Uncaught (in promise): FirebaseError: Firebase: The password is invalid or the user does not have a password. (auth/wrong-password).

at createErrorInternal (index-c6def6da.js:474:41)
at _fail (index-c6def6da.js:445:11)
at index-c6def6da.js:976:17
at Generator.next (<anonymous>)
at asyncGeneratorStep (asyncToGenerator.js:3:1)
at _next (asyncToGenerator.js:25:1)
at _ZoneDelegate.invoke (zone.js:372:26)
at Object.onInvoke (core.mjs:26274:33)
at _ZoneDelegate.invoke (zone.js:371:52)
at Zone.run (zone.js:134:43)
at resolvePromise (zone.js:1211:31)
at resolvePromise (zone.js:1165:17)
at zone.js:1278:17
at _ZoneDelegate.invokeTask (zone.js:406:31)
at Object.onInvokeTask (core.mjs:26261:33)
at _ZoneDelegate.invokeTask (zone.js:405:60)
at Zone.runTask (zone.js:178:47)
at drainMicroTaskQueue (zone.js:585:35)