问:
Why .last()/.first() change the order of the ordered and distinct queryset?
I have query like this - it needs to filter values by date and in case we have priorities on dates (x), we are setting up proper order which data we need.

```<code>def filterX(self, order_list=[3,2,1], *args, **kwargs):
        return (
            self.get_queryset()
            .filter(*args, **kwargs)
            .order_by(
                "date",
                Case(
                    *[
                        When(x=y, then=Value(i))
                        for i, y in enumerate(order_list)
                    ],
                    default=None,
                ).asc(),
            )
            .distinct("date")
        )

</code>```

So I need only one item per one date with highest order given. And it works perfectly. From table 1 I have table 2 ->

Table 1.

ID
DATE
PRIORITY

1
2022/11/1
1

2
2022/11/1
2

3
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
1

6
2022/11/3
2

Table 2.

ID
DATE
PRIORITY

1
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
2

But if I use this query for one date I get queryset with one item (which I need), but after .last the item is actually changed.

Any advices?

Body:
I have query like this - it needs to filter values by date and in case we have priorities on dates (x), we are setting up proper order which data we need.

def filterX(self, order_list=[3,2,1], *args, **kwargs):
        return (
            self.get_queryset()
            .filter(*args, **kwargs)
            .order_by(
                "date",
                Case(
                    *[
                        When(x=y, then=Value(i))
                        for i, y in enumerate(order_list)
                    ],
                    default=None,
                ).asc(),
            )
            .distinct("date")
        )

So I need only one item per one date with highest order given. And it works perfectly. From table 1 I have table 2 ->

Table 1.

ID
DATE
PRIORITY

1
2022/11/1
1

2
2022/11/1
2

3
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
1

6
2022/11/3
2

Table 2.

ID
DATE
PRIORITY

1
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
2

But if I use this query for one date I get queryset with one item (which I need), but after .last the item is actually changed.

Any advices?


来源: stackexchange

问:
Breaking from a while loop with a character in C
I am totally new to C programming, and now, as I am writing my first program, I have encountered a problem with breaking from a while loop. Here is my code:

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

int multipl(int x, int y);

int main(){
    int x, y, result;
    char replyChar;
    while (1){
        printf("Enter two numbers to be multiplied: \n");
        printf("Number A: "); scanf("%d", &x);
        printf("\nNumber B: "); scanf("%d", &y);

        result = multipl(x, y);
        printf("\nThe product of %d and %d is %d", x, y, result);
        printf("\nDo you wish to proceed?(y/n): ");
        scanf("%c", &replyChar);
        if (replyChar == 'n'){
            printf("Exiting the program.. :)");
            break;
        }
        else{
            continue;
        }
    }
    return 0;
}

int multipl(int x, int y){
    return x * y;
}
</code>```

The problem is that after function 'multipl' returns a result and the 'Do you wish to proceed' phrase comes on, the code does not wait for receiving the replyChar, and just prints printf("Enter two numbers to be multiplied: \n");.
How can I make my code wait for the replyChar without going on further? Thanks in advance for your help!

ContentLicense: CC BY-SA 4.0

Body:
I am totally new to C programming, and now, as I am writing my first program, I have encountered a problem with breaking from a while loop. Here is my code:

#include <stdio.h>
#include <stdlib.h>

int multipl(int x, int y);

int main(){
    int x, y, result;
    char replyChar;
    while (1){
        printf("Enter two numbers to be multiplied: \n");
        printf("Number A: "); scanf("%d", &x);
        printf("\nNumber B: "); scanf("%d", &y);

        result = multipl(x, y);
        printf("\nThe product of %d and %d is %d", x, y, result);
        printf("\nDo you wish to proceed?(y/n): ");
        scanf("%c", &replyChar);
        if (replyChar == 'n'){
            printf("Exiting the program.. :)");
            break;
        }
        else{
            continue;
        }
    }
    return 0;
}

int multipl(int x, int y){
    return x * y;
}

The problem is that after function 'multipl' returns a result and the 'Do you wish to proceed' phrase comes on, the code does not wait for receiving the replyChar, and just prints printf("Enter two numbers to be multiplied: \n");.
How can I make my code wait for the replyChar without going on further? Thanks in advance for your help!


问:
Add multiple Visual Basic Powerpoint animations
Good morning everyone. I have the following problem. I've just been handed a project in Visual Basic which currently adds an animation to some shapes.

I was asked that now you can add more than one animation. I can't get this.

When trying to add a second animation, the first animation is lost

Note: I am not an expert in this language.

```<code>Private Sub AddAppearEffect()
        Try
            Dim CurrentSlide As Slide = Globals.ThisAddIn.Application.ActiveWindow.View.Slide
            Dim shapes As PowerPoint.ShapeRange = Globals.ThisAddIn.Application.ActiveWindow.Selection.ShapeRange
            Dim draw As New DrawItems
            If shapes.Count = 2 Then
                Dim Sequence As Sequence = CurrentSlide.TimeLine.InteractiveSequences.Add(1)
                Dim triggerShape As Shape = shapes(1)
                Dim targetShape As Shape = shapes(2)
                targetShape.AnimationSettings.Animate = False
                Dim variable2 As Effect = Sequence.AddTriggerEffect(targetShape, MsoAnimEffect.msoAnimEffectAppear, MsoAnimTriggerType.msoAnimTriggerOnShapeClick,
                             Sequence.triggerShape, "", MsoAnimateByLevel.msoAnimateLevelNone)
                Sequence.ConvertToAfterEffect(variable2, MsoAnimAfterEffect.msoAnimAfterEffectHideOnNextClick, 0, PpColorSchemeIndex.ppNotSchemeColor)
                MsgBox("Appear effect was added succesfully", MsgBoxStyle.Information, "CEMEX Toolkit")
            Else
                Throw New Exception("Please select two(2) shapes")
            End If

        Catch ex As Exception
            MsgBox("Please select two(2) shapes", MsgBoxStyle.Critical, "CEMEX Toolkit")
        End Try

    End Sub
</code>```

I wish I could add more animations without losing the ones I've already added

Body:
Good morning everyone. I have the following problem. I've just been handed a project in Visual Basic which currently adds an animation to some shapes.

I was asked that now you can add more than one animation. I can't get this.

When trying to add a second animation, the first animation is lost

Note: I am not an expert in this language.

Private Sub AddAppearEffect()
        Try
            Dim CurrentSlide As Slide = Globals.ThisAddIn.Application.ActiveWindow.View.Slide
            Dim shapes As PowerPoint.ShapeRange = Globals.ThisAddIn.Application.ActiveWindow.Selection.ShapeRange
            Dim draw As New DrawItems
            If shapes.Count = 2 Then
                Dim Sequence As Sequence = CurrentSlide.TimeLine.InteractiveSequences.Add(1)
                Dim triggerShape As Shape = shapes(1)
                Dim targetShape As Shape = shapes(2)
                targetShape.AnimationSettings.Animate = False
                Dim variable2 As Effect = Sequence.AddTriggerEffect(targetShape, MsoAnimEffect.msoAnimEffectAppear, MsoAnimTriggerType.msoAnimTriggerOnShapeClick,
                             Sequence.triggerShape, "", MsoAnimateByLevel.msoAnimateLevelNone)
                Sequence.ConvertToAfterEffect(variable2, MsoAnimAfterEffect.msoAnimAfterEffectHideOnNextClick, 0, PpColorSchemeIndex.ppNotSchemeColor)
                MsgBox("Appear effect was added succesfully", MsgBoxStyle.Information, "CEMEX Toolkit")
            Else
                Throw New Exception("Please select two(2) shapes")
            End If

        Catch ex As Exception
            MsgBox("Please select two(2) shapes", MsgBoxStyle.Critical, "CEMEX Toolkit")
        End Try

    End Sub

I wish I could add more animations without losing the ones I've already added


问:
how to create Live lock
can anybody help me understand what is Live lock and how to create it? I read about it but didn't quite understand how it works, how to make sure that from n-threads only n-1 threads will work at the same time? is it even possible to do in c++?

for now, I'm just reading some documents, I have not seen any actual code, it would be nice if provided with one

Title: how to create Live lock


问:
Simple GitLab parent-child pipeline example
I'm looking for a simple as easy to follow GitLab parent-child pipeline example. Single repo, single project, no dynamic. My understanding is that it would be called downstream?

We have a Gitlab pipeline that needs to be split into a parent and child in order for us to be able to click BUILD on the child to give us control of the drop schema/rename timing. Currently, we have no control on the drop schema/rename timing.

USE CASE

Parent pipeline is for spinning pod, pg_dump prod /  pg_restore to non-prod postgres so schema for refresh will be ready ahead till we wish to actually drop/rename schema.

Child pipeline will have another BUILD button that will allow us to drop former destination schema and rename so we can fully control the drop/rename schema timing.


问:
NestJS FileValidator return different error messages
I am trying to validate my uploaded file by extending the abstract FileValidator

```<code>export declare abstract class FileValidator<TValidationOptions = Record<string, any>> {
    protected readonly validationOptions: TValidationOptions;
    constructor(validationOptions: TValidationOptions);
    /**
     * Indicates if this file should be considered valid, according to the options passed in the constructor.
     * @param file the file from the request object
     */
    abstract isValid(file?: any): boolean | Promise<boolean>;
    /**
     * Builds an error message in case the validation fails.
     * @param file the file from the request object
     */
    abstract buildErrorMessage(file: any): string;
}
</code>```

Quite simply, I can create my own extended version to validate the upload file is an Excel Workbook.

```<code>import { FileValidator } from '@nestjs/common';
import { read, WorkBook } from 'xlsx';

export declare type ExcelWorkbookValidatorOptions = {
    Option1: boolean;
    Option2: number;
};

export class ExcelWorkbookValidator extends FileValidator<ExcelWorkbookValidatorOptions> {
    private ExcelData_: WorkBook;

    constructor(protected readonly validationOptions: ExcelWorkbookValidatorOptions) {
        super(validationOptions);
    }

    /**
     * Indicates if this file should be considered valid, according to the options passed in the constructor.
     * @param UploadedFile the file from the request object
     */
    public isValid(UploadedFile: Express.Multer.File): boolean | Promise<boolean> {
         if (this.validationOptions.Option1) {
             // Check something
             return false;
         }

         if (this.validationOptions.Option2) {
             // Check something else
             return false;
         }

         return true;
    }

    /**
     * Builds an error message in case the validation fails.
     * @param UploadedFile the file from the request object
     */
    public buildErrorMessage(UploadedFile: Express.Multer.File): string {
        return `${UploadedFile.originalname} is not an Excel Workbook`;
    }

}
</code>```

The buildMessage() gets the original file as a parameter.  I do not know how I can indicate what failed in the Option1 and Option2 check, so that I could change the response message to indicate the issue.

As both the isValid() and buildMessage() get the uploaded file (file: any), does this mean that both functions need the logic to determine if the file is good or bad for custom messages?

I would assume I can do all different functions, one for each Option check, and if it returns false, then the isValid returns false, and the buildMessage would return the text I want to send to indicate the actual issue (Option1 or Option2 failed)?

```<code>    /**
     * Builds an error message in case the validation fails.
     * @param UploadedFile the file from the request object
     */
    public buildErrorMessage(UploadedFile: Express.Multer.File): string {
        let ErrorText: string = '';
        if (! this.IsValidExcelMimeType(UploadedFile.mimetype)) {
            ErrorText = `invalid mimetype ${UploadedFile.mimetype}`;
        }
        if (! this.VerifyOption1() ) {
            ErrorText = 'Option1 failure';
        }
        return `${UploadedFile.originalname} ${ErrorText}`;
    }
</code>```

This just seems somewhat redundant given the exact same tests would all have to be in the isValid() method.

Body:
I am trying to validate my uploaded file by extending the abstract FileValidator

export declare abstract class FileValidator<TValidationOptions = Record<string, any>> {
    protected readonly validationOptions: TValidationOptions;
    constructor(validationOptions: TValidationOptions);
    /**
     * Indicates if this file should be considered valid, according to the options passed in the constructor.
     * @param file the file from the request object
     */
    abstract isValid(file?: any): boolean | Promise<boolean>;
    /**
     * Builds an error message in case the validation fails.
     * @param file the file from the request object
     */
    abstract buildErrorMessage(file: any): string;
}

Quite simply, I can create my own extended version to validate the upload file is an Excel Workbook.

import { FileValidator } from '@nestjs/common';
import { read, WorkBook } from 'xlsx';

export declare type ExcelWorkbookValidatorOptions = {
    Option1: boolean;
    Option2: number;
};

export class ExcelWorkbookValidator extends FileValidator<ExcelWorkbookValidatorOptions> {
    private ExcelData_: WorkBook;

    constructor(protected readonly validationOptions: ExcelWorkbookValidatorOptions) {
        super(validationOptions);
    }

    /**
     * Indicates if this file should be considered valid, according to the options passed in the constructor.
     * @param UploadedFile the file from the request object
     */
    public isValid(UploadedFile: Express.Multer.File): boolean | Promise<boolean> {
         if (this.validationOptions.Option1) {
             // Check something
             return false;
         }

         if (this.validationOptions.Option2) {
             // Check something else
             return false;
         }

         return true;
    }

    /**
     * Builds an error message in case the validation fails.
     * @param UploadedFile the file from the request object
     */
    public buildErrorMessage(UploadedFile: Express.Multer.File): string {
        return `${UploadedFile.originalname} is not an Excel Workbook`;
    }

}

The buildMessage() gets the original file as a parameter.  I do not know how I can indicate what failed in the Option1 and Option2 check, so that I could change the response message to indicate the issue.

As both the isValid() and buildMessage() get the uploaded file (file: any), does this mean that both functions need the logic to determine if the file is good or bad for custom messages?

I would assume I can do all different functions, one for each Option check, and if it returns false, then the isValid returns false, and the buildMessage would return the text I want to send to indicate the actual issue (Option1 or Option2 failed)?

    /**
     * Builds an error message in case the validation fails.
     * @param UploadedFile the file from the request object
     */
    public buildErrorMessage(UploadedFile: Express.Multer.File): string {
        let ErrorText: string = '';
        if (! this.IsValidExcelMimeType(UploadedFile.mimetype)) {
            ErrorText = `invalid mimetype ${UploadedFile.mimetype}`;
        }
        if (! this.VerifyOption1() ) {
            ErrorText = 'Option1 failure';
        }
        return `${UploadedFile.originalname} ${ErrorText}`;
    }

This just seems somewhat redundant given the exact same tests would all have to be in the isValid() method.


问:
Javascript, crop an image to square format and upload it
I have the form and the scripts below to upload an image.
Before uploading, I resize the image in square format using a canvas. But I can't upload the square image, it's always the original image that is uploaded.
Does anyone have an idea for me?
thanks in advance

if (document.getElementById('imgInp')) {
  imgInp.onchange = (evt) => {
    if (document.getElementById('pngImg')) {
      document.getElementById('pngImg').remove();
    }
    if (document.getElementById('canvas')) {
      document.getElementById('canvas').remove();
    }
    const [file] = imgInp.files;

    if (file) {
      blah.src = URL.createObjectURL(file);
      crop(blah.src, 1 / 1).then((canvas) => {
        // `canvas` is cthe resulting image
        //.replace('image/png', 'image/octet-stream');
        canvas.setAttributeNS(null, 'class', 'visuallyhidden');
        document.body.appendChild(canvas).setAttribute('id', 'canvas');

        let pnGImage = convertCanvasToImage();
        document.body.appendChild(pnGImage).setAttribute('id', 'pngImg');
        document.getElementById('pngImg').className = 'visuallyhidden';

        let url = document.getElementById('pngImg').src;
        blah.src = url;

      });
    }
  };
}

/**
 * @param {string} url - The source image
 * @param {number} aspectRatio - The aspect ratio
 * @return {Promise<HTMLCanvasElement>} A Promise that resolves with the resulting image as a canvas element
 */
function crop(url, aspectRatio) {
  // we return a Promise that gets resolved with our canvas element
  return new Promise((resolve) => {
    // this image will hold our source image data
    const inputImage = new Image();

    // we want to wait for our image to load
    inputImage.onload = () => {
      // let's store the width and height of our image
      const inputWidth = inputImage.naturalWidth;
      const inputHeight = inputImage.naturalHeight;

      // get the aspect ratio of the input image
      const inputImageAspectRatio = inputWidth / inputHeight;

      // if it's bigger than our target aspect ratio
      let outputWidth = inputWidth;
      let outputHeight = inputHeight;
      if (inputImageAspectRatio > aspectRatio) {
        outputWidth = inputHeight * aspectRatio;
      } else if (inputImageAspectRatio < aspectRatio) {
        outputHeight = inputWidth / aspectRatio;
      }

      // calculate the position to draw the image at
      const outputX = (outputWidth - inputWidth) * 0.5;
      const outputY = (outputHeight - inputHeight) * 0.5;

      // create a canvas that will present the output image
      const outputImage = document.createElement('canvas');

      // set it to the same size as the image
      outputImage.width = outputWidth;
      outputImage.height = outputHeight;

      // draw our image at position 0, 0 on the canvas
      const ctx = outputImage.getContext('2d');
      ctx.drawImage(inputImage, outputX, outputY);
      resolve(outputImage);
    };

    // start loading our image
    inputImage.src = url;
    //return url;
  });
}

function convertCanvasToImage() {
  let canvas = document.getElementById('canvas');
  let image = new Image();

  image.src = canvas.toDataURL('image/png', 0.9);

  //canvas.toBlob(function (blob) {
  // const formData = new FormData();
  // formData.append('my-file', blob, 'filename.png');
  //});

  console.log(image);
  return image;
  //return formData;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <form class="row g-3" action="" method="post" enctype="multipart/form-data">
    <div class="col-sm-12">
      <label for="nom" class="form-label">Nom</label>
      <input type="text" class="form-control" id="nom" name="nom" required value='{{body.nom}}'>
    </div>
    <div class="col-sm-12">
      <p class="mb-2">Ajouter une photo</p>
      <label class=" mb-3 mt-0">
        {{#if body.img}}
        <img src="{{body.img}}" class="image-upload" id="blah">
        {{else}}
        <img src="/images/camera3.png" class="image-upload" id="blah">
        {{/if}}
        <input type="file" name="imgInp" accept="image/*" id="imgInp"
          onkeyup="document.getElementById('image-upload').value=this.value">
      </label>
    </div>

    <div class="col-12">
      <button class="btn btn-success" type="submit" value="submit" name="action">{{action}}</button>
      Annuler
    </div>
  </form>
</div></code>```

I have the form and the scripts below to upload an image.
Before uploading, I resize the image in square format using a canvas. But I can't upload the square image, it's always the original image that is uploaded.
Does anyone have an idea for me?
thanks in advance

Body:
I have the form and the scripts below to upload an image.
Before uploading, I resize the image in square format using a canvas. But I can't upload the square image, it's always the original image that is uploaded.
Does anyone have an idea for me?
thanks in advance

if (document.getElementById('imgInp')) {
  imgInp.onchange = (evt) => {
    if (document.getElementById('pngImg')) {
      document.getElementById('pngImg').remove();
    }
    if (document.getElementById('canvas')) {
      document.getElementById('canvas').remove();
    }
    const [file] = imgInp.files;

    if (file) {
      blah.src = URL.createObjectURL(file);
      crop(blah.src, 1 / 1).then((canvas) => {
        // `canvas` is cthe resulting image
        //.replace('image/png', 'image/octet-stream');
        canvas.setAttributeNS(null, 'class', 'visuallyhidden');
        document.body.appendChild(canvas).setAttribute('id', 'canvas');

        let pnGImage = convertCanvasToImage();
        document.body.appendChild(pnGImage).setAttribute('id', 'pngImg');
        document.getElementById('pngImg').className = 'visuallyhidden';

        let url = document.getElementById('pngImg').src;
        blah.src = url;

      });
    }
  };
}

/**
 * @param {string} url - The source image
 * @param {number} aspectRatio - The aspect ratio
 * @return {Promise<HTMLCanvasElement>} A Promise that resolves with the resulting image as a canvas element
 */
function crop(url, aspectRatio) {
  // we return a Promise that gets resolved with our canvas element
  return new Promise((resolve) => {
    // this image will hold our source image data
    const inputImage = new Image();

    // we want to wait for our image to load
    inputImage.onload = () => {
      // let's store the width and height of our image
      const inputWidth = inputImage.naturalWidth;
      const inputHeight = inputImage.naturalHeight;

      // get the aspect ratio of the input image
      const inputImageAspectRatio = inputWidth / inputHeight;

      // if it's bigger than our target aspect ratio
      let outputWidth = inputWidth;
      let outputHeight = inputHeight;
      if (inputImageAspectRatio > aspectRatio) {
        outputWidth = inputHeight * aspectRatio;
      } else if (inputImageAspectRatio < aspectRatio) {
        outputHeight = inputWidth / aspectRatio;
      }

      // calculate the position to draw the image at
      const outputX = (outputWidth - inputWidth) * 0.5;
      const outputY = (outputHeight - inputHeight) * 0.5;

      // create a canvas that will present the output image
      const outputImage = document.createElement('canvas');

      // set it to the same size as the image
      outputImage.width = outputWidth;
      outputImage.height = outputHeight;

      // draw our image at position 0, 0 on the canvas
      const ctx = outputImage.getContext('2d');
      ctx.drawImage(inputImage, outputX, outputY);
      resolve(outputImage);
    };

    // start loading our image
    inputImage.src = url;
    //return url;
  });
}

function convertCanvasToImage() {
  let canvas = document.getElementById('canvas');
  let image = new Image();

  image.src = canvas.toDataURL('image/png', 0.9);

  //canvas.toBlob(function (blob) {
  // const formData = new FormData();
  // formData.append('my-file', blob, 'filename.png');
  //});

  console.log(image);
  return image;
  //return formData;
}

  <form class="row g-3" action="" method="post" enctype="multipart/form-data">

      Nom
      <input type="text" class="form-control" id="nom" name="nom" required value='{{body.nom}}'>

Ajouter une photo

        {{#if body.img}}

        {{else}}

        {{/if}}
        <input type="file" name="imgInp" accept="image/*" id="imgInp"
          onkeyup="document.getElementById('image-upload').value=this.value">

      <button class="btn btn-success" type="submit" value="submit" name="action">{{action}}</button>
      Annuler

  </form>

I have the form and the scripts below to upload an image.
Before uploading, I resize the image in square format using a canvas. But I can't upload the square image, it's always the original image that is uploaded.
Does anyone have an idea for me?
thanks in advance


问:
How to add classpath in Spring Boot when trying to run project locally with IntelliJ
Simple Spring boot program to load application.properties from src/main/resource directory:

```<code>@SpringBootApplication
public class PathLearningApplication {

    public static void main(String[] args) throws IOException {
        // 1.
        InputStream inputStream = new ClassPathResource("classpath:application.properties").getInputStream();

        // 2.
        InputStream inputStream2 = new ClassPathResource("application.properties").getInputStream();

        // 3.
        ResourceLoader resourceLoader = new DefaultResourceLoader();

        Resource resource = resourceLoader.getResource("classpath:application.properties");
        resource.getInputStream();

        SpringApplication.run(PathLearningApplication.class, args);
    }

}
</code>```

When I tried to run this program locally using Intellij, line number 1. gave me the error:

Error:

```<code>Exception in thread "main" java.io.FileNotFoundException: class path resource [classpath:application.properties] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:199)
    at com.example.PathLearning.PathLearningApplication.main(PathLearningApplication.java:19)
</code>```

While line number 2. (InputStream2) and line number 3. (ResourceLoader works fine).

Here is the classPath set in intellij using stackoverflow

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Classpath set in intellij

So now my questions related to this post are:

What is the difference between classpath: prefix and without classpath: prefix in path

why line 1 (ClassPathResource) didn't work while line 3 (ResourceLoader) worked in which I have also used classpath prefix.

What is the best way of loading the file? Using the classpath prefix or without it, and what is its purpose?

Body:
Simple Spring boot program to load application.properties from src/main/resource directory:

@SpringBootApplication
public class PathLearningApplication {

    public static void main(String[] args) throws IOException {
        // 1.
        InputStream inputStream = new ClassPathResource("classpath:application.properties").getInputStream();

        // 2.
        InputStream inputStream2 = new ClassPathResource("application.properties").getInputStream();

        // 3.
        ResourceLoader resourceLoader = new DefaultResourceLoader();

        Resource resource = resourceLoader.getResource("classpath:application.properties");
        resource.getInputStream();

        SpringApplication.run(PathLearningApplication.class, args);
    }

}

When I tried to run this program locally using Intellij, line number 1. gave me the error:

Error:

Exception in thread "main" java.io.FileNotFoundException: class path resource [classpath:application.properties] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:199)
    at com.example.PathLearning.PathLearningApplication.main(PathLearningApplication.java:19)

While line number 2. (InputStream2) and line number 3. (ResourceLoader works fine).

Here is the classPath set in intellij using stackoverflow

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Classpath set in intellij

So now my questions related to this post are:

What is the difference between classpath: prefix and without classpath: prefix in path

why line 1 (ClassPathResource) didn't work while line 3 (ResourceLoader) worked in which I have also used classpath prefix.

What is the best way of loading the file? Using the classpath prefix or without it, and what is its purpose?


问:
Ping timeout in docker container with low ttl values. Expecting Time to live exceeded response
It seems that pinging inside a docker container for linux with a low TTL results in a TimedOut. I use ping with a low value for ttl, such as 1 or 3 or 4 and so on but the result is a timeout exception.

See this test:

```<code># ping 1.1.1.1 -t 3 -w 2
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.

--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1075ms

# ping 1.1.1.1 -t 15 -w 4
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=37 time=19.7 ms
64 bytes from 1.1.1.1: icmp_seq=2 ttl=37 time=18.5 ms
64 bytes from 1.1.1.1: icmp_seq=3 ttl=37 time=18.5 ms
64 bytes from 1.1.1.1: icmp_seq=4 ttl=37 time=22.4 ms

--- 1.1.1.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3006ms
rtt min/avg/max/mdev = 18.512/19.799/22.407/1.585 ms
</code>```

I created a .Net 7 Console app deployed to a docker linux container to test a Ping request using the IP Address, timeout, buffer, and PingOptions. I increment the TTL in PingOptions from 1 to 30 trying to ping 1.1.1.1 and it does not work with low ttl numbers.

The same code works fine in WSL2 using Ubuntu. It provides the intermediate IP addresses along the way to the final stop of 1.1.1.1 (or any other known IP address).

Why does a ping fail in the docker linux container when the TTL is a low number?

Is there a security setting or other configuration needed to get the ping send to result in a "TtlExpired" instead of "TimedOut"?

Body:
It seems that pinging inside a docker container for linux with a low TTL results in a TimedOut. I use ping with a low value for ttl, such as 1 or 3 or 4 and so on but the result is a timeout exception.

See this test:

# ping 1.1.1.1 -t 3 -w 2
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.

--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1075ms

# ping 1.1.1.1 -t 15 -w 4
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=37 time=19.7 ms
64 bytes from 1.1.1.1: icmp_seq=2 ttl=37 time=18.5 ms
64 bytes from 1.1.1.1: icmp_seq=3 ttl=37 time=18.5 ms
64 bytes from 1.1.1.1: icmp_seq=4 ttl=37 time=22.4 ms

--- 1.1.1.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3006ms
rtt min/avg/max/mdev = 18.512/19.799/22.407/1.585 ms

I created a .Net 7 Console app deployed to a docker linux container to test a Ping request using the IP Address, timeout, buffer, and PingOptions. I increment the TTL in PingOptions from 1 to 30 trying to ping 1.1.1.1 and it does not work with low ttl numbers.

The same code works fine in WSL2 using Ubuntu. It provides the intermediate IP addresses along the way to the final stop of 1.1.1.1 (or any other known IP address).

Why does a ping fail in the docker linux container when the TTL is a low number?

Is there a security setting or other configuration needed to get the ping send to result in a "TtlExpired" instead of "TimedOut"?


问:
TypeError: Series.cov() missing 1 required positional argument: 'other'
Get an TypeError when compiling this code:

TypeError: Series.cov() missing 1 required positional argument: 'other'

. What is my problem?

```<code>def portifolioOptimalization(inputStocks):

    stocks = inputStocks

    portifolioData = yf.download(stocks, '2020-1-1')['Close']

    portifolioReturns = portifolioData.pct_change()
    numberOfStocks = len(inputStocks)
    portifolioWeight = []

    global weightSum
    weightSum = 1

    for i in range(0,numberOfStocks-1):

        stockWeight = round(random.uniform(0.0, weightSum), 2)

        weightSum = weightSum - stockWeight

        portifolioWeight.append(stockWeight)

    portifolioWeight.append(weightSum)
    portifolioReturns = portifolioReturns.dot(portifolioWeight)

    varianceMatrix = portifolioReturns.cov()
</code>```

Expects a covariance matrix

Body:
Get an TypeError when compiling this code:

TypeError: Series.cov() missing 1 required positional argument: 'other'

. What is my problem?

def portifolioOptimalization(inputStocks):

    stocks = inputStocks

    portifolioData = yf.download(stocks, '2020-1-1')['Close']

    portifolioReturns = portifolioData.pct_change()
    numberOfStocks = len(inputStocks)
    portifolioWeight = []

    global weightSum
    weightSum = 1

    for i in range(0,numberOfStocks-1):

        stockWeight = round(random.uniform(0.0, weightSum), 2)

        weightSum = weightSum - stockWeight

        portifolioWeight.append(stockWeight)

    portifolioWeight.append(weightSum)
    portifolioReturns = portifolioReturns.dot(portifolioWeight)

    varianceMatrix = portifolioReturns.cov()

Expects a covariance matrix


问:
'There can be only one type with an [Application]' error when attempting to build .NET MAUI android app
I am in the process of migrating a Xamarin.Forms app to .NET MAUI, and I am currently fixing build errors as part of the official migration guide published by Microsoft here:
https://github.com/dotnet/maui/wiki/Migrating-from-Xamarin.Forms-(Preview)

Currently, I am attempting to fix the build errors that appear with the Android version of the app, but when I attempt to build now, I am getting the following errors:

```<code>1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.ManifestDocument.CreateApplicationElement(XElement manifest, String applicationClass, List`1 subclasses, TypeDefinitionCache cache)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.ManifestDocument.Merge(TaskLoggingHelper log, TypeDefinitionCache cache, List`1 subclasses, String applicationClass, Boolean embed, String bundledWearApplicationName, IEnumerable`1 mergedManifestDocuments)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.GenerateJavaStubs.Run(DirectoryAssemblyResolver res)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.GenerateJavaStubs.RunTask()
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Microsoft.Android.Build.Tasks.AndroidTask.Execute() in /Users/runner/work/1/s/xamarin-android/external/xamarin-android-tools/src/Microsoft.Android.Build.BaseTasks/AndroidTask.cs:line 17
</code>```

However, there is only one type in my project that has the [Application] attribute, which is the MainApplication class.  The app shouldn't even be using Xamarin.Forms at all, which is why this is puzzling to me.

Body:
I am in the process of migrating a Xamarin.Forms app to .NET MAUI, and I am currently fixing build errors as part of the official migration guide published by Microsoft here:
https://github.com/dotnet/maui/wiki/Migrating-from-Xamarin.Forms-(Preview)

Currently, I am attempting to fix the build errors that appear with the Android version of the app, but when I attempt to build now, I am getting the following errors:

1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.ManifestDocument.CreateApplicationElement(XElement manifest, String applicationClass, List`1 subclasses, TypeDefinitionCache cache)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.ManifestDocument.Merge(TaskLoggingHelper log, TypeDefinitionCache cache, List`1 subclasses, String applicationClass, Boolean embed, String bundledWearApplicationName, IEnumerable`1 mergedManifestDocuments)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.GenerateJavaStubs.Run(DirectoryAssemblyResolver res)
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Xamarin.Android.Tasks.GenerateJavaStubs.RunTask()
1>C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.476\tools\Xamarin.Android.Common.targets(1438,3): error XAGJS7009:    at Microsoft.Android.Build.Tasks.AndroidTask.Execute() in /Users/runner/work/1/s/xamarin-android/external/xamarin-android-tools/src/Microsoft.Android.Build.BaseTasks/AndroidTask.cs:line 17

However, there is only one type in my project that has the [Application] attribute, which is the MainApplication class.  The app shouldn't even be using Xamarin.Forms at all, which is why this is puzzling to me.


问:
Subprocess Error when Launching ec2 cluster instance
I am getting subprocess error when launching ec2 cluster instance.

The terminal lags on

Waiting for cluster to enter 'ssh-ready' state'

when running

```<code>./spark-ec2 --key-pair=ru_spark --identity-file=ru_spark.pem --region=us-east-1 --zone=us-east-1a launch mycluster
</code>```

Console:

```<code>Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Connection to ec2-52-87-225-32.compute-1.amazonaws.com closed.
Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Transferring cluster's SSH key to slaves...
ec2-34-207-153-79.compute-1.amazonaws.com
Warning: Permanently added 'ec2-34-207-153-79.compute-1.amazonaws.com,34.207.153.79' (RSA) to the list of known hosts.
Cloning spark-ec2 scripts from https://github.com/amplab/spark-ec2/tree/branch-1.6 on master...
Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Cloning into 'spark-ec2'...
error: Peer reports incompatible or unsupported protocol version. while accessing https://github.com/amplab/spark-ec2/info/refs?service=git-upload-pack
fatal: HTTP request failed
Connection to ec2-52-87-225-32.compute-1.amazonaws.com closed.
Error executing remote command, retrying after 30 seconds: Command '['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-i', 'ru_spark.pem', '-t', '-t', u'root@ec2-52-87-225-32.compute-1.amazonaws.com', 'rm -rf spark-ec2 && git clone https://github.com/amplab/spark-ec2 -b branch-1.6 spark-ec2']' returned non-zero exit status 128
</code>```

I updated to curl ssl, changed file permissions to 400 and 600 for ru_spark.pem but neither have helped solve the issue.

Body:
I am getting subprocess error when launching ec2 cluster instance.

The terminal lags on

Waiting for cluster to enter 'ssh-ready' state'

when running

./spark-ec2 --key-pair=ru_spark --identity-file=ru_spark.pem --region=us-east-1 --zone=us-east-1a launch mycluster

Console:

Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Connection to ec2-52-87-225-32.compute-1.amazonaws.com closed.
Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Transferring cluster's SSH key to slaves...
ec2-34-207-153-79.compute-1.amazonaws.com
Warning: Permanently added 'ec2-34-207-153-79.compute-1.amazonaws.com,34.207.153.79' (RSA) to the list of known hosts.
Cloning spark-ec2 scripts from https://github.com/amplab/spark-ec2/tree/branch-1.6 on master...
Warning: Permanently added 'ec2-52-87-225-32.compute-1.amazonaws.com,52.87.225.32' (RSA) to the list of known hosts.
Cloning into 'spark-ec2'...
error: Peer reports incompatible or unsupported protocol version. while accessing https://github.com/amplab/spark-ec2/info/refs?service=git-upload-pack
fatal: HTTP request failed
Connection to ec2-52-87-225-32.compute-1.amazonaws.com closed.
Error executing remote command, retrying after 30 seconds: Command '['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-i', 'ru_spark.pem', '-t', '-t', u'root@ec2-52-87-225-32.compute-1.amazonaws.com', 'rm -rf spark-ec2 && git clone https://github.com/amplab/spark-ec2 -b branch-1.6 spark-ec2']' returned non-zero exit status 128

I updated to curl ssl, changed file permissions to 400 and 600 for ru_spark.pem but neither have helped solve the issue.


问:
Keras model custom signatures are not saved when learning is done on GCP
After reading blog "An Object Oriented Approach To Train an Image Classifier with Tensorflow" I've tried to set custom signatures for my Keras model (TF2) like this:

```<code>class ImageClassifierModel(tf.keras.Model):
    def __init__(self,...)
    def call(self,...)
    def save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None,save_traces=True):
        if signatures is None:
            signatures = dict()
        signatures["serving_default"] = self.predict_b64_image
        signatures["serving_array"] = self.predict_numpy_image
        super().save(filepath, overwrite, include_optimizer, save_format, signatures, options, save_traces)

    @tf.function(input_signature=[tf.TensorSpec(name="image_b64_string", shape=None, dtype=tf.string)])
    def predict_b64_image(self, b64_image):
        #...

    @tf.function(input_signature=[tf.TensorSpec(name="image_tensor", shape=(None, None, None, 3), dtype=tf.float32)])
    def predict_numpy_image(self, image):
        #...
</code>```

I have a ModelCheckpoint callback that saves the model when learning is done.

Once learning is finished, if I looked at the model signatures with saved_model_cli tool, I can see that:

When learning is done locally (docker container):
my signatures are there.

When learning is done on Google Cloud Platform (same custom container):
After the download of the model locally (from Google Storage) I look at the signatures: my custom signatures are not there anymore. Only the "image" signature (probably inferred by TF) that expects an image of rank 4

How do you explain such a behavior?

EDIT: the only workaround I've found is:

```<code>model = tf.keras.models.load_model(my_model_path)
model.save_weights('/tmp/my_model_weights')
# redefine my model
model = ResnetModel(...)
keras_model.load_weights('/tmp/my_model_weights')
model.save(my_model_path)
</code>```

Body:
After reading blog "An Object Oriented Approach To Train an Image Classifier with Tensorflow" I've tried to set custom signatures for my Keras model (TF2) like this:

class ImageClassifierModel(tf.keras.Model):
    def __init__(self,...)
    def call(self,...)
    def save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None,save_traces=True):
        if signatures is None:
            signatures = dict()
        signatures["serving_default"] = self.predict_b64_image
        signatures["serving_array"] = self.predict_numpy_image
        super().save(filepath, overwrite, include_optimizer, save_format, signatures, options, save_traces)

    @tf.function(input_signature=[tf.TensorSpec(name="image_b64_string", shape=None, dtype=tf.string)])
    def predict_b64_image(self, b64_image):
        #...

    @tf.function(input_signature=[tf.TensorSpec(name="image_tensor", shape=(None, None, None, 3), dtype=tf.float32)])
    def predict_numpy_image(self, image):
        #...

I have a ModelCheckpoint callback that saves the model when learning is done.

Once learning is finished, if I looked at the model signatures with saved_model_cli tool, I can see that:

When learning is done locally (docker container):
my signatures are there.

When learning is done on Google Cloud Platform (same custom container):
After the download of the model locally (from Google Storage) I look at the signatures: my custom signatures are not there anymore. Only the "image" signature (probably inferred by TF) that expects an image of rank 4

How do you explain such a behavior?

EDIT: the only workaround I've found is:

model = tf.keras.models.load_model(my_model_path)
model.save_weights('/tmp/my_model_weights')
# redefine my model
model = ResnetModel(...)
keras_model.load_weights('/tmp/my_model_weights')
model.save(my_model_path)


问:
"Player.ControlType.PC" via instance reference is not possible; instead, specify it by specifying the type name
I'm new to c#. And I don't understand the essence of the error and how to solve it.Please help

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public ControlType controlType;
    public float speed;
    public Joystick joystick;

    public enum ControlType{PC, Android}

    private Rigidbody2D rb;
    private Vector2 moveInput;
    private Vector2 moveVelocity;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (controlType == controlType.PC)
        {
            moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        }
        else if (controlType = controlType.Android)
        {
            moveInput = new Vector2(joystick.Horizontal, joystick.Vertical);
        }
        moveVelocity = moveInput.normalized * speed;
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }
}
</code>```

What is the error, I don't understand.watching some videos from

Error CS0176 "Player.ControlType.PC" through a reference to an instance is not possible; instead, refine it by specifying the type name. I haven't found anything yet

Body:
I'm new to c#. And I don't understand the essence of the error and how to solve it.Please help

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public ControlType controlType;
    public float speed;
    public Joystick joystick;

    public enum ControlType{PC, Android}

    private Rigidbody2D rb;
    private Vector2 moveInput;
    private Vector2 moveVelocity;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (controlType == controlType.PC)
        {
            moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        }
        else if (controlType = controlType.Android)
        {
            moveInput = new Vector2(joystick.Horizontal, joystick.Vertical);
        }
        moveVelocity = moveInput.normalized * speed;
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }
}

What is the error, I don't understand.watching some videos from

Error CS0176 "Player.ControlType.PC" through a reference to an instance is not possible; instead, refine it by specifying the type name. I haven't found anything yet


问:
Why some images on my website are displaying partially and some being displayed fully?
I am facing this strange issue on some ios devices. The problem is that some images are displaying entirely while some are rendering only partially like half or even less, but when I open the same site on some other ios device or any android device, it is rendering fully. Not sure what's the issue. Btw I am adding images to the DOM via JavaScript as I am receiving them through an API.
Also, I noticed that this issue only occurs for the starting images and not on the ending images!
In total there are like 6 images.
Please find attached the screenshot.

The starting 2 images as you can see are less than half rendered and the later ones are fully rendered. Also, from dev tools when I hover over the image src, it is showing the complete images so which confirms that there is some issue on the frontend side. Kindly help me with this!

This is the code for adding images:

```<code>overlayData.overlays.forEach((overlay) => {
        let thumbnail = document.createElement("img");
        thumbnail.className = "swiper-slide canvas-edit-thumbnail overlay";
        thumbnail.src = overlay.image;
        thumbnail.addEventListener("click", () => {
          overlayImgPreview.style.display = "block";
          overlayImgPreview.src = thumbnail.src;
          overlayAdded = true;
        });
        overlayThumbnails.appendChild(thumbnail);
      });
</code>```

Body:
I am facing this strange issue on some ios devices. The problem is that some images are displaying entirely while some are rendering only partially like half or even less, but when I open the same site on some other ios device or any android device, it is rendering fully. Not sure what's the issue. Btw I am adding images to the DOM via JavaScript as I am receiving them through an API.
Also, I noticed that this issue only occurs for the starting images and not on the ending images!
In total there are like 6 images.
Please find attached the screenshot.

The starting 2 images as you can see are less than half rendered and the later ones are fully rendered. Also, from dev tools when I hover over the image src, it is showing the complete images so which confirms that there is some issue on the frontend side. Kindly help me with this!

This is the code for adding images:

overlayData.overlays.forEach((overlay) => {
        let thumbnail = document.createElement("img");
        thumbnail.className = "swiper-slide canvas-edit-thumbnail overlay";
        thumbnail.src = overlay.image;
        thumbnail.addEventListener("click", () => {
          overlayImgPreview.style.display = "block";
          overlayImgPreview.src = thumbnail.src;
          overlayAdded = true;
        });
        overlayThumbnails.appendChild(thumbnail);
      });


问:
Getting Value Error while creating RNN model
Im getting this error: ValueError: logits and labels must have the same shape, received ((32, 1) vs (32, 23740))

This is my full code:

```<code>import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import re
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.utils import pad_sequences

# All data processing stuff

data = pd.read_csv('test.csv')          # Load the data

# convert Sentiment type to string
data['Sentiment'] = data['Sentiment'].astype(str)

# remove special characters and convert to lowercase
data["Tweet"] = data["Tweet"].apply(lambda x: x.lower())    # Convert all tweets to lowercase
data["Tweet"] = data["Tweet"].apply(lambda x: x.replace("[^a-zA-Z0-9]", ""))    # Remove special characters
data["Sentiment"] = data["Sentiment"].apply(lambda x: x.lower())

# Initialize the Tokenizer
tokenizer = Tokenizer()

# Fit the Tokenizer on the text data
tokenizer.fit_on_texts(data["Tweet"] + data["Sentiment"])

token_sequences1 = tokenizer.texts_to_matrix(data["Tweet"])
token_sequences2 = tokenizer.texts_to_matrix(data["Sentiment"])

padded_sequences1 = pad_sequences(token_sequences1)
padded_sequences2 = pad_sequences(token_sequences2)

# split the data into training and testing sets

x_train, x_test, y_train, y_test = train_test_split(
    padded_sequences1, padded_sequences2, test_size=0.2, random_state=42)

# create the RNN model
model = Sequential()

# 1000 is the number of words in the vocabulary, 128 is the dimension of the embedding vector,
model.add(Embedding(1000, 128))
model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))

# compile the model with a specified loss function and optimizer
# binary_crossentropy is used for binary classification problems like this one (positive or negative sentiment)
# accuracy is the metric used to evaluate the model performance (the percentage of correct predictions)
# the loss function and the optimizer can be changed to see if the model performance improves or not
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())

# train the model on the training data and put verbose=1 to see the training progress
model.fit(x_train, y_train, batch_size=32, epochs=10, verbose=1)

# evaluate the model on the testing data
y_pred = model.predict(x_test)

# calculate the evaluation metrics
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

# print the evaluation metrics
print("Accuracy: {:.2f}".format(accuracy))
print("Precision: {:.2f}".format(precision))
print("Recall: {:.2f}".format(recall))
print("F1 Score: {:.2f}".format(f1))
</code>```

Im actually trying to create sentiment analyser on news headlines tweets from this data, here is a sample image of how my data looks in CSV.

Please provide a solution to this, I have tried every solution I had find

Body:
Im getting this error: ValueError: logits and labels must have the same shape, received ((32, 1) vs (32, 23740))

This is my full code:

import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import re
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.utils import pad_sequences

# All data processing stuff

data = pd.read_csv('test.csv')          # Load the data

# convert Sentiment type to string
data['Sentiment'] = data['Sentiment'].astype(str)

# remove special characters and convert to lowercase
data["Tweet"] = data["Tweet"].apply(lambda x: x.lower())    # Convert all tweets to lowercase
data["Tweet"] = data["Tweet"].apply(lambda x: x.replace("[^a-zA-Z0-9]", ""))    # Remove special characters
data["Sentiment"] = data["Sentiment"].apply(lambda x: x.lower())

# Initialize the Tokenizer
tokenizer = Tokenizer()

# Fit the Tokenizer on the text data
tokenizer.fit_on_texts(data["Tweet"] + data["Sentiment"])

token_sequences1 = tokenizer.texts_to_matrix(data["Tweet"])
token_sequences2 = tokenizer.texts_to_matrix(data["Sentiment"])

padded_sequences1 = pad_sequences(token_sequences1)
padded_sequences2 = pad_sequences(token_sequences2)

# split the data into training and testing sets

x_train, x_test, y_train, y_test = train_test_split(
    padded_sequences1, padded_sequences2, test_size=0.2, random_state=42)

# create the RNN model
model = Sequential()

# 1000 is the number of words in the vocabulary, 128 is the dimension of the embedding vector,
model.add(Embedding(1000, 128))
model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(1, activation='sigmoid'))

# compile the model with a specified loss function and optimizer
# binary_crossentropy is used for binary classification problems like this one (positive or negative sentiment)
# accuracy is the metric used to evaluate the model performance (the percentage of correct predictions)
# the loss function and the optimizer can be changed to see if the model performance improves or not
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())

# train the model on the training data and put verbose=1 to see the training progress
model.fit(x_train, y_train, batch_size=32, epochs=10, verbose=1)

# evaluate the model on the testing data
y_pred = model.predict(x_test)

# calculate the evaluation metrics
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

# print the evaluation metrics
print("Accuracy: {:.2f}".format(accuracy))
print("Precision: {:.2f}".format(precision))
print("Recall: {:.2f}".format(recall))
print("F1 Score: {:.2f}".format(f1))

Im actually trying to create sentiment analyser on news headlines tweets from this data, here is a sample image of how my data looks in CSV.

Please provide a solution to this, I have tried every solution I had find


问:
Merging data with various criteria by dates in Excel
I have some data in excel that are formulated as so:

I need the records with identical features to merge to one record with the oldest active date to the newest active date and the ones with changes to remain split. Basically, if there are no changes there should be one record with new active dates and if there is one change 2 records, 2 changes-3 records as so:

I'd really appreciate the help.

I tried ordering the data by id and date and applying an if statement where if there the id above or below are equal AND any of the features are not equal than return the same date and if they are equal than return the oldest and newest date for begin and end date respectively for that ID number so that they would have identical date ranges and then deleting the duplicates but resulted in the records and the records that were not sorted in a particular order not merging since it only compared the records to the ones above or below it.


问:
'datetime.datetime' object has no attribute 'strip'
I created an update form, the form has 2 time field and 2 date time field, once click on submit even nothing change, I got an error "'datetime.datetime' object has no attribute 'strip'".
but there is no error when creating a new object for the same model .
modles:

```<code>time_start=models.DateTimeField(blank=True,null=True)
htime_start=models.TimeField(blank=True,null=True)
time_end = models.DateTimeField(blank=True, null=True)
htime_end=models.TimeField(blank=True,null=True)
time_require=models.DateTimeField(blank=True,null=True)
machine=models.ForeignKey(Machine,null=True, on_delete=models.SET_NULL, blank=True)
</code>```

forms:

```<code>class AssignTimeForProjects(forms.ModelForm):
title = forms.CharField(disabled=True)
owner=forms.CharField(disabled=True)
time_require=forms.TimeField(disabled=True)
class Meta:
    model = tb_order
    # fields='__all__'
    fields = ['title', 'owner', 'grade', 'quantity',
              'time_require','htime_start','color',
              'mould','time_start','time_end', 'htime_end' ,'machine']

def __init__(self, *args, **kwargs):
    super(AssignTimeForProjects, self).__init__(*args, **kwargs)
    self.fields["time_end"] = JalaliDateField(label=('تاریخ اتمام'), widget=(AdminJalaliDateWidget))
    self.fields["time_start"] = JalaliDateField(label=('تاریخ شروع'), widget=(AdminJalaliDateWidget))
</code>```

Html:

```<code><label>{{ form.htime_start.label}}</label>
                {% render_field form.htime_start  type="time"  class+="form-control timepicker" autocomplete="off" %}
                <br>
                <label>{{ form.time_end.label}}</label>
                {% render_field form.time_end  class+="form-control" autocomplete="off" %}
                <br>
                <label>{{ form.htime_end.label}}</label>
                {% render_field form.htime_end  type="time"  class+="form-control" autocomplete="off" %}
</code>```

Body:
I created an update form, the form has 2 time field and 2 date time field, once click on submit even nothing change, I got an error "'datetime.datetime' object has no attribute 'strip'".
but there is no error when creating a new object for the same model .
modles:

time_start=models.DateTimeField(blank=True,null=True)
htime_start=models.TimeField(blank=True,null=True)
time_end = models.DateTimeField(blank=True, null=True)
htime_end=models.TimeField(blank=True,null=True)
time_require=models.DateTimeField(blank=True,null=True)
machine=models.ForeignKey(Machine,null=True, on_delete=models.SET_NULL, blank=True)

forms:

class AssignTimeForProjects(forms.ModelForm):
title = forms.CharField(disabled=True)
owner=forms.CharField(disabled=True)
time_require=forms.TimeField(disabled=True)
class Meta:
    model = tb_order
    # fields='__all__'
    fields = ['title', 'owner', 'grade', 'quantity',
              'time_require','htime_start','color',
              'mould','time_start','time_end', 'htime_end' ,'machine']

def __init__(self, *args, **kwargs):
    super(AssignTimeForProjects, self).__init__(*args, **kwargs)
    self.fields["time_end"] = JalaliDateField(label=('تاریخ اتمام'), widget=(AdminJalaliDateWidget))
    self.fields["time_start"] = JalaliDateField(label=('تاریخ شروع'), widget=(AdminJalaliDateWidget))

Html:

{{ form.htime_start.label}}
                {% render_field form.htime_start  type="time"  class+="form-control timepicker" autocomplete="off" %}

                {{ form.time_end.label}}
                {% render_field form.time_end  class+="form-control" autocomplete="off" %}

                {{ form.htime_end.label}}
                {% render_field form.htime_end  type="time"  class+="form-control" autocomplete="off" %}


问:
LinkedIn login in Firebase without use of libraries like passport js
I want to authenticate users with firebase using LinkedIn Signin. All guides I found require use of libraries like passport. Is there a way to achieve this in Cloud functions using POST/GET requests?
My frontend is developed in ReactJS with Firestore Cloud Functions as backend.

I have tried making POST requests using various methods including the use of axios but Firestore Cloud function gives error when I try to make any POST/GET request from inside.


问:
How to customize the hovering text when it is another column rather than the columns introduced for axes?
I have a df with several columns, and I have a 3D plot showing three columns. I want to customize the hovering text to show z and also another column named place
I have done the first part for the z, but I don’t understand how to do it for another column that is not one of the axes.

```<code>fig = go.Figure()
fig.add_trace(go.Scatter3d(x=df['X'], y=df['Y'], z=df['Z'],
                           hovertemplate="<b><i>Z</i>: %{z:.2f}</b>" + "<br><b><i>%{text}</i>"),)
</code>```

Body:
I have a df with several columns, and I have a 3D plot showing three columns. I want to customize the hovering text to show z and also another column named place
I have done the first part for the z, but I don’t understand how to do it for another column that is not one of the axes.

fig = go.Figure()
fig.add_trace(go.Scatter3d(x=df['X'], y=df['Y'], z=df['Z'],
                           hovertemplate="Z: %{z:.2f}" + "
%{text}"),)


问:
Trying to make buttons based off last search
Trying to make the webpage load animals out when a zipcode is submitted and then create a button that stays there even if you refresh the webpage.

When I try to pass through the local storage it keeps saying undefined. I checked the typeof and it keeps saying that it is a string and I'm not sure how to change it to a number.

```<code>let apiKey = "sbkQE4y07LmiClHOWA7HTgN4YohDfEx44m5DOUc4DVEQjbQoQU";
let secret = "QvbeKf6Pg5ylYKSPPZEtvZp4nJL5iaxlFv49mN5w";
let token;
let dogCards = document.getElementById("dog-cards")
let animalSearch = document.getElementById("animal-search")
const dogForm = document.getElementById("dog-form")

addEventListener('submit', grabAnimals)
console.log(localStorage)
function pastZipCodeSubmitHandler(data){
var zipCode = event.target.getAttribute("data-zipCode");
// console.log(zipCode)
console.log(typeof zipCode)
grabAnimals(zipCode)
}

function grabAnimals(e){
// e.preventDefault();
let zipCode = document.querySelector("#zip-code").value.trim();

    // grabs the access token from Pet Finders API

fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + apiKey + '&client_secret=' + secret,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then((res) =\> res.json())
.then((data) =\> {
token = data.access_token
})
.then(() =\>{
//calls the api but this time with the token Oauth
// TODO put user inputs into this fetch
fetch('https://api.petfinder.com/v2/animals?type=dog&location='+ zipCode + '&status=adoptable', {
headers: {
Authorization: "Bearer " + token,
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res) =\> res.json())
.then((data) =\> showAnimals(data.animals));
// catches the error
}).catch((err) =\> console.error(err));
}

function showAnimals(pet) {
console.log(pet)

    pet.forEach(pet => {
        const div = document.createElement("div");

        div.classList.add("card", "card-body", "bg-stone-300", "bg-opacity-50");
        div.innerHTML = `
      <div class="p-5">
        <div class="pet-container block sm:flex">
        <img class="pet-image mb-5 mr-5 w-full sm:w-auto" src="${
          pet.photos[0] ? pet.photos[0].medium : ""
        }">
          <div  class="mb-5">
            <ul class="">
            <li class=""><strong>Name: </strong>${pet.name} (${pet.age})</li>
            <li  class="text-secondary"><strong>Breed: </strong>${pet.breeds.primary}</li>
              <li><strong>Location: </strong>${pet.contact.address.city}, ${pet.contact.address.state} ${
                pet.contact.address.postcode},${pet.contact.address.country} </li>
              <li class="">${
                pet.contact.phone
                  ? `<li class=""><strong>Phone: </strong>${pet.contact.phone}</li>`
                  : ``}</li>
              ${
                pet.contact.email
                  ? `<li class=""><strong>Email: </strong>${pet.contact.email}</li>`
                  : ``
              }
              <li class=""><strong>Shelter ID: </strong>${pet.organization_id}</li>
            </ul>
            <a class="font-extrabold" href="${pet.url}" target="_blank">Click Here For more info</a>
          </div>
        </div>
        <iframe
         width="100%"
         height="400"
         style="border:0"
         loading="lazy"
         allowfullscreen
         referrerpolicy="no-referrer-when-downgrade"
         src="https://www.google.com/maps/embed/v1/place?key=AIzaSyC7PriPa6496JhFyFBICpjkcjkxgyUukgM
         &q=${pet.contact.address.city}+${pet.contact.address.state}+${
          pet.contact.address.postcode}">
        </iframe>

      </div>
    `;
        dogCards.append(div)

    });

}

let usersZipCode = \[\];
let pastSearchZipCodes = document.querySelector(".userLastZipCode")
const text = document.querySelector('text');

addEventListener('submit', event =\> {
let zipCodeInput = document.querySelector("#zip-code").value.trim();
// text.textContent = number.target.value
saveZipCode(zipCodeInput);
oldZipCodes(zipCodeInput)
})

var saveZipCode = function (zipCodeInput) {
localStorage.setItem("zipCode", JSON.stringify(zipCodeInput))
}

var oldZipCodes = function(e) {
var storedZipCodes = JSON.parse(localStorage.getItem("zipCode"));
console.log(storedZipCodes)

    pastSearchEl = document.createElement("button");
    pastSearchEl.textContent = storedZipCodes;
    pastSearchEl.classList = "zip-code-btn";
    pastSearchEl.setAttribute("data-zipCode", storedZipCodes);
    pastSearchEl.setAttribute("type", "submit");
    pastSearchZipCodes.prepend(pastSearchEl)

}
oldZipCodes();

document.querySelector('.zip-code-btn').addEventListener("click", pastZipCodeSubmitHandler)
</code>```

Body:
Trying to make the webpage load animals out when a zipcode is submitted and then create a button that stays there even if you refresh the webpage.

When I try to pass through the local storage it keeps saying undefined. I checked the typeof and it keeps saying that it is a string and I'm not sure how to change it to a number.

let apiKey = "sbkQE4y07LmiClHOWA7HTgN4YohDfEx44m5DOUc4DVEQjbQoQU";
let secret = "QvbeKf6Pg5ylYKSPPZEtvZp4nJL5iaxlFv49mN5w";
let token;
let dogCards = document.getElementById("dog-cards")
let animalSearch = document.getElementById("animal-search")
const dogForm = document.getElementById("dog-form")

addEventListener('submit', grabAnimals)
console.log(localStorage)
function pastZipCodeSubmitHandler(data){
var zipCode = event.target.getAttribute("data-zipCode");
// console.log(zipCode)
console.log(typeof zipCode)
grabAnimals(zipCode)
}

function grabAnimals(e){
// e.preventDefault();
let zipCode = document.querySelector("#zip-code").value.trim();

    // grabs the access token from Pet Finders API

fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + apiKey + '&client_secret=' + secret,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then((res) =\> res.json())
.then((data) =\> {
token = data.access_token
})
.then(() =\>{
//calls the api but this time with the token Oauth
// TODO put user inputs into this fetch
fetch('https://api.petfinder.com/v2/animals?type=dog&location='+ zipCode + '&status=adoptable', {
headers: {
Authorization: "Bearer " + token,
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res) =\> res.json())
.then((data) =\> showAnimals(data.animals));
// catches the error
}).catch((err) =\> console.error(err));
}

function showAnimals(pet) {
console.log(pet)

    pet.forEach(pet => {
        const div = document.createElement("div");

        div.classList.add("card", "card-body", "bg-stone-300", "bg-opacity-50");
        div.innerHTML = `

Name: ${pet.name} (${pet.age})

Breed: ${pet.breeds.primary}

Location: ${pet.contact.address.city}, ${pet.contact.address.state} ${
                pet.contact.address.postcode},${pet.contact.address.country}

${
                pet.contact.phone
                  ? `<li class=""><strong>Phone: </strong>${pet.contact.phone}</li>`
                  : ``}

              ${
                pet.contact.email
                  ? `<li class=""><strong>Email: </strong>${pet.contact.email}</li>`
                  : ``
              }

Shelter ID: ${pet.organization_id}

            Click Here For more info

    `;
        dogCards.append(div)

    });

}

let usersZipCode = \[\];
let pastSearchZipCodes = document.querySelector(".userLastZipCode")
const text = document.querySelector('text');

addEventListener('submit', event =\> {
let zipCodeInput = document.querySelector("#zip-code").value.trim();
// text.textContent = number.target.value
saveZipCode(zipCodeInput);
oldZipCodes(zipCodeInput)
})

var saveZipCode = function (zipCodeInput) {
localStorage.setItem("zipCode", JSON.stringify(zipCodeInput))
}

var oldZipCodes = function(e) {
var storedZipCodes = JSON.parse(localStorage.getItem("zipCode"));
console.log(storedZipCodes)

    pastSearchEl = document.createElement("button");
    pastSearchEl.textContent = storedZipCodes;
    pastSearchEl.classList = "zip-code-btn";
    pastSearchEl.setAttribute("data-zipCode", storedZipCodes);
    pastSearchEl.setAttribute("type", "submit");
    pastSearchZipCodes.prepend(pastSearchEl)

}
oldZipCodes();

document.querySelector('.zip-code-btn').addEventListener("click", pastZipCodeSubmitHandler)


问:
Gradle Could not create task ':flutter_plugin_android_lifecycle:generateDebugUnitTestConfig'
I am trying to use Apache Pdfbox plugin in my android project but when I try to implement this plugin in my app level build.gradle file it shows the following error.

```<code>Could not create task ':flutter_plugin_android_lifecycle:generateDebugUnitTestConfig'.
this and base files have different roots: F:\pdf2photo\build\flutter_plugin_android_lifecycle and C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.7\android.
</code>```

Here is my app level build.gradle

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.pdf2photo"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName

    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    // https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox
    implementation("org.apache.pdfbox:pdfbox:3.0.0-RC1")
}

</code>```

I think the lifecycle plugin is being called from two different locations but dont know how to solve it

Body:
I am trying to use Apache Pdfbox plugin in my android project but when I try to implement this plugin in my app level build.gradle file it shows the following error.

Could not create task ':flutter_plugin_android_lifecycle:generateDebugUnitTestConfig'.
this and base files have different roots: F:\pdf2photo\build\flutter_plugin_android_lifecycle and C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-2.0.7\android.

Here is my app level build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.pdf2photo"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName

    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    // https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox
    implementation("org.apache.pdfbox:pdfbox:3.0.0-RC1")
}

I think the lifecycle plugin is being called from two different locations but dont know how to solve it


问:
FFMPEG recombine a video with its original uncropped version
I have a video which I cropped to run through a script to process these files much quicker. I would like to now combine the cropped videos back in with their original uncropped version, using the audio from one of the files (the cropped one in this case). The script to crop was:

```<code>ffmpeg -i file.mp4 -filter:v "crop=1000:1000:580:0" -crf 20 -preset slow smaller.mp4
</code>```

So how do I remerge them?

Body:
I have a video which I cropped to run through a script to process these files much quicker. I would like to now combine the cropped videos back in with their original uncropped version, using the audio from one of the files (the cropped one in this case). The script to crop was:

ffmpeg -i file.mp4 -filter:v "crop=1000:1000:580:0" -crf 20 -preset slow smaller.mp4

So how do I remerge them?


问:
what parameters should be used in grid search?
I am using grid search with Random Forest for a model in Python. However, because of the size of the data and capability of the platform, I cannot put all the parameters in the grid search and have to select the important ones. Can someone tell me what important parameters I should use and what value should I use in each parameter? The size of the data being used in the grid search is 100,000, 10% of the original data. Below is what I using. Thank you in advanced.</p>
```<code>param_grid =
{
'n_estimators': [50,100,200,300,400,500],
'max_depth':[5,10,20,30,50,80],
'min_samples_leaf': [1, 2, 5, 10],
}
</code>```

Body:
I am using grid search with Random Forest for a model in Python. However, because of the size of the data and capability of the platform, I cannot put all the parameters in the grid search and have to select the important ones. Can someone tell me what important parameters I should use and what value should I use in each parameter? The size of the data being used in the grid search is 100,000, 10% of the original data. Below is what I using. Thank you in advanced.

param_grid =
{
'n_estimators': [50,100,200,300,400,500],
'max_depth':[5,10,20,30,50,80],
'min_samples_leaf': [1, 2, 5, 10],
}


问:
Video rotates sometimes in Exoplayer.I want to play only portrait videos
I recorded video so its rotation degree is 90 in video metadata.
I am playing all videos in viewpager with recycler Adapter using EXOPLAYER.
This video Plays correct that portrait mode but sometimes rotates.

```<code>  DefaultRenderersFactory rf = new DefaultRenderersFactory(mContext)
                .setExtensionRendererMode(EXTENSION_RENDERER_MODE_PREFER).setMediaCodecSelector(
                        new MediaCodecSelector() {
                            @Override
                            public List<MediaCodecInfo> getDecoderInfos(String mimeType,
                                                                        boolean requiresSecureDecoder, boolean requiresTunnelingDecoder)
                                    throws MediaCodecUtil.DecoderQueryException {
                                List<MediaCodecInfo> decoderInfos = MediaCodecSelector.DEFAULT
                                        .getDecoderInfos(mimeType, requiresSecureDecoder, requiresTunnelingDecoder);
                                if (MimeTypes.VIDEO_H264.equals(mimeType)) {
                                    // copy the list because MediaCodecSelector.DEFAULT returns an unmodifiable list
                                    decoderInfos = new ArrayList<>(decoderInfos);
                                    Collections.reverse(decoderInfos);
                                }
                                return decoderInfos;
                            }
                        });

exoPlayer = new ExoPlayer.Builder(holder.mVideoView.getContext(),rf).setLoadControl(loadControl).build();

holder.mVideoView.setPlayer(exoPlayer);
holder.mVideoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
holder.mVideoView.setShutterBackgroundColor(Color.TRANSPARENT);
holder.mVideoView.setKeepContentOnPlayerReset(true);
exoPlayer.seekTo(0);
exoPlayer.setRepeatMode(Player.REPEAT_MODE_ONE);

 mediaSource = new ProgressiveMediaSource.Factory(
        new CacheDataSource.Factory()
                .setCache(SimpleMediaPlayer.getInstance(mContext))
                .setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
                        .setUserAgent(mContext.getString(R.string.app_name)))
                .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(videoItem.videoURL));

exoPlayer.addMediaSource(mediaSource);

exoPlayer.prepare();

exoPlayer.setPlayWhenReady(true);
exoPlayer.play();

This is my code.I tried by setting rotation for EXoplayer.What will be solution.
</code>```

where is issue?Can anyone tell?..
If issue is in decoder,it rotate every time but video does not rotate every time.

when first time I load video in viewpager2 .It does not rotate.later it rotates.

Please I am badly stuck here.Please help.

Body:
I recorded video so its rotation degree is 90 in video metadata.
I am playing all videos in viewpager with recycler Adapter using EXOPLAYER.
This video Plays correct that portrait mode but sometimes rotates.

  DefaultRenderersFactory rf = new DefaultRenderersFactory(mContext)
                .setExtensionRendererMode(EXTENSION_RENDERER_MODE_PREFER).setMediaCodecSelector(
                        new MediaCodecSelector() {
                            @Override
                            public List<MediaCodecInfo> getDecoderInfos(String mimeType,
                                                                        boolean requiresSecureDecoder, boolean requiresTunnelingDecoder)
                                    throws MediaCodecUtil.DecoderQueryException {
                                List<MediaCodecInfo> decoderInfos = MediaCodecSelector.DEFAULT
                                        .getDecoderInfos(mimeType, requiresSecureDecoder, requiresTunnelingDecoder);
                                if (MimeTypes.VIDEO_H264.equals(mimeType)) {
                                    // copy the list because MediaCodecSelector.DEFAULT returns an unmodifiable list
                                    decoderInfos = new ArrayList<>(decoderInfos);
                                    Collections.reverse(decoderInfos);
                                }
                                return decoderInfos;
                            }
                        });

exoPlayer = new ExoPlayer.Builder(holder.mVideoView.getContext(),rf).setLoadControl(loadControl).build();

holder.mVideoView.setPlayer(exoPlayer);
holder.mVideoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
holder.mVideoView.setShutterBackgroundColor(Color.TRANSPARENT);
holder.mVideoView.setKeepContentOnPlayerReset(true);
exoPlayer.seekTo(0);
exoPlayer.setRepeatMode(Player.REPEAT_MODE_ONE);

 mediaSource = new ProgressiveMediaSource.Factory(
        new CacheDataSource.Factory()
                .setCache(SimpleMediaPlayer.getInstance(mContext))
                .setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
                        .setUserAgent(mContext.getString(R.string.app_name)))
                .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(videoItem.videoURL));

exoPlayer.addMediaSource(mediaSource);

exoPlayer.prepare();

exoPlayer.setPlayWhenReady(true);
exoPlayer.play();

This is my code.I tried by setting rotation for EXoplayer.What will be solution.

where is issue?Can anyone tell?..
If issue is in decoder,it rotate every time but video does not rotate every time.

when first time I load video in viewpager2 .It does not rotate.later it rotates.

Please I am badly stuck here.Please help.


问:
How do I make a contain method in Notion look for two conditions?
I have a Date field in Notion. It's setup is like this: December 7, 2022.
I have made a formula that looks for the month and then adds up expenses from that month. this is the formula:

```<code>contains(format(prop("Date")), "December") ? prop("Expenses") : 0
</code>```

The problem is that I also need it to search for the year, but ignore the day. Is that possible at all?
Kind of like this, but it's not working:

```<code>contains(format(prop("Date")), "December" and "2022") ? prop("Expenses") : 0
</code>```

Body:
I have a Date field in Notion. It's setup is like this: December 7, 2022.
I have made a formula that looks for the month and then adds up expenses from that month. this is the formula:

contains(format(prop("Date")), "December") ? prop("Expenses") : 0

The problem is that I also need it to search for the year, but ignore the day. Is that possible at all?
Kind of like this, but it's not working:

contains(format(prop("Date")), "December" and "2022") ? prop("Expenses") : 0


问:
Alternative for `:has()` css class
The HTML code:

```<code><label class="switch">
  <div class="form-check">
    <input class="form-check-input" type="checkbox" />
    <label class="form-check-label form-label"></label>
  </div>
  <span class="switch__slider switch__round"></span>
</label>
</code>```

I need to change the CSS of the switch__slider when the form-check-input is checked

at the moment I am using

```<code>.switch .form-check:has(input:checked) + switch__slider {
    background-color: #2196F3;
}
</code>```

But I just found out it's not a good idea to use :has() class yet because it's still experimental from what I understood.

But I can't find another solution, any ideas?

Title: Alternative for `:has()` css class

Body:
The HTML code:

    <input class="form-check-input" type="checkbox" />

I need to change the CSS of the switch__slider when the form-check-input is checked

at the moment I am using

.switch .form-check:has(input:checked) + switch__slider {
    background-color: #2196F3;
}

But I just found out it's not a good idea to use :has() class yet because it's still experimental from what I understood.

But I can't find another solution, any ideas?


问:
FB.login() called before FB.init() - Flutter
Trying to:

Authorize via facebook login on web

Problem:

I get the error: FB.login() called before FB.init().

What I'm doing:

I'm using package flutter_facebook_auth: ^5.0.6 for my flutter project. It works fine with Android and iOS, but fails on web.

The main.dart-file initialises facebook before I call the login, so I'm not sure what I need to do. This is my main-file:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if(kIsWeb){
    await FacebookAuth.i.webAndDesktopInitialize(
        appId: "provided in the real code",
        cookie: true,
        xfbml: true,
        version: "v14.0"
    );
  }
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const ProviderScope(child: App()));
}
.
.
.
```


问:
Is it possible to use angular localization in an Ionic application
I've configured angular localizacion (through configuration of the file angular.json) in an application that in fact is an Ionic application.

The problem is that now I get the following error when I try to run capacitor sync:

```<code>[capacitor] [error] The web assets directory (./www) must contain an index.html file.
</code>```

This is because the application now has two directories, one per translated version (one called en for english and another one es for spanish).

Should I have used ngx-translate instead?

Body:
I've configured angular localizacion (through configuration of the file angular.json) in an application that in fact is an Ionic application.

The problem is that now I get the following error when I try to run capacitor sync:

[capacitor] [error] The web assets directory (./www) must contain an index.html file.

This is because the application now has two directories, one per translated version (one called en for english and another one es for spanish).

Should I have used ngx-translate instead?


问:
Lost connection to server - Peer.js
Sometimes, in a very random way, the error "Lost connection to server" appears

Peerjs server code:

const { PeerServer } = require('peer');
const peerServer = PeerServer({ port: 80, host: 'ip' });
```
<p>Peerjs connection code:</p>
<pre class="lang-js prettyprint-override"><code>this.peer = new Peer('', {
  host: 'peerjs server domain (uses cloudflare)',
  port: 443,
  debug: 2,
  pingInterval: 2500,
  secure: true,
  path: '/',
  config: {
    iceServers: [
      {
        urls: [
          'turn:coturnServerIP:3478',
          'stun:coturnServerIP:3478'
        ],
        username,
        credential
      }
    ]
  }
});
</code>```

Title: Lost connection to server - Peer.js

Body:
Sometimes, in a very random way, the error "Lost connection to server" appears

Peerjs server code:

const { PeerServer } = require('peer');
const peerServer = PeerServer({ port: 80, host: 'ip' });

Peerjs connection code:

this.peer = new Peer('', {
  host: 'peerjs server domain (uses cloudflare)',
  port: 443,
  debug: 2,
  pingInterval: 2500,
  secure: true,
  path: '/',
  config: {
    iceServers: [
      {
        urls: [
          'turn:coturnServerIP:3478',
          'stun:coturnServerIP:3478'
        ],
        username,
        credential
      }
    ]
  }
});


问:
How to create MS Access Report With dynamic number of columns
I am building a report in MS Access based on a crosstab query. Therefore I do not know the number of columns or column headers in advance. I have created a template report with one column. In VBA I make a copy of this template report. Using the report recordsource, I then add labels to the report header and textboxes to the report detail and give the report headers the correct name. I set the label and textbox properties using the settings of the label and textbox from the template report. All this is done in VBA.
Is there a better way to create a report with dynamic number of columns? If not, using VBA, is it possible to add columns to the report grid and snap the labels and textboxes that were dynamically created to the grid.</p>


问:
Discord.js invalid form body type when coding discord bot
I'm trying to make a discord bot using Fusion Terror's YouTube tutorial. Everything worked fine until I got an error. Here is the error that I got:

DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
```
<p>And here is the code causing the error</p>
<pre class="lang-js prettyprint-override"><code>const clientId = "1050802610866753608";
const guildId = "1050660625472303104"
const rest = new REST({ version: "9" }).setToken(process.env.token);
    try {
      console.log("Started refreshing application (/) commands.");

      await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
        body: client.commandArray,
      });

      console.log("Successfully reloaded application (/) commands.");
    } catch (error) {
      console.error(error);
    }
</code>```

It should have turned out like this:

```<code>Started refreshing application (/) commands.
Successfully reloaded application (/) commands.
Amber Heart#5868 is connected to the discord server!
</code>```

Body:
I'm trying to make a discord bot using Fusion Terror's YouTube tutorial. Everything worked fine until I got an error. Here is the error that I got:

DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required

And here is the code causing the error

const clientId = "1050802610866753608";
const guildId = "1050660625472303104"
const rest = new REST({ version: "9" }).setToken(process.env.token);
    try {
      console.log("Started refreshing application (/) commands.");

      await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
        body: client.commandArray,
      });

      console.log("Successfully reloaded application (/) commands.");
    } catch (error) {
      console.error(error);
    }

It should have turned out like this:

Started refreshing application (/) commands.
Successfully reloaded application (/) commands.
Amber Heart#5868 is connected to the discord server!


问:
Elastic Search must and Should Combination
I'm new to elastic search and I've the below data in ElasticSearch.

```<code>    {
        "User": "A",
        "Event": "E1"
    },
    {
        "User": "A",
        "Event": "E2"
    }
    {
        "User": "A",
        "Event": "E3"
    },
    {
        "User": "A",
        "Event": "E4"
    }
</code>```

Now I want to fetch data like below i.e

(Event='E1') AND (Event='E2'OR Event='E3' OR Event='E4')

I went through elastic search doc and found that should is used as OR and must is used as AND but I'm a bit confused about how can I form the query.

I used the below query:-

```<code>{
    "from": 0,
    "size": 10,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "Event": "E1"
                    }
                },
                {
                    "bool": {
                        "should": [
                            {
                                "match": {
                                    "Event": "E2"
                                }
                            },
                            {
                                "match": {
                                    "Event": "E3"
                                }
                            },
                            {
                                "match": {
                                    "Event": "E4"
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}
</code>```

But the output is not as expected.
The help is appreciated thanks in advance!!!

Body:
I'm new to elastic search and I've the below data in ElasticSearch.

    {
        "User": "A",
        "Event": "E1"
    },
    {
        "User": "A",
        "Event": "E2"
    }
    {
        "User": "A",
        "Event": "E3"
    },
    {
        "User": "A",
        "Event": "E4"
    }

Now I want to fetch data like below i.e

(Event='E1') AND (Event='E2'OR Event='E3' OR Event='E4')

I went through elastic search doc and found that should is used as OR and must is used as AND but I'm a bit confused about how can I form the query.

I used the below query:-

{
    "from": 0,
    "size": 10,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "Event": "E1"
                    }
                },
                {
                    "bool": {
                        "should": [
                            {
                                "match": {
                                    "Event": "E2"
                                }
                            },
                            {
                                "match": {
                                    "Event": "E3"
                                }
                            },
                            {
                                "match": {
                                    "Event": "E4"
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}

But the output is not as expected.
The help is appreciated thanks in advance!!!


问:
Keep Getting a NONE output
I keep getting a NONE otpout when I run this code. Please help.</p>
```<code>def lengthenStr(strhere):
        while len(strhere) <= 8:
            strhere= strhere.append('d')
            print(strhere)
        return strhere

whatStr = list("hi")
print(lengthenStr(whatStr ))
</code>```

Title: Keep Getting a NONE output

Body:
I keep getting a NONE otpout when I run this code. Please help.

def lengthenStr(strhere):
        while len(strhere) <= 8:
            strhere= strhere.append('d')
            print(strhere)
        return strhere

whatStr = list("hi")
print(lengthenStr(whatStr ))