问:
PATCH in web API for Many to Many relationships using EF
I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.

[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
    if (id == 0 || patchNoteDTO == null)
        return BadRequest();
    var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
    if (note == null)
        return NotFound();

    CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
    if (field.Equals("tags"))
    {
        var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
        List<TagDTO> tagDTOs = new List<TagDTO>();
        if (tags.Count > 0)
        {
            foreach (var tag in tags)
            {
                TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
                tagDTOs.Add(tagDTO);
            }
        }
        createNoteDTO.Tags = tagDTOs;
    }
    patchNoteDTO.ApplyTo(createNoteDTO, ModelState);

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    Note updateNote = _mapper.Map<Note>(createNoteDTO);
    updateNote.ID = id;
    updateNote.ChangedDate = DateTime.Now;
    _db.Update(updateNote);
    if (!field.ToLower().Equals("category"))
        _db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
    _db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
    _db.SaveChanges();
    return NoContent();
}
```
<p>My ApplicationDBContext looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
    public DbSet<Note> Notes { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Tag> Tags { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        modelBuilder.Entity<Note>()
                    .HasOne(e => e.Category)
                    .WithMany(e => e.Notes)
                    .HasForeignKey(e => e.FKCategory)
                    .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<Note>()
                .HasMany(n => n.Tags)
                .WithMany(t => t.Notes)
                .UsingEntity(j => j
                .ToTable("NoteTag")
                .HasData
                (
                    new { NotesID = 1, TagsTagID = 1 },
                    new { NotesID = 2, TagsTagID = 2 }
                ));

        modelBuilder.Entity<Category>().HasData
            (
            new Category
            {
                CategoryID = 1,
                CategoryName = "testCategory1",
                CreatedDate = DateTime.Now
            },
            new Category
            {
                CategoryID = 2,
                CategoryName = "testCategory2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Tag>().HasData
            (
            new Tag
            {
                TagID = 1,
                TagName = "testTag1",
                CreatedDate = DateTime.Now
            },
            new Tag
            {
                TagID = 2,
                TagName = "testTag2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Note>().HasData
            (
            new Note
            {
                ID = 1,
                Title = "testTitle1",
                Description = "testDescription1",
                FKCategory = 1,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            },
            new Note
            {
                ID = 2,
                Title = "testTitle2",
                Description = "testDescription2",
                FKCategory = 2,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            }
            );
    }
}
</code>```

Any suggestions?
Thanks in advance.

Initially I tried without the following if condition:

CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
    var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
    List<TagDTO> tagDTOs = new List<TagDTO>();
    if (tags.Count > 0)
    {
        foreach (var tag in tags)
        {
            TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
            tagDTOs.Add(tagDTO);
        }
    }
    createNoteDTO.Tags = tagDTOs;
}
```

But I got a different error:

I wanted to remove a tag form the following object using a PATCH request:
Note Object

Body:
I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.

[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
    if (id == 0 || patchNoteDTO == null)
        return BadRequest();
    var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
    if (note == null)
        return NotFound();

    CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
    if (field.Equals("tags"))
    {
        var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
        List<TagDTO> tagDTOs = new List<TagDTO>();
        if (tags.Count > 0)
        {
            foreach (var tag in tags)
            {
                TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
                tagDTOs.Add(tagDTO);
            }
        }
        createNoteDTO.Tags = tagDTOs;
    }
    patchNoteDTO.ApplyTo(createNoteDTO, ModelState);

    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    Note updateNote = _mapper.Map<Note>(createNoteDTO);
    updateNote.ID = id;
    updateNote.ChangedDate = DateTime.Now;
    _db.Update(updateNote);
    if (!field.ToLower().Equals("category"))
        _db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
    _db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
    _db.SaveChanges();
    return NoContent();
}

My ApplicationDBContext looks like this:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
    public DbSet<Note> Notes { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Tag> Tags { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        modelBuilder.Entity<Note>()
                    .HasOne(e => e.Category)
                    .WithMany(e => e.Notes)
                    .HasForeignKey(e => e.FKCategory)
                    .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<Note>()
                .HasMany(n => n.Tags)
                .WithMany(t => t.Notes)
                .UsingEntity(j => j
                .ToTable("NoteTag")
                .HasData
                (
                    new { NotesID = 1, TagsTagID = 1 },
                    new { NotesID = 2, TagsTagID = 2 }
                ));

        modelBuilder.Entity<Category>().HasData
            (
            new Category
            {
                CategoryID = 1,
                CategoryName = "testCategory1",
                CreatedDate = DateTime.Now
            },
            new Category
            {
                CategoryID = 2,
                CategoryName = "testCategory2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Tag>().HasData
            (
            new Tag
            {
                TagID = 1,
                TagName = "testTag1",
                CreatedDate = DateTime.Now
            },
            new Tag
            {
                TagID = 2,
                TagName = "testTag2",
                CreatedDate = DateTime.Now
            }
            );
        modelBuilder.Entity<Note>().HasData
            (
            new Note
            {
                ID = 1,
                Title = "testTitle1",
                Description = "testDescription1",
                FKCategory = 1,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            },
            new Note
            {
                ID = 2,
                Title = "testTitle2",
                Description = "testDescription2",
                FKCategory = 2,
                Deleted = false,
                CreatedDate = DateTime.Now,
                ChangedDate = DateTime.Now,
            }
            );
    }
}

Any suggestions?
Thanks in advance.

Initially I tried without the following if condition:

CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
    var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
    List<TagDTO> tagDTOs = new List<TagDTO>();
    if (tags.Count > 0)
    {
        foreach (var tag in tags)
        {
            TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
            tagDTOs.Add(tagDTO);
        }
    }
    createNoteDTO.Tags = tagDTOs;
}

But I got a different error:

I wanted to remove a tag form the following object using a PATCH request:
Note Object


来源: stackexchange

问:
How to checkout a git repository in Jenkins groovy script
In my Jenkins job, I am having Active Choices Reactive Parameter

My requirement is to clone a git repository and process one of the from that repository

In Jenkins, I have the credential for that git repository with required privileges

Can someone explain, how to clone the git repository in the Groovy script part of the Active Choices Reactive Parameter ?

ContentLicense: CC BY-SA 4.0


问:
Missing font using html2canvas and recharts
I'm trying to fix a bug that's driving me crazy... I have a chart from recharts in my React app, and export in to PNG file with html2canvas library. The issue is, it changes the font in chart for some reason... Anyone had issues with that?

I have a hook that returns exportAsImage function.
Exported image should have Proxima Nova font (it works in DOM), or at least sans-serif font, instead it has serif
Other exported elements have correct font, so it got me thinking it could be something with either html2canvas having issues with rendering SVGs, or recharts doing something weird

```<code>export const useExportAsImage = ({ fileName, backgroundColor, type = 'image/png' }) => {
  const refForExport = useRef();

  const saveAs = useCallback((uri, filename) => {
    const link = document.createElement('a');

    if (typeof link.download === 'string') {
      link.href = uri;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      window.open(uri);
    }
  }, []);

  const exportAsImage = useCallback(() => {
    if (typeof window === 'undefined') {
      return null;
    }

    const element = refForExport?.current;

    if (!element) {
      return null;
    }

    return html2canvas(element, {
      backgroundColor,
      scrollY: -window.scrollY,
      useCORS: true,
      onclone: (doc) => {
        // toggle HTML elements
        doc.querySelectorAll('.watermark, .png-hidden').forEach((element) => {
          element.toggleAttribute('hidden');
        });
        // svg sizing fix
        doc.querySelectorAll('svg').forEach((svg) => {
          svg.setAttribute('width', svg.getBoundingClientRect().width);
          svg.setAttribute('height', svg.getBoundingClientRect().height);
          svg.style.width = null;
          svg.style.height = null;
        });
      },
    }).then((canvas) => {
      saveAs(canvas.toDataURL(type, 1.0), fileName);
    });
  }, [fileName, backgroundColor, type, refForExport, saveAs]);

  return {
    exportAsImage,
    refForExport,
  };
};
</code>```

And the outcome image

Body:
I'm trying to fix a bug that's driving me crazy... I have a chart from recharts in my React app, and export in to PNG file with html2canvas library. The issue is, it changes the font in chart for some reason... Anyone had issues with that?

I have a hook that returns exportAsImage function.
Exported image should have Proxima Nova font (it works in DOM), or at least sans-serif font, instead it has serif
Other exported elements have correct font, so it got me thinking it could be something with either html2canvas having issues with rendering SVGs, or recharts doing something weird

export const useExportAsImage = ({ fileName, backgroundColor, type = 'image/png' }) => {
  const refForExport = useRef();

  const saveAs = useCallback((uri, filename) => {
    const link = document.createElement('a');

    if (typeof link.download === 'string') {
      link.href = uri;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      window.open(uri);
    }
  }, []);

  const exportAsImage = useCallback(() => {
    if (typeof window === 'undefined') {
      return null;
    }

    const element = refForExport?.current;

    if (!element) {
      return null;
    }

    return html2canvas(element, {
      backgroundColor,
      scrollY: -window.scrollY,
      useCORS: true,
      onclone: (doc) => {
        // toggle HTML elements
        doc.querySelectorAll('.watermark, .png-hidden').forEach((element) => {
          element.toggleAttribute('hidden');
        });
        // svg sizing fix
        doc.querySelectorAll('svg').forEach((svg) => {
          svg.setAttribute('width', svg.getBoundingClientRect().width);
          svg.setAttribute('height', svg.getBoundingClientRect().height);
          svg.style.width = null;
          svg.style.height = null;
        });
      },
    }).then((canvas) => {
      saveAs(canvas.toDataURL(type, 1.0), fileName);
    });
  }, [fileName, backgroundColor, type, refForExport, saveAs]);

  return {
    exportAsImage,
    refForExport,
  };
};

And the outcome image


问:
How to set a tablet device dimensions on a web browser
I am using flutter for developing an android app optimised (from frontend layout perspective) for a specific tablet (Galaxy tab A8).

Specs for tablet are -

Resolution: 1920x1080, 16:10 ratio (216 ppi density)

Dimensions: 9.72 inches x 6.37 inches

The issue is that I do not have the tablet physically and my machine is too low powered to run an emulator hence I need to rely on the chrome/web for development.

Now when I try to use the chrome dev tools and and plug in the resolution in the responsive settings, the screen I get has way more space than the actual device and hence I am not able to optimise specifically for that device.

I think the device dimensions has something to do with this issue but there is no option to set the dimensions for the browser window. How do I set the resolution in chrome dev tool so that it matches my device. Is there any conversion factor?


问:
Directory files as input in Snakemake
I plan to implement a pipeline where I search for specific transcripts at three different genomes to align the best hits and estimate some statistics by each.

To automatize the task in Snakemake, I run blat given the genomes sequence. Nonetheless, at some point, the pipeline needs to use the output transcripts from blat as the subsequent inputs. The problem is that I don't know which transcripts will be output by the checkpoint get_transcripts (see below). Does someone know how to read the directory containing the transcripts and use them as parallel inputs for the next steps? I tried to implement a function to read the path, but then the rule macse_align (see bellow) gets as input a list of files, and Snakemake does not iterate by transcripts name but instead tries to execute the rule using all the input at once.

I have checked similar post, but the solution usually use the list of file inside a directory as an input list for the next rule (e.g: use directories or all files in directories as input in snakemake)

Here is my code

```<code>
import os
import glob

configfile: 'config.yaml'

ROOT = os.path.abspath('genomes') + '/'

for d in ['pslx','info','genes','annotations']:
    os.makedirs(ROOT + d,exist_ok=True)

rule all:
    input:
        outgroups = expand(ROOT+config['FOCAL'] + '_{outgroup}.fa',outgroup=config['OUTGROUPS']),
        "genomes/genes/",
        [f+'/'+f.split('/')[-1] + '_NT.fa' for f in glob.glob('genomes/genes/*')]

rule parse_cds:
    input:
        ROOT + config['PREFIX'] + 'cds.all.fa.gz'
    output:
        ROOT + config['FOCAL'] + '_cds.fa'
    shell:
        """bioawk -c fastx '{{print ">"$name"\\n"$seq}}' {input} > {output}"""

rule pblat:
    input:
        cds    = ROOT + config['FOCAL'] + '_cds.fa',
        genome = ROOT + "{outgroup}.fa.gz"
    output:
        ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}.pslx"
    threads:
        config['THREADS']
    shell:
        """
            pblat {input.genome} {input.cds} -t=dna -q=dna -minIdentity=60 -fine -threads={threads} -out=pslx {output}
        """

rule pslx_reps:
    input:
        ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}.pslx"
    output:
        pslx=ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}_reps.pslx",
        psr=ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}_reps.psr"

    shell:
        "pslReps -nohead {input} {output.pslx} {output.psr}"

rule pslx_info:
    input:
        ROOT + "pslx/" + "human_{outgroup}_reps.pslx"
    output:
        fa   = ROOT + "human_{outgroup}.fa",
        info = ROOT + "info/" + "human_{outgroup}.info"
    shell:
        "perl scripts/pslx_to_fasta.pl --pslx {input} --fasta {output.fa} --info {output.info}"

checkpoint get_transcripts:
    input:
        outgroups = expand(ROOT+config['FOCAL'] + '_{outgroup}.fa',outgroup=config['OUTGROUPS']),
        infos     = expand(ROOT+'info/{outgroup}_back.info',outgroup=config['OUTGROUPS']),
        focal     = ROOT + config['FOCAL'] + '_cds.fa',
    output:
        directory(ROOT+'genes/')
    params:
        species_dict=config["OUTGROUPS"],
        distance=config['DISTANCE'],
        gtf = ROOT + config['GTF']
    script:
        'scripts/test.py'

# input function for rule macse_align, return paths to all files produced by the checkpoint 'somestep'
def list_transcripts(wildcards):
    checkpoint_output = checkpoints.get_transcripts.get(**wildcards).output[0]
    in_dir = glob.glob(checkpoint_output+'/*/*')
    return [i + "/" + i.split('/')[-1] + '.fa' for i in in_dir]

rule macse_align:
    input:
        list_transcripts
    output:
        [f+'/'+f.split('/')[-1] + '_NT.fa' for f in glob.glob('genomes/genes/*')]
    shell:
        """
            java -Xmx8G -jar scripts/macse_v2.06.jar -prog alignSequences -seq {input} -out_NT {output}
        """
</code>```

Title: Directory files as input in Snakemake

Body:
I plan to implement a pipeline where I search for specific transcripts at three different genomes to align the best hits and estimate some statistics by each.

To automatize the task in Snakemake, I run blat given the genomes sequence. Nonetheless, at some point, the pipeline needs to use the output transcripts from blat as the subsequent inputs. The problem is that I don't know which transcripts will be output by the checkpoint get_transcripts (see below). Does someone know how to read the directory containing the transcripts and use them as parallel inputs for the next steps? I tried to implement a function to read the path, but then the rule macse_align (see bellow) gets as input a list of files, and Snakemake does not iterate by transcripts name but instead tries to execute the rule using all the input at once.

I have checked similar post, but the solution usually use the list of file inside a directory as an input list for the next rule (e.g: use directories or all files in directories as input in snakemake)

Here is my code

import os
import glob

configfile: 'config.yaml'

ROOT = os.path.abspath('genomes') + '/'

for d in ['pslx','info','genes','annotations']:
    os.makedirs(ROOT + d,exist_ok=True)

rule all:
    input:
        outgroups = expand(ROOT+config['FOCAL'] + '_{outgroup}.fa',outgroup=config['OUTGROUPS']),
        "genomes/genes/",
        [f+'/'+f.split('/')[-1] + '_NT.fa' for f in glob.glob('genomes/genes/*')]

rule parse_cds:
    input:
        ROOT + config['PREFIX'] + 'cds.all.fa.gz'
    output:
        ROOT + config['FOCAL'] + '_cds.fa'
    shell:
        """bioawk -c fastx '{{print ">"$name"\\n"$seq}}' {input} > {output}"""

rule pblat:
    input:
        cds    = ROOT + config['FOCAL'] + '_cds.fa',
        genome = ROOT + "{outgroup}.fa.gz"
    output:
        ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}.pslx"
    threads:
        config['THREADS']
    shell:
        """
            pblat {input.genome} {input.cds} -t=dna -q=dna -minIdentity=60 -fine -threads={threads} -out=pslx {output}
        """

rule pslx_reps:
    input:
        ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}.pslx"
    output:
        pslx=ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}_reps.pslx",
        psr=ROOT + 'pslx/' + config['FOCAL'] + "_{outgroup}_reps.psr"

    shell:
        "pslReps -nohead {input} {output.pslx} {output.psr}"

rule pslx_info:
    input:
        ROOT + "pslx/" + "human_{outgroup}_reps.pslx"
    output:
        fa   = ROOT + "human_{outgroup}.fa",
        info = ROOT + "info/" + "human_{outgroup}.info"
    shell:
        "perl scripts/pslx_to_fasta.pl --pslx {input} --fasta {output.fa} --info {output.info}"

checkpoint get_transcripts:
    input:
        outgroups = expand(ROOT+config['FOCAL'] + '_{outgroup}.fa',outgroup=config['OUTGROUPS']),
        infos     = expand(ROOT+'info/{outgroup}_back.info',outgroup=config['OUTGROUPS']),
        focal     = ROOT + config['FOCAL'] + '_cds.fa',
    output:
        directory(ROOT+'genes/')
    params:
        species_dict=config["OUTGROUPS"],
        distance=config['DISTANCE'],
        gtf = ROOT + config['GTF']
    script:
        'scripts/test.py'

# input function for rule macse_align, return paths to all files produced by the checkpoint 'somestep'
def list_transcripts(wildcards):
    checkpoint_output = checkpoints.get_transcripts.get(**wildcards).output[0]
    in_dir = glob.glob(checkpoint_output+'/*/*')
    return [i + "/" + i.split('/')[-1] + '.fa' for i in in_dir]

rule macse_align:
    input:
        list_transcripts
    output:
        [f+'/'+f.split('/')[-1] + '_NT.fa' for f in glob.glob('genomes/genes/*')]
    shell:
        """
            java -Xmx8G -jar scripts/macse_v2.06.jar -prog alignSequences -seq {input} -out_NT {output}
        """


问:
my python code return an error because of the PyPDF2.PdfFileWriter func of PyPDF2 library
im having an issue with this line:

```<code>pdf_writer = PyPDF2.PdfFileWriter(strict=False)
</code>```

it return this:

Multiple definitions in dictionary at byte 0x1fd19 for key /Info
Multiple definitions in dictionary at byte 0x1fd25 for key /Info

Multiple definitions in dictionary at byte 0x1fd31 for key /Info

Multiple definitions in dictionary at byte 0x207d6 for key /Info

Multiple definitions in dictionary at byte 0x207e2 for key /Info

Multiple definitions in dictionary at byte 0x207ee for key /Info

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

Multiple definitions in dictionary at byte 0x23f8a for key /Info
Multiple definitions in dictionary at byte 0x23f96 for key /Info

Multiple definitions in dictionary at byte 0x23fa2 for key /Info

Multiple definitions in dictionary at byte 0x1e634 for key /Info

Multiple definitions in dictionary at byte 0x1e640 for key /Info

Multiple definitions in dictionary at byte 0x1e64c for key /Info

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

does someone have an idea of why is this happening?

code:

```<code>import os
import PyPDF2
import re
import math

def main():
    # Set the directory containing the PDF files
    inputDirectory = 'input_path'
    # Set the directory where the output PDF files will be saved
    outputDirectory = 'output_path'

    # Get a list of all of the PDF filenames in the input directory
    pdfFilenames = [f for f in os.listdir(inputDirectory) if f.endswith('.pdf')]

    pdf_dict = {}
    for file in pdfFilenames:
        if file.endswith('R.pdf'):
            pdf_dict[file] = file.replace('R.pdf', 'V.pdf')
        elif file.endswith('V.pdf'):
            pdf_dict[file.replace('V.pdf', 'R.pdf')] = file

    err = []
    l_fin = []
    fileAct = 0
    print("Début d'execution")
    for fileR, fileV in pdf_dict.items():
        # Ouvrez les fichiers PDF
        with open('CNI-R-V//' + fileR, 'rb') as file_handle_1, open('CNI-R-V//' + fileV, 'rb') as file_handle_2:
            # Créez des objets PDF à partir des fichiers
            try:
                pdf1 = PyPDF2.PdfFileReader(file_handle_1, strict=False)
                pdf2 = PyPDF2.PdfFileReader(file_handle_2, strict=False)
                # Créez un nouvel objet PDF
                pdf_writer = PyPDF2.PdfFileWriter(strict=False)
                # Ajoutez chaque page des fichiers PDF originaux au nouveau fichier
                for page_num in range(pdf1.getNumPages()):
                    pdf_writer.addPage(pdf1.getPage(page_num))
                for page_num in range(pdf2.getNumPages()):
                    pdf_writer.addPage(pdf2.getPage(page_num))
                # Créez le fichier PDF combiné en utilisant le nom des fichiers originaux
                with open(f'output/{fileR[:-5]}_combined.pdf', 'wb') as fh:
                    pdf_writer.write(fh)
                progressBar(len(pdf_dict), fileAct, err)
                fileAct += 1
            except:
                #print('erreur', fileR, fileV)
                err.append((fileR, fileV))
                progressBar(len(pdf_dict), fileAct, err)
                fileAct += 1
                continue

def progressBar(nbVal, actVal, err):
  percent = actVal/nbVal
  nEquals = math.floor(percent*20)
  bar = '=' * nEquals + ' ' * ( 20 - nEquals )

  print("\r", end='')
  print(f"[{bar}] {percent*100:.2f}%", end='')

  if percent == 1:
    print("\nFin d'execution")
    if err != []:
      print("Erreurs:")
      for el in err:
        print(el)

if __name__ == '__main__':
    main()
</code>```

My code should create a pdf from 2 other pdfs. but the line that is technically able to write a pdf doesn't work

Body:
im having an issue with this line:

pdf_writer = PyPDF2.PdfFileWriter(strict=False)

it return this:

Multiple definitions in dictionary at byte 0x1fd19 for key /Info
Multiple definitions in dictionary at byte 0x1fd25 for key /Info

Multiple definitions in dictionary at byte 0x1fd31 for key /Info

Multiple definitions in dictionary at byte 0x207d6 for key /Info

Multiple definitions in dictionary at byte 0x207e2 for key /Info

Multiple definitions in dictionary at byte 0x207ee for key /Info

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

Multiple definitions in dictionary at byte 0x23f8a for key /Info
Multiple definitions in dictionary at byte 0x23f96 for key /Info

Multiple definitions in dictionary at byte 0x23fa2 for key /Info

Multiple definitions in dictionary at byte 0x1e634 for key /Info

Multiple definitions in dictionary at byte 0x1e640 for key /Info

Multiple definitions in dictionary at byte 0x1e64c for key /Info

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

/Prev=0 in the trailer - assuming there is no previous xref table
/Prev=0 in the trailer - assuming there is no previous xref table

does someone have an idea of why is this happening?

code:

import os
import PyPDF2
import re
import math

def main():
    # Set the directory containing the PDF files
    inputDirectory = 'input_path'
    # Set the directory where the output PDF files will be saved
    outputDirectory = 'output_path'

    # Get a list of all of the PDF filenames in the input directory
    pdfFilenames = [f for f in os.listdir(inputDirectory) if f.endswith('.pdf')]

    pdf_dict = {}
    for file in pdfFilenames:
        if file.endswith('R.pdf'):
            pdf_dict[file] = file.replace('R.pdf', 'V.pdf')
        elif file.endswith('V.pdf'):
            pdf_dict[file.replace('V.pdf', 'R.pdf')] = file

    err = []
    l_fin = []
    fileAct = 0
    print("Début d'execution")
    for fileR, fileV in pdf_dict.items():
        # Ouvrez les fichiers PDF
        with open('CNI-R-V//' + fileR, 'rb') as file_handle_1, open('CNI-R-V//' + fileV, 'rb') as file_handle_2:
            # Créez des objets PDF à partir des fichiers
            try:
                pdf1 = PyPDF2.PdfFileReader(file_handle_1, strict=False)
                pdf2 = PyPDF2.PdfFileReader(file_handle_2, strict=False)
                # Créez un nouvel objet PDF
                pdf_writer = PyPDF2.PdfFileWriter(strict=False)
                # Ajoutez chaque page des fichiers PDF originaux au nouveau fichier
                for page_num in range(pdf1.getNumPages()):
                    pdf_writer.addPage(pdf1.getPage(page_num))
                for page_num in range(pdf2.getNumPages()):
                    pdf_writer.addPage(pdf2.getPage(page_num))
                # Créez le fichier PDF combiné en utilisant le nom des fichiers originaux
                with open(f'output/{fileR[:-5]}_combined.pdf', 'wb') as fh:
                    pdf_writer.write(fh)
                progressBar(len(pdf_dict), fileAct, err)
                fileAct += 1
            except:
                #print('erreur', fileR, fileV)
                err.append((fileR, fileV))
                progressBar(len(pdf_dict), fileAct, err)
                fileAct += 1
                continue

def progressBar(nbVal, actVal, err):
  percent = actVal/nbVal
  nEquals = math.floor(percent*20)
  bar = '=' * nEquals + ' ' * ( 20 - nEquals )

  print("\r", end='')
  print(f"[{bar}] {percent*100:.2f}%", end='')

  if percent == 1:
    print("\nFin d'execution")
    if err != []:
      print("Erreurs:")
      for el in err:
        print(el)

if __name__ == '__main__':
    main()

My code should create a pdf from 2 other pdfs. but the line that is technically able to write a pdf doesn't work


问:
How to enforce 1-[max n] relationship concurrency-safely? Semaphore table?
I have the following minimal example showing my problem:

I have a Person table, which has an (auto-increment) id as primary key and some information about the Person.

I have a Widget table, which likewise has an (auto-increment) id is primary key and some non-unique other information.

I have a Person_Widget table that maps Persons to Widget. This is supposed to be a 1-to-N relation ship where N must be max-limited to 5. A person should have at most 5 widgets (and can also have zero).

How can I enforce this in a concurrency-safe way?
If 2 transactions which intend to add Widgets to a Person both do a SELECT COUNT(...)... first to determine how many it might still insert, both can read 3 and determine "I can still insert two more widgets for this person", they might both insert two more, leading to a total of 7. This is a classic race condition.

Determining the current COUNT per person with a SELECT ... FOR UPDATE will not help because as determined in this thread, How do I lock on an InnoDB row that doesn't exist yet? , it is not reliable for locking non-existent rows, which will be a problem at least in the case where the Person has zero widgets before the two concurrent transactions start.

My solution: I add a num_widgets column to the person table. Before modifying Person_Widget entries for a person, a transaction must do SELECT num_widgets FROM Person WHERE Person.id=X FOR UPDATE;. The transaction will also keep this num_widges updated within the transaction so COUNT() isn't necessary anymore.

I.e. I am using the Person table as what I think is referred to as "semaphore table". Is this a bad practice?
Coming from a non-database concurrency programming background, this seems a straightforward and intuitive solution, but I've hardly seen anyone talk about it in my very limited MYSQL experience.

Before determining this question to be a duplicate, please consider that the other similar questions with the problem of limiting a table to X rows per key do not consider concurrency and locking at all. It's a whole different matter when concurrecny is considered.


问:
Display dynamic modal vuetify v-dialog in component Nuxtjs3
I want to open a dynamic modal on v-card onclick, each card clicked will change the content of the v-dialog.

In my case it open once and then nothing happen.

here the view

```<code><template>
    <div>
        <OrderComment :display="display"/>
        <h1 align="center">Commandes à Livrer</h1>
        <v-row>
            <!--    <Message></Message> -->
            <v-col lg="3" sm="6" v-for="order in orders.orders" v-bind:key="order.id" class="mt-16">
                <!--    </v-sheet>-->
                <v-card @click="displayModal(order.id)">
                    <v-card-title align="center" class="big-font">
                        <strong>{{ order.id }}</strong>
                    </v-card-title>
                    <v-divider class="mx-4"></v-divider>
                    <v-card-text>
                        {{ order.date_upd }}
                        <!--                        <OrderPartialCustomer :id_customer="order.id_customer" /> <br/>-->
                        <OrderPartialAddress :id_address_delivery="order.id_address_delivery"/>
                    </v-card-text>
                    <v-card-actions>
                        <v-btn @click="changeStatus(order.id)">
                            Passer en Livre
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-col>
        </v-row>

    </div>
</template>
</code>```

method in script

```<code>const display = ref(false);
function displayModal(id_order: String) {
    display.value = true;
    console.log(display.value)
}
</code>```

And my component

```<code><template v-slot:activator="{ on, attrs }">
    <div>
        <v-dialog
            v-model="props.display"
            width="500"
        >
            <v-card>
                <v-card-title class="text-h5 grey lighten-2">
                    Commentaires
                </v-card-title>

                <v-card-text>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </v-card-text>

                <v-divider></v-divider>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="danger"
                        text
                        @click="display = false"
                    >
                        Fermer
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </div>
</template>

<script lang="ts" setup>

    const props = defineProps({
        display: {
            type: Boolean,
            required: true,
        },
    })
</script>
</code>```

So finally it works only once. I don't know what is wrong or how i have to achieve it. I even don't know if i have to use v-slot:activator

Body:
I want to open a dynamic modal on v-card onclick, each card clicked will change the content of the v-dialog.

In my case it open once and then nothing happen.

here the view

<template>

        <OrderComment :display="display"/>

Commandes à Livrer

        <v-row>

            <v-col lg="3" sm="6" v-for="order in orders.orders" v-bind:key="order.id" class="mt-16">

                <v-card @click="displayModal(order.id)">
                    <v-card-title align="center" class="big-font">
                        {{ order.id }}
                    </v-card-title>
                    <v-divider class="mx-4"></v-divider>
                    <v-card-text>
                        {{ order.date_upd }}

                        <OrderPartialAddress :id_address_delivery="order.id_address_delivery"/>
                    </v-card-text>
                    <v-card-actions>
                        <v-btn @click="changeStatus(order.id)">
                            Passer en Livre
                        </v-btn>
                    </v-card-actions>
                </v-card>
            </v-col>
        </v-row>

</template>

method in script

const display = ref(false);
function displayModal(id_order: String) {
    display.value = true;
    console.log(display.value)
}

And my component

<template v-slot:activator="{ on, attrs }">

        <v-dialog
            v-model="props.display"
            width="500"
        >
            <v-card>
                <v-card-title class="text-h5 grey lighten-2">
                    Commentaires
                </v-card-title>

                <v-card-text>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </v-card-text>

                <v-divider></v-divider>

                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                        color="danger"
                        text
                        @click="display = false"
                    >
                        Fermer
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

</template>

So finally it works only once. I don't know what is wrong or how i have to achieve it. I even don't know if i have to use v-slot:activator


问:
Server Docker not found, Cannot connect to Docker daemon, Docker Machine executable is not specified
I'm learning Java and Spring Boot with a tutorial and there is a docker-compose.yml which I should run, but I get an error:

Error running 'docker-compose.yml: Compose Deployment': Server Docker not found

I opened Preferences and there really wasn't configured integration, so I tried to add one, but I got another error:

Cannot connect: Cannot connect to Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? (Details: [2] No such file or directory)

In the Docker Tools I found the Docker Machine executable is not specified. But I have no clue what  there should be and Google isn't helping me.

Could you please help me?


问:
Is it possible to give a link in a sankey diagram a grading colour in R?
I've made a sankey diagram to illustrate the change of a conclusion after an index event. The conclusion is noted as "Normal", "Borderline", or "Abnormal". I have changed the nodes of the diagram to reflect the conclusion by giving them either the color green, yellow or red. I would want to make the link from normal to borderline have gradient colour from green to yellow.

I managed to colour the different links between groups with a colour (e.g. from normal to borderline is yellow) by creating a vector called links$group and assigning a colour to the type of link (e.g. type_b is the link between normal to borderline and giving it a colour using the following function:

```<code>my_color <- 'd3.scaleOrdinal() .domain(["a", "b", "c", "type_a", "type_b", "type_c", "type_e"])
                                .range(["#9ACD32", "#FFD700", "#FF4500", "#CCCCCC", "#FFD700", "#FF4500", "#FF4500"])'
</code>```

This is informative but a little hard on the eyes. I think i need to use the RColorBrewer"package. I made the following code:

```<code>type_b_color <- ramp <- colorRamp(c("#9ACD32", "#FFD700"))
</code>```

and asigned it in the previous code as follows:

```<code>my_color <- 'd3.scaleOrdinal() .domain(["a", "b", "c", "type_a", "type_b", "type_c", "type_e"])
                                .range(["#9ACD32", "#FFD700", "#FF4500", "#CCCCCC", "type_b_color", "#FF4500",
</code>```

This does however remove the color completely instead of letting it be gradient from the normal node (green) to the borderline node (yellow).

Body:
I've made a sankey diagram to illustrate the change of a conclusion after an index event. The conclusion is noted as "Normal", "Borderline", or "Abnormal". I have changed the nodes of the diagram to reflect the conclusion by giving them either the color green, yellow or red. I would want to make the link from normal to borderline have gradient colour from green to yellow.

I managed to colour the different links between groups with a colour (e.g. from normal to borderline is yellow) by creating a vector called links$group and assigning a colour to the type of link (e.g. type_b is the link between normal to borderline and giving it a colour using the following function:

my_color <- 'd3.scaleOrdinal() .domain(["a", "b", "c", "type_a", "type_b", "type_c", "type_e"])
                                .range(["#9ACD32", "#FFD700", "#FF4500", "#CCCCCC", "#FFD700", "#FF4500", "#FF4500"])'

This is informative but a little hard on the eyes. I think i need to use the RColorBrewer"package. I made the following code:

type_b_color <- ramp <- colorRamp(c("#9ACD32", "#FFD700"))

and asigned it in the previous code as follows:

my_color <- 'd3.scaleOrdinal() .domain(["a", "b", "c", "type_a", "type_b", "type_c", "type_e"])
                                .range(["#9ACD32", "#FFD700", "#FF4500", "#CCCCCC", "type_b_color", "#FF4500",

This does however remove the color completely instead of letting it be gradient from the normal node (green) to the borderline node (yellow).


问:
Using Wix Pro-Gallery eventsListener
So I'm trying to use wix pro-gallery's react component on an older version 3.1.38 with its built in eventListener which is created with this according to their docs

```<code>const eventsListener = (eventName, eventData) =>
    console.log({eventName, eventData});
</code>```

It would output the following information such as click, hover, and mouse over events. What I am attempmting to do is run a function as soon as the click function (which looks like {eventName: 'ITEM_CLICKED', eventData: {}} in the console log) is fired, that another function runs.

Among other attemps I tried to run this with the code to no success:

```<code>    if(eventsListener(eventName) === "ITEM_CLICKED"){
      lightbox.loadAndOpen(0)
    }
</code>```

Title: Using Wix Pro-Gallery eventsListener

Body:
So I'm trying to use wix pro-gallery's react component on an older version 3.1.38 with its built in eventListener which is created with this according to their docs

const eventsListener = (eventName, eventData) =>
    console.log({eventName, eventData});

It would output the following information such as click, hover, and mouse over events. What I am attempmting to do is run a function as soon as the click function (which looks like {eventName: 'ITEM_CLICKED', eventData: {}} in the console log) is fired, that another function runs.

Among other attemps I tried to run this with the code to no success:

    if(eventsListener(eventName) === "ITEM_CLICKED"){
      lightbox.loadAndOpen(0)
    }


问:
Pytest async setup fixture isn't starting
I want to make a setup_and_clean fixture that will make it possible to clear database after each test to not clear it manually.
My code looks like this:

```<code>@pytest.mark.asyncio
class TestPersistentGrantRepository:

    @pytest.fixture
    async def setup_and_clean(self, connection):
        self.persistent_grant_repo = PersistentGrantRepository(connection)
        self.grants_to_delete = []
        yield
        for grant in self.grants_to_delete:
            await self.persistent_grant_repo.delete(
                data=grant.data,
                grant_type=grant.type)

    @pytest.mark.asyncio
    async def test_create_new_grant(self, setup_and_clean):
        await self.persistent_grant_repo.create(
            client_id='double_test',
            data='secret_code',
            user_id=2
        )

        grant = await self.persistent_grant_repo.get(grant_type='code', data='secret_code')

        self.grants_to_delete.append(grant)

        assert grant.subject_id == 2
        assert grant.data == 'secret_code'
</code>```

It gives me an error:

```<code>E       AttributeError: 'TestPersistentGrantRepository' object has no attribute 'persistent_grant_repo'
</code>```

This setup needs to be async because self.persistent_grant_repo.detele() needs to be awaited to work. When this setup function isn't async - the test passes, there's no error but there's a warning:

```<code>RuntimeWarning: coroutine 'PersistentGrantRepository.delete' was never awaited
</code>```

And database isn't clean after test. How can I make this async fixture start before tests?

Body:
I want to make a setup_and_clean fixture that will make it possible to clear database after each test to not clear it manually.
My code looks like this:

@pytest.mark.asyncio
class TestPersistentGrantRepository:

    @pytest.fixture
    async def setup_and_clean(self, connection):
        self.persistent_grant_repo = PersistentGrantRepository(connection)
        self.grants_to_delete = []
        yield
        for grant in self.grants_to_delete:
            await self.persistent_grant_repo.delete(
                data=grant.data,
                grant_type=grant.type)

    @pytest.mark.asyncio
    async def test_create_new_grant(self, setup_and_clean):
        await self.persistent_grant_repo.create(
            client_id='double_test',
            data='secret_code',
            user_id=2
        )

        grant = await self.persistent_grant_repo.get(grant_type='code', data='secret_code')

        self.grants_to_delete.append(grant)

        assert grant.subject_id == 2
        assert grant.data == 'secret_code'

It gives me an error:

E       AttributeError: 'TestPersistentGrantRepository' object has no attribute 'persistent_grant_repo'

This setup needs to be async because self.persistent_grant_repo.detele() needs to be awaited to work. When this setup function isn't async - the test passes, there's no error but there's a warning:

RuntimeWarning: coroutine 'PersistentGrantRepository.delete' was never awaited

And database isn't clean after test. How can I make this async fixture start before tests?


问:
Unable to install React-chartjs-2 in React Parcel Project
Very simply by using the following command, I am unable to install React-chartJs-2 module in my React Parcel project:

```<code>npm install --save chart.js react-chartjs-2
</code>```

After the installation when i started my project using (npm start), i getting the following error:

```<code>@parcel/core: Failed to resolve 'react-chartjs-2' from './src/pages/dashboard/quiz-detail.js'
</code>```

My package.json after installation is looks like:

```<code>    {
  "name": "quizcopy",
  "version": "1.0.0",
  "homepage": ".",
  "description": "",
  "source": "/src/index.html",
  "scripts": {
    "start": "parcel",
    "build": "parcel build src/index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@parcel/transformer-sass": "^2.7.0",
    "autoprefixer": "^10.4.8",
    "buffer": "^6.0.3",
    "parcel": "^2.7.0",
    "postcss": "^8.4.16",
    "process": "^0.11.10",
    "sass": "^1.54.9",
    "tailwindcss": "^3.1.8"
  },
  "dependencies": {
    "@headlessui/react": "^1.7.0",
    "@heroicons/react": "^2.0.10",
    "axios": "^0.27.2",
    "chart.js": "^4.1.1",
    "crypto-js": "^4.1.1",
    "dotenv": "^16.0.2",
    "js-cookie": "^3.0.1",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-chartjs-2": "^5.1.0",
    "react-datetime-picker": "^4.0.1",
    "react-dom": "^18.2.0",
    "react-export-table-to-excel": "^1.0.6",
    "react-google-recaptcha-v3": "^1.10.0",
    "react-hot-toast": "^2.4.0",
    "react-image-file-resizer": "^0.4.8",
    "react-quill": "^2.0.0",
    "react-router-dom": "^6.3.0",
    "react-transition-group": "^4.4.5",
    "read-excel-file": "^5.5.3",
    "swr": "^1.3.0"
  }
}
</code>```

Body:
Very simply by using the following command, I am unable to install React-chartJs-2 module in my React Parcel project:

npm install --save chart.js react-chartjs-2

After the installation when i started my project using (npm start), i getting the following error:

@parcel/core: Failed to resolve 'react-chartjs-2' from './src/pages/dashboard/quiz-detail.js'

My package.json after installation is looks like:

    {
  "name": "quizcopy",
  "version": "1.0.0",
  "homepage": ".",
  "description": "",
  "source": "/src/index.html",
  "scripts": {
    "start": "parcel",
    "build": "parcel build src/index.html"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@parcel/transformer-sass": "^2.7.0",
    "autoprefixer": "^10.4.8",
    "buffer": "^6.0.3",
    "parcel": "^2.7.0",
    "postcss": "^8.4.16",
    "process": "^0.11.10",
    "sass": "^1.54.9",
    "tailwindcss": "^3.1.8"
  },
  "dependencies": {
    "@headlessui/react": "^1.7.0",
    "@heroicons/react": "^2.0.10",
    "axios": "^0.27.2",
    "chart.js": "^4.1.1",
    "crypto-js": "^4.1.1",
    "dotenv": "^16.0.2",
    "js-cookie": "^3.0.1",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-chartjs-2": "^5.1.0",
    "react-datetime-picker": "^4.0.1",
    "react-dom": "^18.2.0",
    "react-export-table-to-excel": "^1.0.6",
    "react-google-recaptcha-v3": "^1.10.0",
    "react-hot-toast": "^2.4.0",
    "react-image-file-resizer": "^0.4.8",
    "react-quill": "^2.0.0",
    "react-router-dom": "^6.3.0",
    "react-transition-group": "^4.4.5",
    "read-excel-file": "^5.5.3",
    "swr": "^1.3.0"
  }
}


问:
expo-location (react native) app crashing on android after getting current location using the static method Location.getCurrentPositionAsync()
My expo managed (react native) app crushes on android  after getting the current location.

when i comment out the line  const locate = await Location.getCurrentPositionAsync() and other lines that depend on it ,the app does not crush..so am thinking its crushing on android because of the static method from expo-location

```<code>import React, { useState, useEffect } from "react"
import * as Location from "expo-location"
import { FontAwesome } from "@expo/vector-icons"
import MapView, { Marker } from "react-native-maps"

export const LocationScreen = ({ navigation }) => {

  const [location, setLocation] = useState(null)

 useEffect(() => {
    ;(async () => {
      const { status } = await Location.requestForegroundPermissionsAsync()
      if (status !== "granted") {
        setError("Permission to access location was denied")
        return
      }
      if (status === "granted") {
        const locate = await Location.getCurrentPositionAsync()
        setLocation(locate.coords)
      }
    })()
  }, [])

return (
 <View style={styles.mapContainer}>
          <MapView style={styles.map}>
            {location ? (
              <Marker coordinate={location} title="My location">
                <FontAwesome name="map-marker" size={40} color={colors.palette.map} />
              </Marker>
            ) : (
              <Text>{error}</Text>
            )}
          </MapView>
        </View>
)

}
</code>```

Am using

"expo": "^46.0.0",

"expo-location": "~14.3.0",

"react-native": "0.69.7",

"react": "18.0.0",

Body:
My expo managed (react native) app crushes on android  after getting the current location.

when i comment out the line  const locate = await Location.getCurrentPositionAsync() and other lines that depend on it ,the app does not crush..so am thinking its crushing on android because of the static method from expo-location

import React, { useState, useEffect } from "react"
import * as Location from "expo-location"
import { FontAwesome } from "@expo/vector-icons"
import MapView, { Marker } from "react-native-maps"

export const LocationScreen = ({ navigation }) => {

  const [location, setLocation] = useState(null)

 useEffect(() => {
    ;(async () => {
      const { status } = await Location.requestForegroundPermissionsAsync()
      if (status !== "granted") {
        setError("Permission to access location was denied")
        return
      }
      if (status === "granted") {
        const locate = await Location.getCurrentPositionAsync()
        setLocation(locate.coords)
      }
    })()
  }, [])

return (
 <View style={styles.mapContainer}>
          <MapView style={styles.map}>
            {location ? (
              <Marker coordinate={location} title="My location">
                <FontAwesome name="map-marker" size={40} color={colors.palette.map} />
              </Marker>
            ) : (
              <Text>{error}</Text>
            )}
          </MapView>
        </View>
)

}

Am using

"expo": "^46.0.0",

"expo-location": "~14.3.0",

"react-native": "0.69.7",

"react": "18.0.0",


问:
ManagementObjectSearcher and ManagementEventWatcher calls are canceled by Windows 11 with (0x80010002 (RPC_E_CALL_CANCELED))
As in the title - query in WPF .NET 5.0 app is canceled with message "Call was canceled by the message filter. (0x80010002 (RPC_E_CALL_CANCELED))"

It worked fine on Windows 10.
There are two instances which cause this issue

```<code>ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\\" + Environment.MachineName + @"\root\SecurityCenter2", "SELECT * FROM AntivirusProduct");
ManagementObjectCollection instances = searcher.Get();
</code>```

In code above it throws this exception on "Get()" instruction.

```<code>var watcher = new ManagementEventWatcher();
watcher.Query = new EventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3");
watcher.Start();
</code>```

In code above it throws this exception on "Start()" instruction.

I have no idea why it occurs as it never happened on Windows 10.
The worse thing is that after a few restarts of the computer the application started normally. From what I know this problem never occurred on any station with Windows 10.

Body:
As in the title - query in WPF .NET 5.0 app is canceled with message "Call was canceled by the message filter. (0x80010002 (RPC_E_CALL_CANCELED))"

It worked fine on Windows 10.
There are two instances which cause this issue

ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\\" + Environment.MachineName + @"\root\SecurityCenter2", "SELECT * FROM AntivirusProduct");
ManagementObjectCollection instances = searcher.Get();

In code above it throws this exception on "Get()" instruction.

var watcher = new ManagementEventWatcher();
watcher.Query = new EventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3");
watcher.Start();

In code above it throws this exception on "Start()" instruction.

I have no idea why it occurs as it never happened on Windows 10.
The worse thing is that after a few restarts of the computer the application started normally. From what I know this problem never occurred on any station with Windows 10.


问:
Vue 3 and Vite - useRoute
i use vite and vue. want to use useRoute, i want url request to interact with api, I get errors, and the router stops working in the application

Title: Vue 3 and Vite - useRoute


问:
how we can import mongdb collection documents to typesense in node js
I am having one issue, I searched whole google but couldn't find the answer.

What I want to do is, suppose I have mongo db collection "companies" with 500 records.
I have implemented Typesense for search engine, now what I want to do is when I start my application I need to import the existing collection (companies) records to Typesense collection (companies), I don't want to run find query to fetch all records in array and push to typesense collection.
I need a proper and better way to implement the replica of mongodb collection to typesense collection.


问:
Expression of type 'System.Decimal' cannot be used for parameter of type 'System.Object' of
I'm getting the below error messagE:

```<code>Expression of type 'System.Decimal' cannot be used for parameter of type 'System.Object' of method 'System.String Format(System.String, System.Object)'
</code>```

When using the below expression:

```<code>var expression = "iif({0}.HasValue, String.Format('{0:0.00}%', {0}.Value), 'NA')";
</code>```

This is used for setting Expression property of GridCalculatedColumn which will be added to my GridTableView:

```<code>var calculatedColumn = new GridCalculatedColumn
            {
                DataFields = dataFields,
                Expression = expression,
            };
</code>```

How to convert decimal expression to object expression here?

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the below error messagE:

Expression of type 'System.Decimal' cannot be used for parameter of type 'System.Object' of method 'System.String Format(System.String, System.Object)'

When using the below expression:

var expression = "iif({0}.HasValue, String.Format('{0:0.00}%', {0}.Value), 'NA')";

This is used for setting Expression property of GridCalculatedColumn which will be added to my GridTableView:

var calculatedColumn = new GridCalculatedColumn
            {
                DataFields = dataFields,
                Expression = expression,
            };

How to convert decimal expression to object expression here?

Thanks


问:
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1623fb680>
```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.optimizers import RMSprop
import matplotlib as plt
import tensorflow as tf
import numpy as np
import cv2
import os
import keras.utils as image
from matplotlib import pyplot as plt

train = ImageDataGenerator(rescale = 1/255)
validation = ImageDataGenerator(rescale = 1/255)
train_dataset = train.flow_from_directory('family/train/', target_size = (500,500), batch_size = 3 ,class_mode = 'binary')
validation_dataset = validation.flow_from_directory('family/validate/', target_size = (500,500), batch_size = 3 ,class_mode = 'binary')
train_dataset.class_indices
train_dataset.classes

from tensorflow.keras import layers , models
model=models.Sequential()

model.add(layers.Conv2D(16,(3,3),activation='relu', input_shape=(500,500,3)))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(32,(3,3),activation = 'relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64,(3,3),activation = 'relu'))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation = 'relu'))
model.add(layers.Dense(1, activation = 'sigmoid'))

model.compile(loss = 'binary_crossentropy',optimizer = RMSprop(learning_rate=0.001), metrics = ['accuracy'])
model.fit(train_dataset, steps_per_epoch = 3, epochs=30,validation_data=validation_dataset)

img = image.load_img("family/testing//test1.jpg")
plt.imshow(img)
plt.show()

X= image.img_to_array(img)
X=np.expand_dims(X,axis=0)
images = np.vstack([X])
val=model.predict(images)
if val == 1 :
    print(" one")
if val == 2 :

    print(" two")

</code>```

Found 10 images belonging to 3 classes.
Found 10 images belonging to 3 classes.

```<code>---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
/var/folders/5m/ybwkn1396vd8_rzf_7gpcv9c0000gq/T/ipykernel_7121/2750052911.py in <module>
     35
     36 model.compile(loss = 'binary_crossentropy',optimizer = RMSprop(learning_rate=0.001), metrics = ['accuracy'])
---> 37 model.fit(train_dataset, steps_per_epoch = 3, epochs=30,validation_data=validation_dataset)
     38
     39

~/opt/anaconda3/lib/python3.9/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

~/opt/anaconda3/lib/python3.9/site-packages/PIL/Image.py in open(fp, mode, formats)
   3145     for message in accept_warnings:
   3146         warnings.warn(message)
-> 3147     raise UnidentifiedImageError(
   3148         "cannot identify image file %r" % (filename if filename else fp)
   3149     )

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1623fb680>
</code>```

The model stops at the model.fit
It show me the above error I don't know why it is an image classifier. Inside the family folder there is a folder called train and validate.

Body:
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.optimizers import RMSprop
import matplotlib as plt
import tensorflow as tf
import numpy as np
import cv2
import os
import keras.utils as image
from matplotlib import pyplot as plt

train = ImageDataGenerator(rescale = 1/255)
validation = ImageDataGenerator(rescale = 1/255)
train_dataset = train.flow_from_directory('family/train/', target_size = (500,500), batch_size = 3 ,class_mode = 'binary')
validation_dataset = validation.flow_from_directory('family/validate/', target_size = (500,500), batch_size = 3 ,class_mode = 'binary')
train_dataset.class_indices
train_dataset.classes

from tensorflow.keras import layers , models
model=models.Sequential()

model.add(layers.Conv2D(16,(3,3),activation='relu', input_shape=(500,500,3)))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(32,(3,3),activation = 'relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64,(3,3),activation = 'relu'))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation = 'relu'))
model.add(layers.Dense(1, activation = 'sigmoid'))

model.compile(loss = 'binary_crossentropy',optimizer = RMSprop(learning_rate=0.001), metrics = ['accuracy'])
model.fit(train_dataset, steps_per_epoch = 3, epochs=30,validation_data=validation_dataset)

img = image.load_img("family/testing//test1.jpg")
plt.imshow(img)
plt.show()

X= image.img_to_array(img)
X=np.expand_dims(X,axis=0)
images = np.vstack([X])
val=model.predict(images)
if val == 1 :
    print(" one")
if val == 2 :

    print(" two")

Found 10 images belonging to 3 classes.
Found 10 images belonging to 3 classes.

---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
/var/folders/5m/ybwkn1396vd8_rzf_7gpcv9c0000gq/T/ipykernel_7121/2750052911.py in <module>
     35
     36 model.compile(loss = 'binary_crossentropy',optimizer = RMSprop(learning_rate=0.001), metrics = ['accuracy'])
---> 37 model.fit(train_dataset, steps_per_epoch = 3, epochs=30,validation_data=validation_dataset)
     38
     39

~/opt/anaconda3/lib/python3.9/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

~/opt/anaconda3/lib/python3.9/site-packages/PIL/Image.py in open(fp, mode, formats)
   3145     for message in accept_warnings:
   3146         warnings.warn(message)
-> 3147     raise UnidentifiedImageError(
   3148         "cannot identify image file %r" % (filename if filename else fp)
   3149     )

UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x1623fb680>

The model stops at the model.fit
It show me the above error I don't know why it is an image classifier. Inside the family folder there is a folder called train and validate.


问:
In the tensorflow, I want to call model prediction in the custom loss function but that results in unexpected tensor?
The code of custom loss function is here

```<code>class CustomLoss(tf.keras.losses.Loss):
  def __init__(self, anchor, positive):
    super().__init__()
    self.anchor=anchor
    self.positive=positive
  def convert(self, image):
    c_im=model(image.reshape(1, 160, 160, 3))
    print(c_im)
    c_im=tf.make_ndarray(c_im)
    return c_im/np.linalg.norm(c_im, ord=2)
  def call(self, y_true, y_pred):
    y_pred_c=tf.cast(y_pred, dtype=tf.float32)
    anchor, positive = self.convert(self.anchor), self.convert(self.positive)
    anchor, positive = tf.convert_to_tensor(anchor, dtype=tf.float32), tf.convert_to_tensor(positive, dtype=tf.float32)
    pos_d=tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_d=tf.reduce_sum(tf.square(tf.subtract(anchor, y_pred_c)), axis=-1)
    basic_l=tf.add(tf.subtract(pos_d, neg_d), 0.2)
    print(basic_l)
    del anchor
    del positive
    return tf.reduce_sum(tf.maximum(basic_l, 0), axis=None)
</code>```

And this is resulting tensor output: Tensor("CustomLoss/sequential/flatten/Reshape:0", shape=(1, 76800), dtype=float32). Why didn't it give the tensor array instead of "CustomLoss/sequential/flatten/Reshape:0"?

I tried these codes I have mentioned in the below.

Body:
The code of custom loss function is here

class CustomLoss(tf.keras.losses.Loss):
  def __init__(self, anchor, positive):
    super().__init__()
    self.anchor=anchor
    self.positive=positive
  def convert(self, image):
    c_im=model(image.reshape(1, 160, 160, 3))
    print(c_im)
    c_im=tf.make_ndarray(c_im)
    return c_im/np.linalg.norm(c_im, ord=2)
  def call(self, y_true, y_pred):
    y_pred_c=tf.cast(y_pred, dtype=tf.float32)
    anchor, positive = self.convert(self.anchor), self.convert(self.positive)
    anchor, positive = tf.convert_to_tensor(anchor, dtype=tf.float32), tf.convert_to_tensor(positive, dtype=tf.float32)
    pos_d=tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_d=tf.reduce_sum(tf.square(tf.subtract(anchor, y_pred_c)), axis=-1)
    basic_l=tf.add(tf.subtract(pos_d, neg_d), 0.2)
    print(basic_l)
    del anchor
    del positive
    return tf.reduce_sum(tf.maximum(basic_l, 0), axis=None)

And this is resulting tensor output: Tensor("CustomLoss/sequential/flatten/Reshape:0", shape=(1, 76800), dtype=float32). Why didn't it give the tensor array instead of "CustomLoss/sequential/flatten/Reshape:0"?

I tried these codes I have mentioned in the below.


问:
I have a question about MPI_Sendrecv sentence. Which is the meaning than dest an source process are the same?
In the below sentence the dest an source process are the same (0), what is the using of this?</p>
```<code>MPI_Sendrecv(A,1,filas_ciclicas,0,0,Alocal,k*N,MPI_DOUBLE,
                 0,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
</code>```

Body:
In the below sentence the dest an source process are the same (0), what is the using of this?

MPI_Sendrecv(A,1,filas_ciclicas,0,0,Alocal,k*N,MPI_DOUBLE,
                 0,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);


问:
Prevent nginx fill download bandwidth when work as reverse proxy

What I do :

I'm using nginx for reverse proxy for access to cloud bucket/workers large contents (+1GB files).

Problem is:

When 1 client try to download a file via this reverse proxy, my nginx server download bandwidth fill to it's 1Gbps even when clients maximum download speed is under 10 Mbps.

It seems that nginx try to download the complete large file then serve to clients.

How to ?

Decrease nginx download speed to exactly/near my clients speed.

For example : if 10 people download from nginx with a total of 500Mbps , nginx server download bandwidth increase to same/near 500Mbps and NOT fill to it's maximum bandwidth.

Here is the reverse/proxy server config:

```<code>server {
    server_name  my.domain.com;
    root /var/www/html/;
    set $bucket "123456.workers.com";
    sendfile on;

    location / {
        resolver 1.1.1.1;

        proxy_http_version     1.1;
        proxy_redirect off;
        proxy_set_header       Connection "";
        proxy_set_header       Authorization '';
        proxy_set_header       Host $bucket;
        proxy_ssl_server_name on;
        proxy_set_header       X-Real-IP $remote_addr;
        proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_hide_header      cf-ray;
        proxy_hide_header      Content-Disposition;
        proxy_hide_header      report-to;
        proxy_hide_header      server;
        proxy_hide_header      x-amz-id-2;
        proxy_hide_header      x-amz-request-id;
        proxy_hide_header      x-amz-meta-server-side-encryption;
        proxy_hide_header      x-amz-server-side-encryption;
        proxy_hide_header      Set-Cookie;
        proxy_ignore_headers   Set-Cookie;
        proxy_intercept_errors on;

        add_header             Cache-Control max-age=31536000;
        proxy_pass             https://$bucket; # without trailing slash
    }

    listen 80 default_server;
}
</code>```

Nginx Config :

```<code>thread_pool default threads=384;
worker_processes auto; #some last versions calculate it automatically
worker_rlimit_nofile 20000;
user www-data;

pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 10000;
    multi_accept on;
}

http {
    fastcgi_read_timeout 900;
    aio threads=default;
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=150000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    access_log off;
    sendfile on;
    sendfile_max_chunk 512k;
    types_hash_max_size 2048;
    tcp_nopush on;
    tcp_nodelay on;

    send_timeout 280;
    keepalive_requests 6000;

    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
</code>```

Body:
What I do :

I'm using nginx for reverse proxy for access to cloud bucket/workers large contents (+1GB files).

Problem is:

When 1 client try to download a file via this reverse proxy, my nginx server download bandwidth fill to it's 1Gbps even when clients maximum download speed is under 10 Mbps.

It seems that nginx try to download the complete large file then serve to clients.

How to ?

Decrease nginx download speed to exactly/near my clients speed.

For example : if 10 people download from nginx with a total of 500Mbps , nginx server download bandwidth increase to same/near 500Mbps and NOT fill to it's maximum bandwidth.

Here is the reverse/proxy server config:

server {
    server_name  my.domain.com;
    root /var/www/html/;
    set $bucket "123456.workers.com";
    sendfile on;

    location / {
        resolver 1.1.1.1;

        proxy_http_version     1.1;
        proxy_redirect off;
        proxy_set_header       Connection "";
        proxy_set_header       Authorization '';
        proxy_set_header       Host $bucket;
        proxy_ssl_server_name on;
        proxy_set_header       X-Real-IP $remote_addr;
        proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_hide_header      cf-ray;
        proxy_hide_header      Content-Disposition;
        proxy_hide_header      report-to;
        proxy_hide_header      server;
        proxy_hide_header      x-amz-id-2;
        proxy_hide_header      x-amz-request-id;
        proxy_hide_header      x-amz-meta-server-side-encryption;
        proxy_hide_header      x-amz-server-side-encryption;
        proxy_hide_header      Set-Cookie;
        proxy_ignore_headers   Set-Cookie;
        proxy_intercept_errors on;

        add_header             Cache-Control max-age=31536000;
        proxy_pass             https://$bucket; # without trailing slash
    }

    listen 80 default_server;
}

Nginx Config :

thread_pool default threads=384;
worker_processes auto; #some last versions calculate it automatically
worker_rlimit_nofile 20000;
user www-data;

pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 10000;
    multi_accept on;
}

http {
    fastcgi_read_timeout 900;
    aio threads=default;
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=150000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    access_log off;
    sendfile on;
    sendfile_max_chunk 512k;
    types_hash_max_size 2048;
    tcp_nopush on;
    tcp_nodelay on;

    send_timeout 280;
    keepalive_requests 6000;

    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


问:
Kubernetes Certificates missing
I have bare metal Kubernetes deployment on AWS EC2 server. After 1 year all the certificates expired.
Screenshot

I tried to renew all certificates and was successful to renew them but unfortunately i was still unable to update the services nor able to access their logs. While trying to resolve this issue unfortunately some certs are now missing as in the screenshot below and i am unable to resolve this now.
How can i add/renew the missing certificates? I cannot restart the nodes as that will wipe out redis cache. Unable to access the redis cache as well due to the missing certs to take backup.

Title: Kubernetes Certificates missing


问:
how to update line graph by choosing datetime and dropdown value in plotly dash
I want to update graph with selected range of time and also dropdown value , here i try to add drop down but its giving empty graph and not changing by selecting different value, also i am not sure how to add daterange selection here is my code if someone can help me to modify this for my required result , my required results are to update graph by choosing date range and also dropdown value.</p>
```<code>options1 = sorted(df1["a"].unique().tolist())
app.layout = html.Div(children=[
    html.H1(children='dashboard 1', style={'text-align': 'center'}),
    html.Div(children='deep', style={'text-align': 'center'}),

    html.Div([
        html.Label(['analysis:'],style={'font-weight': 'bold'}),
        dcc.Dropdown(
            id='dropdown',
            options=options1,
            value=options1[0],
            style={"width": "60%"}),

    html.Div(dcc.Graph(id='graph')),
        ]),

])

@app.callback(
    Output('graph', 'figure'),
    [Input(component_id='dropdown', component_property='value')]
)
def select_graph(value):
    df2=df1[df1['a_first']==value]
    fig = px.line(df2, x="Date_first", y="d_mean")
    return fig

if __name__ == '__main__':
    app.run_server(debug=False)
</code>```

Body:
I want to update graph with selected range of time and also dropdown value , here i try to add drop down but its giving empty graph and not changing by selecting different value, also i am not sure how to add daterange selection here is my code if someone can help me to modify this for my required result , my required results are to update graph by choosing date range and also dropdown value.

options1 = sorted(df1["a"].unique().tolist())
app.layout = html.Div(children=[
    html.H1(children='dashboard 1', style={'text-align': 'center'}),
    html.Div(children='deep', style={'text-align': 'center'}),

    html.Div([
        html.Label(['analysis:'],style={'font-weight': 'bold'}),
        dcc.Dropdown(
            id='dropdown',
            options=options1,
            value=options1[0],
            style={"width": "60%"}),

    html.Div(dcc.Graph(id='graph')),
        ]),

])

@app.callback(
    Output('graph', 'figure'),
    [Input(component_id='dropdown', component_property='value')]
)
def select_graph(value):
    df2=df1[df1['a_first']==value]
    fig = px.line(df2, x="Date_first", y="d_mean")
    return fig

if __name__ == '__main__':
    app.run_server(debug=False)


问:
default tab controller doesn't fit with Flutter list view builder scroll
I have a profile page in which theres a default tab controller.

```<code>Scaffold(
backgroundColor: Colors.lightGreen,
body: Column(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      CircleAvatar(),
      Text(
      "state.eu.username",
      style: TextStyle(fontSize: 25),
      ),
      DetailedTab(
      domainExpertise: domainExpertise,
      eu: eu,
      ),
    ],
  ));
</code>```

This is the tab view :

```<code> return DefaultTabController(
length: 4,
child: Column(
  children: [
    TabBar(
      labelPadding: const EdgeInsets.fromLTRB(8, 5, 8, 0),
      padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
      indicatorColor: Theme.of(context).primaryColor,
      labelColor: Theme.of(context).primaryColor,
      unselectedLabelColor:
          Theme.of(context).primaryColor.withOpacity(0.3),
      isScrollable: true,
      tabs: [
        Container(
          width: 120,
          child: Tab(
            text: 'Domain Expertise',)),
        Tab(
          text: 'Sessions'),
        Tab(
          text: 'Subscription',),
        Tab(
          text: 'Reviews',)
      ],
    ),
    Divider(
      height: 1,
      color: Theme.of(context).primaryColor.withOpacity(0.3),
    ),
    Container(
      height: 350,
      child: TabBarView(
        physics: BouncingScrollPhysics(),
        children: <Widget>[
        widget1,
        Padding(
          padding: const EdgeInsets.only(left: 20, right: 20, top: 30),
          child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: UpcomingSessionsListTile().upcomingSessionsListTile(currentUserName: widget.eu.username)),
        ),
        widget3,widget4,
        ],
      ),
    ),
  ],
));
</code>```

I wanted to solve this scroll : https://imgur.com/vMuz84B  thats happening but cant figure out whats wrong. widget2 returns a list view builder.I can't make out why tab controller is behaving like a stack and the scroll is going beneath it for it should just behave normal.  How can I resolve it so that the list don't scroll to the very top.

This is the List View Builder thats getting returned :

```<code> ListView.builder(
  shrinkWrap: true,
  physics: BouncingScrollPhysics(),
  itemCount: 20,
  itemBuilder: (((context, index) {
    return PreviousSessionCard(
      trailing: Container(
        height: 0,
        width: 0,
      ),
      sessionWith: "Session",
      sessionTime: "timeString",
      onTap: () {},
      padd: false,
    );
  })))
</code>```

And this would be the PreviousSessionCard :

```<code> class PreviousSessionCard extends StatelessWidget {
  final String sessionWith;
  final String sessionTime;
  final Function onTap;
  final bool padd;
  final String day;
  final Widget trailing;
  PreviousSessionCard(
      {Key key,
      this.sessionWith,
      this.sessionTime,
      this.onTap,
      this.padd = true,
      this.day,
      this.trailing})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(
          horizontal: padd ? 15.0 : 0.0, vertical: padd ? 6.0 : 0.0),
      child: ListTile(
        onTap: onTap,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
        tileColor: Colors.white,
        leading: CircleAvatar(
          backgroundColor: Colors.transparent,
          radius: 25,
          child: ClipOval(
              child: SvgPicture.asset(
            'assets/images/profile.svg',
            fit: BoxFit.fill,
          )),
        ),
        trailing: trailing ??
            Icon(Icons.arrow_forward_ios,
                size: 15.0, color: Theme.of(context).primaryColor),
        title: Text(sessionWith,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
              // color: Theme.of(context).primaryColor,
            )),
        subtitle: Text(
          sessionTime,
          style: TextStyle(
            fontWeight: FontWeight.w300,
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}

</code>```

Body:
I have a profile page in which theres a default tab controller.

Scaffold(
backgroundColor: Colors.lightGreen,
body: Column(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      CircleAvatar(),
      Text(
      "state.eu.username",
      style: TextStyle(fontSize: 25),
      ),
      DetailedTab(
      domainExpertise: domainExpertise,
      eu: eu,
      ),
    ],
  ));

This is the tab view :

 return DefaultTabController(
length: 4,
child: Column(
  children: [
    TabBar(
      labelPadding: const EdgeInsets.fromLTRB(8, 5, 8, 0),
      padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
      indicatorColor: Theme.of(context).primaryColor,
      labelColor: Theme.of(context).primaryColor,
      unselectedLabelColor:
          Theme.of(context).primaryColor.withOpacity(0.3),
      isScrollable: true,
      tabs: [
        Container(
          width: 120,
          child: Tab(
            text: 'Domain Expertise',)),
        Tab(
          text: 'Sessions'),
        Tab(
          text: 'Subscription',),
        Tab(
          text: 'Reviews',)
      ],
    ),
    Divider(
      height: 1,
      color: Theme.of(context).primaryColor.withOpacity(0.3),
    ),
    Container(
      height: 350,
      child: TabBarView(
        physics: BouncingScrollPhysics(),
        children: <Widget>[
        widget1,
        Padding(
          padding: const EdgeInsets.only(left: 20, right: 20, top: 30),
          child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: UpcomingSessionsListTile().upcomingSessionsListTile(currentUserName: widget.eu.username)),
        ),
        widget3,widget4,
        ],
      ),
    ),
  ],
));

I wanted to solve this scroll : https://imgur.com/vMuz84B  thats happening but cant figure out whats wrong. widget2 returns a list view builder.I can't make out why tab controller is behaving like a stack and the scroll is going beneath it for it should just behave normal.  How can I resolve it so that the list don't scroll to the very top.

This is the List View Builder thats getting returned :

 ListView.builder(
  shrinkWrap: true,
  physics: BouncingScrollPhysics(),
  itemCount: 20,
  itemBuilder: (((context, index) {
    return PreviousSessionCard(
      trailing: Container(
        height: 0,
        width: 0,
      ),
      sessionWith: "Session",
      sessionTime: "timeString",
      onTap: () {},
      padd: false,
    );
  })))

And this would be the PreviousSessionCard :

 class PreviousSessionCard extends StatelessWidget {
  final String sessionWith;
  final String sessionTime;
  final Function onTap;
  final bool padd;
  final String day;
  final Widget trailing;
  PreviousSessionCard(
      {Key key,
      this.sessionWith,
      this.sessionTime,
      this.onTap,
      this.padd = true,
      this.day,
      this.trailing})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(
          horizontal: padd ? 15.0 : 0.0, vertical: padd ? 6.0 : 0.0),
      child: ListTile(
        onTap: onTap,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
        tileColor: Colors.white,
        leading: CircleAvatar(
          backgroundColor: Colors.transparent,
          radius: 25,
          child: ClipOval(
              child: SvgPicture.asset(
            'assets/images/profile.svg',
            fit: BoxFit.fill,
          )),
        ),
        trailing: trailing ??
            Icon(Icons.arrow_forward_ios,
                size: 15.0, color: Theme.of(context).primaryColor),
        title: Text(sessionWith,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
              // color: Theme.of(context).primaryColor,
            )),
        subtitle: Text(
          sessionTime,
          style: TextStyle(
            fontWeight: FontWeight.w300,
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}


问:
Uvicorn gives "access is denied" in Anaconda Prompt
Problem

I have two conda virtual environments. One can run uvicorn commands such as uvicorn main:app --reload to run the example code from the FastAPI tutorial, but the other environment returns Access is denied. for each uvicorn command.

What I have tried

The second (not working one) has the exact same versions of uvicorn, fastapi, and python installed and I'm using the same anaconda prompt. Hence it's not a problem of access rights on the underlying folder or admin rights, because in that case both environments should not work in the same prompts (right?).

I'm looking for a difference in both environments, but given that only fastapi and uvicorn are required to run Fast API code, I'm not sure what to try next.

Question

Are there additional requirements for running a FastAPI app, beyond the fastapi and uvicorn packages that could cause this problem and/or are there perhaps other matters I should look into?


问:
How to add Bundle Identifier correctly to my app in XCode?
I have created App ID Prefix and Bundle ID in AppStore and I am wondering if that together forms the bundle identifier like so:

```<code>[AppIDPrefix].[com.myapp.extension]
</code>```

Furthermore, when I add it like that in XCode -> Target app -> General -> Bundle Identifier, it automatically adds a dash (-) before the identifier. Why?

FYI App ID Prefix looks something like this: 8HJ23V44G5

Also, I am not sure if SKU should be added anywhere in XCode or not. Please let me know.

Body:
I have created App ID Prefix and Bundle ID in AppStore and I am wondering if that together forms the bundle identifier like so:

[AppIDPrefix].[com.myapp.extension]

Furthermore, when I add it like that in XCode -> Target app -> General -> Bundle Identifier, it automatically adds a dash (-) before the identifier. Why?

FYI App ID Prefix looks something like this: 8HJ23V44G5

Also, I am not sure if SKU should be added anywhere in XCode or not. Please let me know.


问:
How to use property variables in ListElement
I am trying to build an ListModel with Listelements by using pre-defined variables in qml.
The error i am getting is "QQmlComponent: Component is not ready", "cannot use script for property value"

On my code, i removed the css or qss edits on purpose, to show code clear

I want to use this property

```<code>property string cellTemperature: "0"
</code>```

in this ListModel

```<code>ListModel {
id: mainValuesList
ListElement { name: "CELL"; listValue: cellTemperature ; sdValue: "_ _SD"}
}
</code>```

and then create a GridView

```<code>GridView {
id: mainValuesGrid
anchors.fill: parent
model: mainValuesList
delegate: Rectangle {

    width: 120
    height: 80
    color: "transparent"

    Text{
        color: "#4A4A4A"
        text: name
    }

    Text{
        color: "#4A4A4A"
        text: listValue
    }

    Text{
        color: "#4A4A4A"
        text: sdValue
    }
  }
}
</code>```

I tried to use
QT_TR_NOOP(cellTemperature)
qsTr(cellTemperature)

But they both did not work. Here are the threads i focused but could not find a solution

Why can ListElement add arbitrary properties?

ListElement fields as properties?

Get properties of QML ListElement

Body:
I am trying to build an ListModel with Listelements by using pre-defined variables in qml.
The error i am getting is "QQmlComponent: Component is not ready", "cannot use script for property value"

On my code, i removed the css or qss edits on purpose, to show code clear

I want to use this property

property string cellTemperature: "0"

in this ListModel

ListModel {
id: mainValuesList
ListElement { name: "CELL"; listValue: cellTemperature ; sdValue: "_ _SD"}
}

and then create a GridView

GridView {
id: mainValuesGrid
anchors.fill: parent
model: mainValuesList
delegate: Rectangle {

    width: 120
    height: 80
    color: "transparent"

    Text{
        color: "#4A4A4A"
        text: name
    }

    Text{
        color: "#4A4A4A"
        text: listValue
    }

    Text{
        color: "#4A4A4A"
        text: sdValue
    }
  }
}

I tried to use
QT_TR_NOOP(cellTemperature)
qsTr(cellTemperature)

But they both did not work. Here are the threads i focused but could not find a solution

Why can ListElement add arbitrary properties?

ListElement fields as properties?

Get properties of QML ListElement


问:
How Can I validate my uploads on videos only in mp4 or mkv extension?
I want to validate the files to upload only in video formats like mp4 or mkv files only, I want to make sure the user is uploading video no anything else using ajax I want valid the FileInput is video not anything else, and if this file not video then show alert in error</p>
```<code><div class="form-group">
                            <label for="" class="control-label"><b>Upload Video</b></label>
                            <input type="file" class="form-control form-control-sm" name="vid" onchange="displayVID(this,$(this))">
                        </div>

function displayVID(input,_this) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#vid-field').html("<source src='"+e.target.result+"'>");
                console.log(e.target.result)
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
    function displayImg(input,_this) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#vid-field').attr('poster', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
$('#manage-upload').submit(function(e){
        e.preventDefault()
        start_load()
        $.ajax({
            url:'ajax.php?action=save_upload',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success:function(resp){
                if(resp == 1){
                    alert_toast('<i class="fa fa-check text-white"></i> Video successfully Upload.',"success");
                    setTimeout(function(){
                        location.reload()
                    },750)
                }
            }
        })
    })
</code>```

Body:
I want to validate the files to upload only in video formats like mp4 or mkv files only, I want to make sure the user is uploading video no anything else using ajax I want valid the FileInput is video not anything else, and if this file not video then show alert in error

                            Upload Video
                            <input type="file" class="form-control form-control-sm" name="vid" onchange="displayVID(this,$(this))">

function displayVID(input,_this) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#vid-field').html("<source src='"+e.target.result+"'>");
                console.log(e.target.result)
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
    function displayImg(input,_this) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#vid-field').attr('poster', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
$('#manage-upload').submit(function(e){
        e.preventDefault()
        start_load()
        $.ajax({
            url:'ajax.php?action=save_upload',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success:function(resp){
                if(resp == 1){
                    alert_toast(' Video successfully Upload.',"success");
                    setTimeout(function(){
                        location.reload()
                    },750)
                }
            }
        })
    })


问:
Kedro register dataset from a board from pins package
For my project I want to use a combination of kedro for the pipeline orchestration and pins for data and model versioning. I have some data which I stored on a board from the pins package.
As I have multiple versions,

I am not sure how to specify the catalog.yml file. In a simple Python script I would simply write:

```<code>import pins
board = pins.board_folder("/path/to/my/folder/")
board.pin_read("df_all")
</code>```

and would automatically get the latest version. Is it possible to register the latest version of the dataset in the catalog.yml without 'knowing' or storing the latest hash?
How would the path in the YAML then look like?
Or maybe there is an elegant way to use a MemoryDataSet?

Thank you very much in advance!

Body:
For my project I want to use a combination of kedro for the pipeline orchestration and pins for data and model versioning. I have some data which I stored on a board from the pins package.
As I have multiple versions,

I am not sure how to specify the catalog.yml file. In a simple Python script I would simply write:

import pins
board = pins.board_folder("/path/to/my/folder/")
board.pin_read("df_all")

and would automatically get the latest version. Is it possible to register the latest version of the dataset in the catalog.yml without 'knowing' or storing the latest hash?
How would the path in the YAML then look like?
Or maybe there is an elegant way to use a MemoryDataSet?

Thank you very much in advance!