问:
Pass a task to a task property
So I have a task, that takes a path and opens the file.

```<code>private async Task OpenFileAsync(string strFilePath)
{
     doTheOpenThing.
}
</code>```

Until now this was a void function and everything was ok, but know we need to support big files and we wanted to do the open file using other thread, in order to not block the UI Thread.

I use reactiveui in my application and I have a method that listens to tasks and runs them as they come.

```<code>        _sessionContext.WhenAnyValue(t => t.NotifyNewTreadTask).Where(t => t != null).Subscribe(t => DoAsyncTask(t));
</code>```

Where

```<code>   private async void DoAsyncTask(Task task)
        {
            if (task != null)
            {
                await DoThreadAction(() => task);
            }

            _sessionContext.NotifyNewTreadTask = null;
        }
</code>```

And DoThreadAction just runs the task

```<code>await Task.Run(async () => await action.Invoke());
</code>```

Now my problem is on assigning NotifyNewTreadTask.

Whenever I do NotifyNewTreadTask = OpenFileAsync(path);

It just runs the OpenFileAsync task. How can pass OpenFileASync task to NotifyNewTreadTask without running it.

```<code>Task? NotifyNewTreadTask { get; set; } NotifyNewTreadTask is a property.
</code>```

答:
You should use a command to execute OpenFileAsync asynchronously instead of calling it in the Subscribe method:

```<code> public class ViewModel
 {
    public ViewModel()
    {
        OpenFile = ReactiveCommand.CreateFromTask<string>(OpenFileAsync);
    }

    public ReactiveCommand<string, Unit> OpenFile { get; }

    private async Task OpenFileAsync(string strFilePath)
    {
        //...
    }
}
</code>```

Instead of setting some property, you could the execute then task directly and await it:

```<code>await OpenFile.Execute("file.txt");
</code>```

You may of course also invoke it as a result of some property being set:

```<code>this.WhenAnyValue(x => x.SomeStringProperty).InvokeCommand(OpenFile);
</code>```

Setting a Task property to a Task to cause another Task to get executed seems a bit clumsy though.

Title: Pass a task to a task property

Body:
So I have a task, that takes a path and opens the file.

private async Task OpenFileAsync(string strFilePath)
{
     doTheOpenThing.
}

Until now this was a void function and everything was ok, but know we need to support big files and we wanted to do the open file using other thread, in order to not block the UI Thread.

I use reactiveui in my application and I have a method that listens to tasks and runs them as they come.

        _sessionContext.WhenAnyValue(t => t.NotifyNewTreadTask).Where(t => t != null).Subscribe(t => DoAsyncTask(t));

Where

   private async void DoAsyncTask(Task task)
        {
            if (task != null)
            {
                await DoThreadAction(() => task);
            }

            _sessionContext.NotifyNewTreadTask = null;
        }

And DoThreadAction just runs the task

await Task.Run(async () => await action.Invoke());

Now my problem is on assigning NotifyNewTreadTask.

Whenever I do NotifyNewTreadTask = OpenFileAsync(path);

It just runs the OpenFileAsync task. How can pass OpenFileASync task to NotifyNewTreadTask without running it.

Task? NotifyNewTreadTask { get; set; } NotifyNewTreadTask is a property.

Body:
You should use a command to execute OpenFileAsync asynchronously instead of calling it in the Subscribe method:

 public class ViewModel
 {
    public ViewModel()
    {
        OpenFile = ReactiveCommand.CreateFromTask<string>(OpenFileAsync);
    }

    public ReactiveCommand<string, Unit> OpenFile { get; }

    private async Task OpenFileAsync(string strFilePath)
    {
        //...
    }
}

Instead of setting some property, you could the execute then task directly and await it:

await OpenFile.Execute("file.txt");

You may of course also invoke it as a result of some property being set:

this.WhenAnyValue(x => x.SomeStringProperty).InvokeCommand(OpenFile);

Setting a Task property to a Task to cause another Task to get executed seems a bit clumsy though.


来源: stackexchange

问:
Export Datatable to Word Document With Page Numbers using Open XML
My requirement is : Exporting a dynamic DataTable to Word document with Page Numbers
We need to use Open XML to achieve this.
I have code to export Datatable to Word. And also to insert page numbers.

I got Below code code to export datatable

```<code>public void CreateWordtable(string filename,DataTable data)
{
    WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
    MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
    mainDocPart.Document = new Document();
    Body body = new Body();
    mainDocPart.Document.Append(body);
    //rinks@::creating new table

    DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
    for (int i = 0; i < data.Rows.Count; ++i)
    {
        TableRow row = new TableRow();
        for (int j = 0; j < data.Columns.Count; j++)
        {
            TableCell cell = new TableCell();
            cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
            cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
            row.Append(cell);
        }
        table.Append(row);
    }
    body.Append(table);
    doc.MainDocumentPart.Document.Save();
    doc.Dispose();
}
</code>```

And below code is to insert page numbers in a word document

```<code>private static void AddPageNumberFooters(WordprocessingDocument parent)
{
    string documentPath = @"D:\EmptyDoc.docx";
    using (WordprocessingDocument package =
        WordprocessingDocument.Open(documentPath, true))
    {
        var mainDocumentPart = parent.AddMainDocumentPart();
        GenerateMainDocumentPart().Save(mainDocumentPart);

        var documentSettingsPart =
            mainDocumentPart.AddNewPart
            <DocumentSettingsPart>("rId1");

        GenerateDocumentSettingsPart().Save(documentSettingsPart);

        var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
        GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);

        var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
        GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
    }
}

private static Document GenerateMainDocumentPart()
{
    var element =
        new Document(
            new Body(
                new Paragraph(
                    new Run(
                        new Text("Page 1 content"))
                ),
                new Paragraph(
                    new Run(
                        new Break() { Type = BreakValues.Page })
                ),
                new Paragraph(
                    new Run(
                        new LastRenderedPageBreak(),
                        new Text("Page 2 content"))
                ),
                new Paragraph(
                    new Run(
                        new Break() { Type = BreakValues.Page })
                ),
                new SectionProperties(
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.First,
                        Id = "rId1"
                    },
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.Even,
                        Id = "rId2"
                    },
                    new PageMargin()
                    {
                        Top = 1440,
                        Right = (UInt32Value)1440UL,
                        Bottom = 1440,
                        Left = (UInt32Value)1440UL,
                        Header = (UInt32Value)720UL,
                        Footer = (UInt32Value)720UL,
                        Gutter = (UInt32Value)0UL
                    },
                    new TitlePage()
                )));

    return element;
}

private static Header GeneratePageHeaderPart(string HeaderText)
{
    var element =
        new Header(
            new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId() { Val = "Header" }),
                new Run(
                    new Text(HeaderText))
            ));

    return element;
}
</code>```

My problem is, I have combine above both methods to export data along with page numbers.
if we know there are 2 pages in the word document, i can insert 2 FooterParts.
But i don't know how many pages will be created after exporting the data.

答:
try the following code to automatically add page numbers:</p>

```<code>  private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
    {
        FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
        if (footerPart1 == null)
        {
            footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
        }

        var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
        // Get SectionProperties and set HeaderReference and FooterRefernce with new Id
        SectionProperties sectionProperties1 = new SectionProperties();
        FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
        sectionProperties1.Append(footerReference2);
        package.MainDocumentPart.Document.Body.Append(sectionProperties1);

        Footer footer1 = new Footer();

        var r = new Run();
        PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right,
            RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
            Leader = AbsolutePositionTabLeaderCharValues.None };

        r.Append(positionalTab2);
        paragraph2.Append(r);

        r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the page number dynamically ***
              new SimpleField() { Instruction = "PAGE" },
              new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the number of pages dynamically ***
              new SimpleField() { Instruction = "NUMPAGES" });
        paragraph2.Append(r);

        footer1.Append(paragraph2);

        footerPart1.Footer = footer1;
        return relationshipId;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My requirement is : Exporting a dynamic DataTable to Word document with Page Numbers
We need to use Open XML to achieve this.
I have code to export Datatable to Word. And also to insert page numbers.

I got Below code code to export datatable

public void CreateWordtable(string filename,DataTable data)
{
    WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
    MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
    mainDocPart.Document = new Document();
    Body body = new Body();
    mainDocPart.Document.Append(body);
    //rinks@::creating new table

    DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
    for (int i = 0; i < data.Rows.Count; ++i)
    {
        TableRow row = new TableRow();
        for (int j = 0; j < data.Columns.Count; j++)
        {
            TableCell cell = new TableCell();
            cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
            cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
            row.Append(cell);
        }
        table.Append(row);
    }
    body.Append(table);
    doc.MainDocumentPart.Document.Save();
    doc.Dispose();
}

And below code is to insert page numbers in a word document

private static void AddPageNumberFooters(WordprocessingDocument parent)
{
    string documentPath = @"D:\EmptyDoc.docx";
    using (WordprocessingDocument package =
        WordprocessingDocument.Open(documentPath, true))
    {
        var mainDocumentPart = parent.AddMainDocumentPart();
        GenerateMainDocumentPart().Save(mainDocumentPart);

        var documentSettingsPart =
            mainDocumentPart.AddNewPart
            <DocumentSettingsPart>("rId1");

        GenerateDocumentSettingsPart().Save(documentSettingsPart);

        var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
        GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);

        var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
        GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
    }
}

private static Document GenerateMainDocumentPart()
{
    var element =
        new Document(
            new Body(
                new Paragraph(
                    new Run(
                        new Text("Page 1 content"))
                ),
                new Paragraph(
                    new Run(
                        new Break() { Type = BreakValues.Page })
                ),
                new Paragraph(
                    new Run(
                        new LastRenderedPageBreak(),
                        new Text("Page 2 content"))
                ),
                new Paragraph(
                    new Run(
                        new Break() { Type = BreakValues.Page })
                ),
                new SectionProperties(
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.First,
                        Id = "rId1"
                    },
                    new FooterReference()
                    {
                        Type = HeaderFooterValues.Even,
                        Id = "rId2"
                    },
                    new PageMargin()
                    {
                        Top = 1440,
                        Right = (UInt32Value)1440UL,
                        Bottom = 1440,
                        Left = (UInt32Value)1440UL,
                        Header = (UInt32Value)720UL,
                        Footer = (UInt32Value)720UL,
                        Gutter = (UInt32Value)0UL
                    },
                    new TitlePage()
                )));

    return element;
}

private static Header GeneratePageHeaderPart(string HeaderText)
{
    var element =
        new Header(
            new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId() { Val = "Header" }),
                new Run(
                    new Text(HeaderText))
            ));

    return element;
}

My problem is, I have combine above both methods to export data along with page numbers.
if we know there are 2 pages in the word document, i can insert 2 FooterParts.
But i don't know how many pages will be created after exporting the data.

Body:
try the following code to automatically add page numbers:

  private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
    {
        FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
        if (footerPart1 == null)
        {
            footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
        }

        var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
        // Get SectionProperties and set HeaderReference and FooterRefernce with new Id
        SectionProperties sectionProperties1 = new SectionProperties();
        FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
        sectionProperties1.Append(footerReference2);
        package.MainDocumentPart.Document.Body.Append(sectionProperties1);

        Footer footer1 = new Footer();

        var r = new Run();
        PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right,
            RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
            Leader = AbsolutePositionTabLeaderCharValues.None };

        r.Append(positionalTab2);
        paragraph2.Append(r);

        r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the page number dynamically ***
              new SimpleField() { Instruction = "PAGE" },
              new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
              // *** Adaptation: This will output the number of pages dynamically ***
              new SimpleField() { Instruction = "NUMPAGES" });
        paragraph2.Append(r);

        footer1.Append(paragraph2);

        footerPart1.Footer = footer1;
        return relationshipId;
    }

ContentLicense: CC BY-SA 4.0


问:
CodeIgniter - Upload file using a form
I am a bit desperate already, because I am programming a project in CodeIgniter which is an Online store of food products. The problem is that when I have to create the product, I have a form in which the administrator is asked to enter, the name, brand, description, price, VAT, category, etc. of the product, and in between, there is another field that is the product image. Well, when I fill in that form and submit it, the product is added to the database and everything works great, except that the product image is not copied from my hard drive to the server folder.

I'm using:
  PHP 7.3.9
  MySQL 5.7.26
  CodeIgniter 3.1.8

I put the code of this form (the view), which I have already changed so many times, that there must be errors excessively:

```<code><div class="container">
<?php if (isset($error)) {?>
    <div class="alert alert-danger">
        <?php echo validation_errors('<div class="container"><b><ul><li>','</li></ul></b></div>') ?>
    </div>
<?php }?>
<div class="panel panel-default">

    <div class="panel-body">
        <h3 style='margin-left: 4em'>Crear Producto</h3>
        <h6 style='margin-left: 8em'>Rellena los siguientes campos con los datos del producto y una vez termines pulsa el botón.</h6>
        <hr>
        <?php echo form_open_multipart('Inicio/verificarProducto'); ?>
        <div class="row">

            <div style='margin-left: 6em' class="container">
                <div class="col-xs-3">
                    <div class="form-group">
                        <label for="user">Nombre *</label>
                        <input type="text" name="nombre" value="<?=set_value('nombre')?>" class="form-control" id="nombre" placeholder="Nombre del Producto" >
                    </div>
                </div>
                <div class="col-xs-3">
                    <div class="form-group">
                        <label for="pass">Descripción *</label>
                        <input type="text" name="descripcion" value="<?=set_value('descripcion')?>" class="form-control" id="descripcion" placeholder="Descripción del Producto" >
                    </div>
                </div>
            </div></div><hr>

            <div style='margin-left: 6em' class="container">

                <div class="row">
                 <div class="col-xs-4">
                    <div class="form-group">
                            <label for="image">Imagen *</label>

                            <!--El name del campo tiene que ser si o si "userfile"-->
                            <input type="file" name="imagen" value="<?=set_value('imagen')?>" />

                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="marca">Marca *</label>
                            <input type="text" name="marca" value="<?=set_value('marca')?>" class="form-control" id="marca" placeholder="Marca del Producto" >
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label for="pvp">PVP *</label>
                            <input type="numeric" name="pvp" value="<?=set_value('pvp')?>" class="form-control" id="pvp" placeholder="0" >
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label for="iva">IVA *</label>
                            <input type="number" step=".01" name="iva" value="<?=set_value('iva')?>" class="form-control" id="iva" placeholder="0" >
                        </div>
                    </div>
                </div><h6 style='color: #2874A6;'>*El IVA no puede ser negativo.</h6>

                <div class="row">
                    <div class="col-xs-2"><hr>
                        <div class="form-group">
                            <label for="stock">Stock *</label>
                            <input type="number" name="stock" value="<?=set_value('stock')?>" class="form-control" id="stock" placeholder="0" >
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label for="categoria">Categoria *</label>
                            <input type="text" name="categoria" value="<?=set_value('categoria')?>" class="form-control" id="categoria" placeholder="Categoria del Producto" >
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label for="finicio_dest">Fecha inicio de destacado (opcional)</label>
                            <input type="date" name="finicio_dest" value="<?=set_value('finicio_dest')?>" class="form-control" id="finicio_dest">
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <div class="form-group">
                            <label for="ffin_dest">Fecha final de destacado (opcional)</label>
                            <input type="date" name="ffin_dest" value="<?=set_value('ffin_dest')?>" class="form-control" id="ffin_dest">
                        </div>
                    </div>
                </div>
            </div>

            <hr>
            <a class="btn btn btn-default" style="margin-left: 50px;" href="<?=site_url().'/Inicio/cargarVista/panel_usuario_admin'?>"><b><span class="glyphicon glyphicon-chevron-left"></span>   Volver atrás</b></a></center><button style='margin-left: 7em' type="submit" name="bcontinuar" class="btn btn-success"><B>Finalizar</B>  <span class="glyphicon glyphicon-chevron-right"></span></button><br>
        </div>
    <?php echo form_close() ?>
</div>
</code>```

Here is the fragment of the controller in charge of the form:

```<code>public function verificarProducto()
{
  $prueba = $this->mproducto->verCategoriasEx($this->input->post('category'));

  if($this->mproducto->verCategoriasEx($this->input->post('category')) >= 0){
    $a = intval($this->mproducto->verCategoriasEx($this->input->post('category')));
  }else{
    $datos_cat = array(
      'name' => $this->input->post('category'),
      'description' => "",
      'announce' => 0,
      'show' => 1
    );

    $a = $this->mproducto->insertaCategoria($datos_cat);
  }

  $datos = array(
    'category_id' => $a ,
    'name' => $this->input->post('nombre'),
    'brand' => $this->input->post('marca'),
    'description' => $this->input->post('descripcion'),
    'discount' => 0,
    'announce' => 0,
    'image' => $this->input->post('image'),
    'pvp' => $this->input->post('pvp'),
    'iva' => $this->input->post('iva'),
    'stock' => $this->input->post('stock'),
    'show' => 1,
    'finicio_dest' => $this->input->post('finicio_dest'),
    'ffin_dest' => $this->input->post('ffin_dest'),
    'destacado' => 1
  );
  $this->mproducto->insertaProducto($datos);
  $cuerpo = $this->load->view("producto_creado", "", TRUE);
  $this->cargaPlantilla($cuerpo, "");
}
</code>```

Here is the fragment of the controller that upload the image:

```<code><?php
if(!defined('BASEPATH'))
  exit('No direct script access allowed');

class subir_controller extends CI_Controller {

 public function __construct(){
  parent::__construct();
}

public function index(){
  $this->load->view('nuevoProducto', array('error' => ' ' ));
}

public function subir(){
  $dato = $this->input->post("txt_dato");
  $image_name = $_FILES['archivoImagen']['name'];
  $data = array("dato" => $dato, "image" => $image_name);
  $guardar = $this->msubir->guardar($data);
  $this->subirImagen();
}

public function subirImagen(){
  $nombreCompleto = $_FILES['archivoImagen']['name'];
  $config['upload_path'] = './assets/img/productos/';
  $config['allowed_types'] = 'jpg|jpeg|png';
  $config['file_name'] = $nombreCompleto;
  $this->load->library('upload', $config);

  if(!$this->upload->do_upload('archivoImagen')) {
    $data['error'] = array('error' => $this->upload->display_errors());
  } else {
    $data['infoImagen'] = $this->upload->data();
  }
}
}
?>
</code>```

And finally, the model here:

```<code><?php
class Subir_model extends CI_Model
{
    function guardar($data)
    {
        $this->db->insert("subir", $data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
</code>```

I have been trying things for a long time and surely from the mixture of solutions that I have tried, there is something about the code that does not make much sense, but right now, it works as I told you at the top of the question. Save all data, including image name, to the database, but don't copy the image to the server folder.

If you don't understand something, please, let me know and I try to answer you as soon al possible.

I appreciate your help in advance.

var_dump($_POST) prints:

```<code>array(10) { ["nombre"]=> string(4) "test" ["descripcion"]=> string(4) "test" ["marca"]=> string(4) "test" ["pvp"]=> string(2) "10" ["iva"]=> string(2) "10" ["stock"]=> string(3) "100" ["categoria"]=> string(4) "Test" ["finicio_dest"]=> string(0) "" ["ffin_dest"]=> string(0) "" ["bcontinuar"]=> string(0) "" }
</code>```

答:
I think you would want to use the "form_open_multipart" function for the form opener as it allows uploading files. Otherwise it sends only the text.

This function is identical to form_open() above, except that it adds a
  multipart attribute, which is necessary if you would like to use the
  form to upload files with.

I can see you are having 2 forms nested, which is not good idea. You should remove the nested form.
In that case that field could not be retrieved from the main form and returns NULL. Otherwise if image is not selected it would simply return empty string.

Also it is a good idea to turn on the XSS FILTER to protect the data entered through the form by using the TRUE tag in input->post function like this:

```<code>$this->input->post('some_data', TRUE);
</code>```

That would escape the string and prevent xss attacks.

Title: CodeIgniter - Upload file using a form

Body:
I am a bit desperate already, because I am programming a project in CodeIgniter which is an Online store of food products. The problem is that when I have to create the product, I have a form in which the administrator is asked to enter, the name, brand, description, price, VAT, category, etc. of the product, and in between, there is another field that is the product image. Well, when I fill in that form and submit it, the product is added to the database and everything works great, except that the product image is not copied from my hard drive to the server folder.

I'm using:
  PHP 7.3.9
  MySQL 5.7.26
  CodeIgniter 3.1.8

I put the code of this form (the view), which I have already changed so many times, that there must be errors excessively:

<?php if (isset($error)) {?>

        <?php echo validation_errors('

','

') ?>

<?php }?>

Crear Producto

Rellena los siguientes campos con los datos del producto y una vez termines pulsa el botón.

        <?php echo form_open_multipart('Inicio/verificarProducto'); ?>

                        Nombre *
                        <input type="text" name="nombre" value="<?=set_value('nombre')?>" class="form-control" id="nombre" placeholder="Nombre del Producto" >

                        Descripción *
                        <input type="text" name="descripcion" value="<?=set_value('descripcion')?>" class="form-control" id="descripcion" placeholder="Descripción del Producto" >

                            Imagen *

                            <input type="file" name="imagen" value="<?=set_value('imagen')?>" />

                            Marca *
                            <input type="text" name="marca" value="<?=set_value('marca')?>" class="form-control" id="marca" placeholder="Marca del Producto" >

                            PVP *
                            <input type="numeric" name="pvp" value="<?=set_value('pvp')?>" class="form-control" id="pvp" placeholder="0" >

                            IVA *
                            <input type="number" step=".01" name="iva" value="<?=set_value('iva')?>" class="form-control" id="iva" placeholder="0" >

*El IVA no puede ser negativo.

                            Stock *
                            <input type="number" name="stock" value="<?=set_value('stock')?>" class="form-control" id="stock" placeholder="0" >

                            Categoria *
                            <input type="text" name="categoria" value="<?=set_value('categoria')?>" class="form-control" id="categoria" placeholder="Categoria del Producto" >

                            Fecha inicio de destacado (opcional)
                            <input type="date" name="finicio_dest" value="<?=set_value('finicio_dest')?>" class="form-control" id="finicio_dest">

                            Fecha final de destacado (opcional)
                            <input type="date" name="ffin_dest" value="<?=set_value('ffin_dest')?>" class="form-control" id="ffin_dest">

            <a class="btn btn btn-default" style="margin-left: 50px;" href="<?=site_url().'/Inicio/cargarVista/panel_usuario_admin'?>">   Volver atrás<button style='margin-left: 7em' type="submit" name="bcontinuar" class="btn btn-success">Finalizar  </button>

    <?php echo form_close() ?>

Here is the fragment of the controller in charge of the form:

public function verificarProducto()
{
  $prueba = $this->mproducto->verCategoriasEx($this->input->post('category'));

  if($this->mproducto->verCategoriasEx($this->input->post('category')) >= 0){
    $a = intval($this->mproducto->verCategoriasEx($this->input->post('category')));
  }else{
    $datos_cat = array(
      'name' => $this->input->post('category'),
      'description' => "",
      'announce' => 0,
      'show' => 1
    );

    $a = $this->mproducto->insertaCategoria($datos_cat);
  }

  $datos = array(
    'category_id' => $a ,
    'name' => $this->input->post('nombre'),
    'brand' => $this->input->post('marca'),
    'description' => $this->input->post('descripcion'),
    'discount' => 0,
    'announce' => 0,
    'image' => $this->input->post('image'),
    'pvp' => $this->input->post('pvp'),
    'iva' => $this->input->post('iva'),
    'stock' => $this->input->post('stock'),
    'show' => 1,
    'finicio_dest' => $this->input->post('finicio_dest'),
    'ffin_dest' => $this->input->post('ffin_dest'),
    'destacado' => 1
  );
  $this->mproducto->insertaProducto($datos);
  $cuerpo = $this->load->view("producto_creado", "", TRUE);
  $this->cargaPlantilla($cuerpo, "");
}

Here is the fragment of the controller that upload the image:

<?php
if(!defined('BASEPATH'))
  exit('No direct script access allowed');

class subir_controller extends CI_Controller {

 public function __construct(){
  parent::__construct();
}

public function index(){
  $this->load->view('nuevoProducto', array('error' => ' ' ));
}

public function subir(){
  $dato = $this->input->post("txt_dato");
  $image_name = $_FILES['archivoImagen']['name'];
  $data = array("dato" => $dato, "image" => $image_name);
  $guardar = $this->msubir->guardar($data);
  $this->subirImagen();
}

public function subirImagen(){
  $nombreCompleto = $_FILES['archivoImagen']['name'];
  $config['upload_path'] = './assets/img/productos/';
  $config['allowed_types'] = 'jpg|jpeg|png';
  $config['file_name'] = $nombreCompleto;
  $this->load->library('upload', $config);

  if(!$this->upload->do_upload('archivoImagen')) {
    $data['error'] = array('error' => $this->upload->display_errors());
  } else {
    $data['infoImagen'] = $this->upload->data();
  }
}
}
?>

And finally, the model here:

<?php
class Subir_model extends CI_Model
{
    function guardar($data)
    {
        $this->db->insert("subir", $data);
        if ($this->db->affected_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
}

I have been trying things for a long time and surely from the mixture of solutions that I have tried, there is something about the code that does not make much sense, but right now, it works as I told you at the top of the question. Save all data, including image name, to the database, but don't copy the image to the server folder.

If you don't understand something, please, let me know and I try to answer you as soon al possible.

I appreciate your help in advance.

var_dump($_POST) prints:

array(10) { ["nombre"]=> string(4) "test" ["descripcion"]=> string(4) "test" ["marca"]=> string(4) "test" ["pvp"]=> string(2) "10" ["iva"]=> string(2) "10" ["stock"]=> string(3) "100" ["categoria"]=> string(4) "Test" ["finicio_dest"]=> string(0) "" ["ffin_dest"]=> string(0) "" ["bcontinuar"]=> string(0) "" }

Body:
I think you would want to use the "form_open_multipart" function for the form opener as it allows uploading files. Otherwise it sends only the text.

This function is identical to form_open() above, except that it adds a
  multipart attribute, which is necessary if you would like to use the
  form to upload files with.

I can see you are having 2 forms nested, which is not good idea. You should remove the nested form.
In that case that field could not be retrieved from the main form and returns NULL. Otherwise if image is not selected it would simply return empty string.

Also it is a good idea to turn on the XSS FILTER to protect the data entered through the form by using the TRUE tag in input->post function like this:

$this->input->post('some_data', TRUE);

That would escape the string and prevent xss attacks.


问:
How can i fix local asset error in flutter?
Can someone tell me why the picture cannot be displayed?

#

When I take a picture from the Internet with "NetworkImage" it works. Is there a local solution too?

#

I tried a lot around but even the posts here in the forum can not help me.

```<code>  # To add assets to your application, add an assets section, like this:

  assets:
    - images/mio.jpg
</code>```

-

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(Main());
}

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          width: 250,
          height: 250,
          color: Colors.grey,
          child: Stack(
            children: <Widget>[
              Container(
                width: 200,
                height: 300,
                color: Colors.green,
              ),
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 200,
                  height: 300,
                  child: Image(
                    fit: BoxFit.contain,
                    image: AssetImage(
                      'images/mio.jpg',
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

I get this error message

答:
I'm not sure why you are getting this error but you should try

```<code>Asset.Image(
  'images/mio.jpg',
  fit: BoxFit.contain,
),
</code>```

instead of

```<code>Image(
  fit: BoxFit.contain,
  image: AssetImage(
     'images/mio.jpg',
   ),
),
</code>```

another suggestion would be to not declare all your images in your pubspec.yaml, because there is a chance of human mistype error, you should just declare the root folder of your images, in your case

```<code>  assets:
    - images/
</code>```

Body:
Can someone tell me why the picture cannot be displayed?

#

When I take a picture from the Internet with "NetworkImage" it works. Is there a local solution too?

#

I tried a lot around but even the posts here in the forum can not help me.

  # To add assets to your application, add an assets section, like this:

  assets:
    - images/mio.jpg

-

import 'package:flutter/material.dart';

void main() {
  runApp(Main());
}

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          width: 250,
          height: 250,
          color: Colors.grey,
          child: Stack(
            children: <Widget>[
              Container(
                width: 200,
                height: 300,
                color: Colors.green,
              ),
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 200,
                  height: 300,
                  child: Image(
                    fit: BoxFit.contain,
                    image: AssetImage(
                      'images/mio.jpg',
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

I get this error message

Body:
I'm not sure why you are getting this error but you should try

Asset.Image(
  'images/mio.jpg',
  fit: BoxFit.contain,
),

instead of

Image(
  fit: BoxFit.contain,
  image: AssetImage(
     'images/mio.jpg',
   ),
),

another suggestion would be to not declare all your images in your pubspec.yaml, because there is a chance of human mistype error, you should just declare the root folder of your images, in your case

  assets:
    - images/


问:
TkMessageBox - No Module
```<code>import TkMessageBox
</code>```

When I import TkMessageBox it displays the messsge 'ImportError: No module named 'TkMessageBox'.

As far as I know im using python 3.3.2 and Tk 8.5.

Am I using the wrong version of python or importing it wrong ?

Any answers would be extremely useful. Alternatively is there something similar in the version i am using?

答:
from tkinter import messagebox sous Python 3
messagebox.showinfo(title=None, message=None, **options)</p>

Title: TkMessageBox - No Module

Body:
import TkMessageBox

When I import TkMessageBox it displays the messsge 'ImportError: No module named 'TkMessageBox'.

As far as I know im using python 3.3.2 and Tk 8.5.

Am I using the wrong version of python or importing it wrong ?

Any answers would be extremely useful. Alternatively is there something similar in the version i am using?


问:
jQuery/Rails 3 button does not change state
I have spent a couple of days (like 4) trying to solve this issue.  I followed the Hartl Rails 3 tutorial and in chapter 12 tried to convert the site from prototype to jQuery.  I am not able to get the "follow"/"unfollow" button to update however.

I am able to issue jQuery commands from within Safari's Inspect Element Console, but if I put even the simplest jQuery command into the destroy.js.erb or create.js.erb files, nothing happens.  The log is indicating that the appropriate relationships/destry.js.erb (or create.js.erb) file is rendering.

Here is the code that I have in the controller:

```<code>class RelationshipsController < ApplicationController
  before_filter :authenticate

  def create
@user = User.find(params[:relationship][:followed_id])
  current_user.follow!(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end
def destroy
  @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end
end
</code>```

The users/_follow.html.haml is

```<code>- relationship = current_user.relationships.build(:followed_id => @user.id)
= form_for(relationship, :remote => true) do |f|
  = f.hidden_field :followed_id
  .actions= f.submit "Follow"
</code>```

The users/_unfollow.html.haml is

```<code>- relationship = current_user.relationships.find_by_followed_id(@user)
- delete = { :method => :delete }
  = form_for(relationship, :html => delete, :remote => true) do |f|
  .actions= f.submit "Unfollow"
</code>```

The users/_follow_form.html.haml is

```<code>- unless current_user?(@user)
  #follow_form
    - if current_user.following?(@user)
    = render 'unfollow'
    - else
    = render 'follow'
</code>```

The relationships/create.js.erb is

```<code>$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')
</code>```

The relationships/destroy.js.erb is

```<code>$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')
</code>```

However, in trying to diagnose this, I tried a very basic

```<code>$("#title").html("Followed")
</code>```

which also does not work.

答:
Looks like an issue with how you're using jQuery.

jQuery uses CSS-style selectors, while Prototype doesn't. So, to make it work, just add a "#" symbol to the selectors.

Instead of

```<code>$("follow_form").html("something");
</code>```

You should use

```<code>$("#follow_form").html("something");
// Note the # symbol in the selector.
// Also, remember to end your statements with a semicolon.
</code>```

You can read about jQuery ID selectors here: http://api.jquery.com/id-selector/

Body:
I have spent a couple of days (like 4) trying to solve this issue.  I followed the Hartl Rails 3 tutorial and in chapter 12 tried to convert the site from prototype to jQuery.  I am not able to get the "follow"/"unfollow" button to update however.

I am able to issue jQuery commands from within Safari's Inspect Element Console, but if I put even the simplest jQuery command into the destroy.js.erb or create.js.erb files, nothing happens.  The log is indicating that the appropriate relationships/destry.js.erb (or create.js.erb) file is rendering.

Here is the code that I have in the controller:

class RelationshipsController < ApplicationController
  before_filter :authenticate

  def create
@user = User.find(params[:relationship][:followed_id])
  current_user.follow!(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end
def destroy
  @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end
end

The users/_follow.html.haml is

- relationship = current_user.relationships.build(:followed_id => @user.id)
= form_for(relationship, :remote => true) do |f|
  = f.hidden_field :followed_id
  .actions= f.submit "Follow"

The users/_unfollow.html.haml is

- relationship = current_user.relationships.find_by_followed_id(@user)
- delete = { :method => :delete }
  = form_for(relationship, :html => delete, :remote => true) do |f|
  .actions= f.submit "Unfollow"

The users/_follow_form.html.haml is

- unless current_user?(@user)
  #follow_form
    - if current_user.following?(@user)
    = render 'unfollow'
    - else
    = render 'follow'

The relationships/create.js.erb is

$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')

The relationships/destroy.js.erb is

$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')

However, in trying to diagnose this, I tried a very basic

$("#title").html("Followed")

which also does not work.

Body:
Looks like an issue with how you're using jQuery.

jQuery uses CSS-style selectors, while Prototype doesn't. So, to make it work, just add a "#" symbol to the selectors.

Instead of

$("follow_form").html("something");

You should use

$("#follow_form").html("something");
// Note the # symbol in the selector.
// Also, remember to end your statements with a semicolon.

You can read about jQuery ID selectors here: http://api.jquery.com/id-selector/


问:
Deleting specific files in a directory using bash
I have a txt file with a list of files (approximately 500) for example:

```<code>
file_0_hard.msOut
file_1_hard.msOut
file_10_hard.msOut
.
.
.
file_1000_hard.msOut

</code>```

I want to delete all those files whose name is not in the txt file. All of these files are in the same directory. How can I do this using bash where I read the text file and then delete all those files in the directory that are not in the text file. Help would be appreciated.

答:
Along the lines of user1934428

There is something to say for this solution. But since we have linux at our disposal with a strong filesystem in use I hope. we can make hardlinks; The only requirement for that the destination is on the same filesystem.

So along those lines:

make a directory to store the files you want to keep.

hardlink (ln {file} {target}) ; as this does not cost extra disk space, it only stores the inode number in the new directory file.

remove all files

move the files back from their origin.

And actually this would be about the same as:

mv {files} {save spot}

remove all files

mv {save spot}/{files} back

Which does pretty much the same thing. Then again; it is a nice way to learn about the power of a hardlink.

Body:
I have a txt file with a list of files (approximately 500) for example:

file_0_hard.msOut
file_1_hard.msOut
file_10_hard.msOut
.
.
.
file_1000_hard.msOut

I want to delete all those files whose name is not in the txt file. All of these files are in the same directory. How can I do this using bash where I read the text file and then delete all those files in the directory that are not in the text file. Help would be appreciated.


问:
Why does adding a class to a p tag in the json of a seeder break that seeder?
I have a seeder that, in one part of it seeds a json column as shown below. If I have the text in a p tag everything seeds just fine.

This works:

```<code>DB::table('table_name')->insert(array(
  array(
    'json' => '<p>some text</p>'
  )
))
</code>```

However if I add a class or a style tag to the text, it breaks the seeder! why? How? How do I get around this?

```<code>DB::table('table_name')->insert(array(
  array(
    'json' => '<p class="subtitle">some text</p>'
  )
))
</code>```

The error that I get is <<Unknown error>>: 3140 Invalid JSON text: "Invalid value." at position 27806 in value for column

答:
Try it like this:

DB::table('table_name')->insert(array(
  array(
    'json' => json_encode('
some text
')
  )
))
```

Body:
I have a seeder that, in one part of it seeds a json column as shown below. If I have the text in a p tag everything seeds just fine.

This works:

DB::table('table_name')->insert(array(
  array(
    'json' => '
some text
'
  )
))

However if I add a class or a style tag to the text, it breaks the seeder! why? How? How do I get around this?

DB::table('table_name')->insert(array(
  array(
    'json' => '
some text
'
  )
))

The error that I get is <<Unknown error>>: 3140 Invalid JSON text: "Invalid value." at position 27806 in value for column

Body:
Try it like this:

DB::table('table_name')->insert(array(
  array(
    'json' => json_encode('<p class="subtitle">some text</p>')
  )
))


问:
c# date formatting issue with Culture info
I try to format a local date into a string, but based on the local format.
By example, for the 5 May 2020, if I use French, I expected "5 Mai, 2020",
but I got "5 May, 2020" ...

The month name is still in English !

Here is my code to test this:

https://dotnetfiddle.net/saZJ0S

Do you have any idea ?

Thx

答:
You need to use the DateTime.ToString overload that gets CultureInfo parameter as a second argument.

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netcore-3.1

So your code would look like (copying from the image you attached):

```<code>string FormattedPostDate = localDate.ToString(CultureInfo.GetCultureInfo("fr-FR").DateTimeFormat.MonthDayPattern, new System.Globalization.CultureInfo("fr-FR")) + ", " + localDate.Year;
</code>```

Body:
You need to use the DateTime.ToString overload that gets CultureInfo parameter as a second argument.

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netcore-3.1

So your code would look like (copying from the image you attached):

string FormattedPostDate = localDate.ToString(CultureInfo.GetCultureInfo("fr-FR").DateTimeFormat.MonthDayPattern, new System.Globalization.CultureInfo("fr-FR")) + ", " + localDate.Year;


问:
Compiled code doesn't execute file writes
I have a class with a run() method that's supposed to write a "header" file, perform some calculations, and write the results of the calculation to a separate file. My problem is that the files never get written. VS code debugger seems to indicate that the .close() calls in the writing methods never get reached. Even when I try to intersperse .flush() methods the file doesn't get any content written, though.

The writing methods call on an inline variable declared in Experiments.h, which is #included in the file.`Experiments::OUTPUT_DIR= "../results/".

I take it that the problem is the content never gets written because .close() never gets called in the compiled code. But how do I fix this?

```<code>// main method in the compiled file

int main(){
    Experiments::Experiment* experiment = new Experiments::UniformRandomAgentGameExperiment();

    experiment -> run();
}
</code>```

```<code>// run() method on the experiment class (simplified)

void Experiments::UniformRandomAgentGameExperiment::run(){

    write_header();

    // Start  maintaining output file in memory, then dump at the end of the experiment

    std::string output_str;
    output_str.reserve(... a large number I calculate ...);
    output_str+="";

    // run all the tests
    int games_played=0;

    while(games_played<n_games){

        // Perform an iteration and accumulate results into output_str.

    }
    // I can verify at this point with simple std::cout that output_str has the content it should
    write_experiment(output_str);
}
</code>```

```<code>// write_header() method

void Experiments::UniformRandomAgentGameExperiment::write_header(){
    std::ofstream header(Experiments::OUTPUT_DIR + fileheader+".header",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited

    header  << "Experiment Name: " << experiment_name << std::endl
            << "Experiment Description: " << description << std::endl << std::endl

            //... and write some more stuff ... <- Debugger indicates these lines get visited

    header.close(); // <- Debugger indicates this line is never reached
}
</code>```

```<code>// write_experiment method

void Experiments::UniformRandomAgentGameExperiment::write_experiment(std::string data){
    std::ofstream logfile(Experiments::OUTPUT_DIR + fileheader + ".csv",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited in compiled code
    logfile << data; // <- Debugger indicates that this line and the next are skipped in compiled code
    logfile.close();
}
</code>```

答:
I found that when I changed Experiments::OUTPUT_DIR = "results/" (rather than "../results/", it wrote!

The code containing main(), as well as the resulting compiled binary, was in a directory within my project root, and I had assumed I needed to specify a path relative to it. I was wrong - the path is apparently relative to where the compiled binary is called (or maybe where it was compiled from? idk).

So before this change, I guess the compiler saw it was trying to write to a non-existent location "project_root/../results" and tried to skip it altogether.

Body:
I have a class with a run() method that's supposed to write a "header" file, perform some calculations, and write the results of the calculation to a separate file. My problem is that the files never get written. VS code debugger seems to indicate that the .close() calls in the writing methods never get reached. Even when I try to intersperse .flush() methods the file doesn't get any content written, though.

The writing methods call on an inline variable declared in Experiments.h, which is #included in the file.`Experiments::OUTPUT_DIR= "../results/".

I take it that the problem is the content never gets written because .close() never gets called in the compiled code. But how do I fix this?

// main method in the compiled file

int main(){
    Experiments::Experiment* experiment = new Experiments::UniformRandomAgentGameExperiment();

    experiment -> run();
}

// run() method on the experiment class (simplified)

void Experiments::UniformRandomAgentGameExperiment::run(){

    write_header();

    // Start  maintaining output file in memory, then dump at the end of the experiment

    std::string output_str;
    output_str.reserve(... a large number I calculate ...);
    output_str+="";

    // run all the tests
    int games_played=0;

    while(games_played<n_games){

        // Perform an iteration and accumulate results into output_str.

    }
    // I can verify at this point with simple std::cout that output_str has the content it should
    write_experiment(output_str);
}

// write_header() method

void Experiments::UniformRandomAgentGameExperiment::write_header(){
    std::ofstream header(Experiments::OUTPUT_DIR + fileheader+".header",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited

    header  << "Experiment Name: " << experiment_name << std::endl
            << "Experiment Description: " << description << std::endl << std::endl

            //... and write some more stuff ... <- Debugger indicates these lines get visited

    header.close(); // <- Debugger indicates this line is never reached
}

// write_experiment method

void Experiments::UniformRandomAgentGameExperiment::write_experiment(std::string data){
    std::ofstream logfile(Experiments::OUTPUT_DIR + fileheader + ".csv",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited in compiled code
    logfile << data; // <- Debugger indicates that this line and the next are skipped in compiled code
    logfile.close();
}


问:
Subscription to MQTT broker and get the data being passed
I am generating data with a node.js simulator and passing this data to a http route /simulator/data

In the application I am listening broker with MQTT mqtthandler.js file which I share below.

```<code>//This is mqtthandler.js file

const mqtt = require("mqtt");

class MqttHandler {
  constructor() {
    this.mqttClient = null;
    this.host = "mqtt://localhost:1883";
    this.username = "YOUR_USER"; // mqtt credentials if these are needed to connect
    this.password = "YOUR_PASSWORD";
  }

  connect() {
    // Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
    this.mqttClient = mqtt.connect(this.host, {
      username: this.username,
      password: this.password,
    });

    // Mqtt error calback
    this.mqttClient.on("error", (err) => {
      console.log(err);
      this.mqttClient.end();
    });

    // Connection callback
    this.mqttClient.on("connect", () => {
      console.log(`mqtt client connected`);
    });

    // mqtt subscriptions
    this.mqttClient.subscribe("value", { qos: 0 });

    // When a message arrives, console.log it
    this.mqttClient.on("message", function (topic, message) {
      console.log(message.toString());
    });

    this.mqttClient.on("close", () => {
      console.log(`mqtt client disconnected`);
    });
  }

  // Sends a mqtt message to topic: mytopic
  sendMessage(message) {
    this.mqttClient.publish("value", message);
  }
}

module.exports = MqttHandler;
</code>```

When simulator sending the data to the /simulator/data route, I am getting the value and sending the broker with value topic. I share the post request code and output of simulator below.

```<code>var mqttHandler = require("../mqtthandler");

module.exports = function (app) {
  app.get("/simulator", function (req, res) {
    res.render("iot/simulator");
  });

  // route to display all the data that is generated
  app.get("/simulator/data", require("./controllers/data").all);

  var mqttClient = new mqttHandler();
  mqttClient.connect();

  // route to write data to the database
  app.post(
    "/simulator/data",
    require("./controllers/data").write,
    (req, res) => {
      mqttClient.sendMessage(req.body.value);
      res.status(200).send("Message sent to mqtt");
    }
  );

  // delete the data when the stream is stopped or when the app is closed
  app.get("/simulator/data/delete", require("./controllers/data").delete);
};
</code>```

When I send get request to /simulator/data I am able to see generated data, however this data is not being sent to broker.

```<code>//This is output of simulator

    [
        {
            "_id": "5ecfadc13cb66f10e4d9d39b",
            "value": "1.886768240197795",
            "__v": 0,
            "categories": []
        },
        {
            "_id": "5ecfadc23cb66f10e4d9d39c",
            "value": "7.351404601932272",
            "__v": 0,
            "categories": []
        }
    ]
</code>```

PS: Broker is created via node-red

I would like to pass this data to broker and see the result with MQTT subscription. However I can not find where am I making mistake.

答:
So a couple of things to look at here.

Your this.mqttClient.subscribe() call is inline with your connect(), on.("error",...), on.("message",...) etc.  So the subscribe() could fire before the connect() has finished...and thus you will never subscribe.  Put the subscribe() inside the connect() block.

You are subscribing to "value", which is not a proper MQTT topic.  If you must, use value/# for the subscribe(), and "value/.." for the publish().  Your class only allows for the single, hard-coded topic, so won't be very useful when you want to reuse that class for other projects.  Take the time now to pass the topic string to the class as well.

Body:
I am generating data with a node.js simulator and passing this data to a http route /simulator/data

In the application I am listening broker with MQTT mqtthandler.js file which I share below.

//This is mqtthandler.js file

const mqtt = require("mqtt");

class MqttHandler {
  constructor() {
    this.mqttClient = null;
    this.host = "mqtt://localhost:1883";
    this.username = "YOUR_USER"; // mqtt credentials if these are needed to connect
    this.password = "YOUR_PASSWORD";
  }

  connect() {
    // Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
    this.mqttClient = mqtt.connect(this.host, {
      username: this.username,
      password: this.password,
    });

    // Mqtt error calback
    this.mqttClient.on("error", (err) => {
      console.log(err);
      this.mqttClient.end();
    });

    // Connection callback
    this.mqttClient.on("connect", () => {
      console.log(`mqtt client connected`);
    });

    // mqtt subscriptions
    this.mqttClient.subscribe("value", { qos: 0 });

    // When a message arrives, console.log it
    this.mqttClient.on("message", function (topic, message) {
      console.log(message.toString());
    });

    this.mqttClient.on("close", () => {
      console.log(`mqtt client disconnected`);
    });
  }

  // Sends a mqtt message to topic: mytopic
  sendMessage(message) {
    this.mqttClient.publish("value", message);
  }
}

module.exports = MqttHandler;

When simulator sending the data to the /simulator/data route, I am getting the value and sending the broker with value topic. I share the post request code and output of simulator below.

var mqttHandler = require("../mqtthandler");

module.exports = function (app) {
  app.get("/simulator", function (req, res) {
    res.render("iot/simulator");
  });

  // route to display all the data that is generated
  app.get("/simulator/data", require("./controllers/data").all);

  var mqttClient = new mqttHandler();
  mqttClient.connect();

  // route to write data to the database
  app.post(
    "/simulator/data",
    require("./controllers/data").write,
    (req, res) => {
      mqttClient.sendMessage(req.body.value);
      res.status(200).send("Message sent to mqtt");
    }
  );

  // delete the data when the stream is stopped or when the app is closed
  app.get("/simulator/data/delete", require("./controllers/data").delete);
};

When I send get request to /simulator/data I am able to see generated data, however this data is not being sent to broker.

//This is output of simulator

    [
        {
            "_id": "5ecfadc13cb66f10e4d9d39b",
            "value": "1.886768240197795",
            "__v": 0,
            "categories": []
        },
        {
            "_id": "5ecfadc23cb66f10e4d9d39c",
            "value": "7.351404601932272",
            "__v": 0,
            "categories": []
        }
    ]

PS: Broker is created via node-red

I would like to pass this data to broker and see the result with MQTT subscription. However I can not find where am I making mistake.


问:
How to optimize query if I already use GIN index
I use (PostgreSQL) 11.8 and I try to provide full text search opportunity by some columns. For that I created GIN index with multiple fields and coalesce. And after my data base grewto 344747 rows in table products I faced with slow execution in my query. When I execute query example I faced with approximately 4.6s. In analyzing information I see my index used, but still slowly. Bitmap Index Scan on npdbcs_swedish_custom_index present. If I correct made conclusion many time spent to grouping. Do someone know any approach or suggestion how to optimize this query, because I can't imagine how it will work when my db grows to 10 million productsю And most hope data from ANALYZE - Planning Time: 0.790 ms it' possible?

```<code>->  GroupAggregate  (cost=27625.67..47476.93 rows=10284 width=928) (actual time=32.328..4490.279 rows=6634 loops=1)
</code>```

my index

```<code>create index npdbcs_swedish_custom_index on products
                    using GIN(to_tsvector('pg_catalog.swedish', name||price||description||brand||category||shop))
</code>```

and my query

```<code> EXPLAIN ANALYZE
        SELECT
            products_alias.id,
            products_alias.sku,
            products_alias.name AS "name",
            products_alias.description,
            products_alias.category,
            products_alias.price,
            products_alias.shipping,
            products_alias.currency,
            products_alias.instock,
            products_alias.product_url AS "productUrl",
            products_alias.image_url AS "imageUrl",
            products_alias.tracking_url AS "trackingUrl",
            products_alias.brand,
            products_alias.shop,
            products_alias.original_price AS "originalPrice",
            products_alias.ean,
            products_alias.manufacturer_article_number AS "manufacturerArticleNumber",
            products_alias.extras,
            products_alias.created_at AS "createdAt",
            products_alias.brand_relation_id AS "brandRelationId",
            products_alias.shop_relation_id AS "shopRelationId",
            array_agg(DISTINCT cpt.category_id) AS categoryIds,
            COUNT(DISTINCT uip.id) as "numberOfEntries",
            ts_rank_cd(to_tsvector('pg_catalog.swedish', products_alias.name||products_alias.price||products_alias.description||products_alias.brand||products_alias.category||products_alias.shop), to_tsquery('pg_catalog.swedish', 'AeroMoov&Air&Layer™&Group&2&Sittdyna&Mörkgrå&One&Size:*|329.00|AeroMoov|Liggdelar|Duovagnar|Barnvagnar|Solskydd')) AS rank

        FROM products products_alias
        LEFT JOIN user_ip_product uip on uip.products_id = products_alias.id
                LEFT JOIN product_category cpt on cpt.product_id = products_alias.id
                WHERE to_tsvector('pg_catalog.swedish', products_alias.name||products_alias.price||products_alias.description||products_alias.brand||products_alias.category||products_alias.shop) @@ to_tsquery('pg_catalog.swedish', 'AeroMoov&Air&Layer™&Group&2&Sittdyna&Mörkgrå&One&Size:*|329.00|AeroMoov|Liggdelar|Duovagnar|Barnvagnar|Solskydd')
        AND products_alias.id != 810429
        GROUP BY products_alias.id ORDER BY rank DESC
        LIMIT 4
        OFFSET 0;

Limit  (cost=47631.19..47631.20 rows=4 width=928) (actual time=4401.654..4401.656 rows=4 loops=1)
  ->  Sort  (cost=47631.19..47656.90 rows=10284 width=928) (actual time=4401.652..4401.653 rows=4 loops=1)
        Sort Key: (ts_rank_cd(to_tsvector('swedish'::regconfig, ((((((products_alias.name)::text || (products_alias.price)::text) || products_alias.description) || (products_alias.brand)::text) || (products_alias.category)::text) || (products_alias.shop)::text)), '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)) DESC
        Sort Method: top-N heapsort  Memory: 31kB
        ->  GroupAggregate  (cost=27625.67..47476.93 rows=10284 width=928) (actual time=31.780..4382.917 rows=6634 loops=1)
              Group Key: products_alias.id
              ->  Gather Merge  (cost=27625.67..44420.18 rows=20203 width=892) (actual time=31.096..88.389 rows=13451 loops=1)
                    Workers Planned: 2
                    Workers Launched: 2
                    ->  Nested Loop Left Join  (cost=26625.65..41088.23 rows=8418 width=892) (actual time=24.549..52.293 rows=4484 loops=3)
                          ->  Merge Left Join  (cost=26625.22..26646.92 rows=4285 width=888) (actual time=24.513..29.039 rows=2212 loops=3)
                                Merge Cond: (products_alias.id = uip.products_id)
                                ->  Sort  (cost=26622.18..26632.89 rows=4285 width=884) (actual time=24.430..26.065 rows=2211 loops=3)
                                      Sort Key: products_alias.id
                                      Sort Method: external merge  Disk: 2808kB
                                      Worker 0:  Sort Method: quicksort  Memory: 3261kB
                                      Worker 1:  Sort Method: quicksort  Memory: 2112kB
                                      ->  Parallel Bitmap Heap Scan on products products_alias  (cost=283.70..26363.68 rows=4285 width=884) (actual time=8.825..17.986 rows=2211 loops=3)
                                            Recheck Cond: (to_tsvector('swedish'::regconfig, ((((((name)::text || (price)::text) || description) || (brand)::text) || (category)::text) || (shop)::text)) @@ '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)
                                            Filter: (id <> 810429)
                                            Rows Removed by Filter: 0
                                            Heap Blocks: exact=2563
                                            ->  Bitmap Index Scan on npdbcs_swedish_custom_index  (cost=0.00..281.13 rows=10284 width=0) (actual time=10.858..10.859 rows=6635 loops=1)
                                                  Index Cond: (to_tsvector('swedish'::regconfig, ((((((name)::text || (price)::text) || description) || (brand)::text) || (category)::text) || (shop)::text)) @@ '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)
                                ->  Sort  (cost=3.05..3.18 rows=53 width=8) (actual time=0.070..0.086 rows=59 loops=3)
                                      Sort Key: uip.products_id
                                      Sort Method: quicksort  Memory: 27kB
                                      Worker 0:  Sort Method: quicksort  Memory: 27kB
                                      Worker 1:  Sort Method: quicksort  Memory: 27kB
                                      ->  Seq Scan on user_ip_product uip  (cost=0.00..1.53 rows=53 width=8) (actual time=0.030..0.040 rows=59 loops=3)
                          ->  Index Scan using idx_cdfc73564584665a on product_category cpt  (cost=0.42..3.34 rows=3 width=8) (actual time=0.007..0.009 rows=2 loops=6636)
                                Index Cond: (product_id = products_alias.id)
Planning Time: 0.660 ms
Execution Time: 4402.940 ms
</code>```

would be great if it spent 0.660 ms. How to optimize this query ?

答:
would be great if it spent 0.660 ms.

The planning time is how much time it spent planning out the execution.  It is not how much time the planner thought the execution of the plan would/should take.  There is no reason to think your hope here is achievable, those two numbers represent entirely different things.  It is like looking how much time you spend tying your shoes, versus running a marathon.  Sure, it would be nice if you could run a marathon in the same time as it takes to tie your shoes, but there is no reason to think that that is achievable.

I'm guessing most of the time is going to either computing ts_rank_cd, or gathering the (possibly TOASTed) inputs necessary to compute it.  What happens if you remove the ts_rank_cd and choose something else to ORDER BY?  EXPLAIN VERBOSE on a simplified version of your query does suggest to me that the actual evaluation of ts_rank_cd is occuring in the correct plan node (i.e. the slow one) for this explanation to be plausible.

One thing that might make it faster is if you save the computed tsvector into the table as a real column, rather than computing it dynamically.  The extra storage needed of course is a trade off there.

I can't imagine how it will work when my db grows to 10 million products

As your products table grows, is your WHERE condition going to still return about the same number of rows, or will it return about the same proportion of the table?

Body:
I use (PostgreSQL) 11.8 and I try to provide full text search opportunity by some columns. For that I created GIN index with multiple fields and coalesce. And after my data base grewto 344747 rows in table products I faced with slow execution in my query. When I execute query example I faced with approximately 4.6s. In analyzing information I see my index used, but still slowly. Bitmap Index Scan on npdbcs_swedish_custom_index present. If I correct made conclusion many time spent to grouping. Do someone know any approach or suggestion how to optimize this query, because I can't imagine how it will work when my db grows to 10 million productsю And most hope data from ANALYZE - Planning Time: 0.790 ms it' possible?

->  GroupAggregate  (cost=27625.67..47476.93 rows=10284 width=928) (actual time=32.328..4490.279 rows=6634 loops=1)

my index

create index npdbcs_swedish_custom_index on products
                    using GIN(to_tsvector('pg_catalog.swedish', name||price||description||brand||category||shop))

and my query

 EXPLAIN ANALYZE
        SELECT
            products_alias.id,
            products_alias.sku,
            products_alias.name AS "name",
            products_alias.description,
            products_alias.category,
            products_alias.price,
            products_alias.shipping,
            products_alias.currency,
            products_alias.instock,
            products_alias.product_url AS "productUrl",
            products_alias.image_url AS "imageUrl",
            products_alias.tracking_url AS "trackingUrl",
            products_alias.brand,
            products_alias.shop,
            products_alias.original_price AS "originalPrice",
            products_alias.ean,
            products_alias.manufacturer_article_number AS "manufacturerArticleNumber",
            products_alias.extras,
            products_alias.created_at AS "createdAt",
            products_alias.brand_relation_id AS "brandRelationId",
            products_alias.shop_relation_id AS "shopRelationId",
            array_agg(DISTINCT cpt.category_id) AS categoryIds,
            COUNT(DISTINCT uip.id) as "numberOfEntries",
            ts_rank_cd(to_tsvector('pg_catalog.swedish', products_alias.name||products_alias.price||products_alias.description||products_alias.brand||products_alias.category||products_alias.shop), to_tsquery('pg_catalog.swedish', 'AeroMoov&Air&Layer™&Group&2&Sittdyna&Mörkgrå&One&Size:*|329.00|AeroMoov|Liggdelar|Duovagnar|Barnvagnar|Solskydd')) AS rank

        FROM products products_alias
        LEFT JOIN user_ip_product uip on uip.products_id = products_alias.id
                LEFT JOIN product_category cpt on cpt.product_id = products_alias.id
                WHERE to_tsvector('pg_catalog.swedish', products_alias.name||products_alias.price||products_alias.description||products_alias.brand||products_alias.category||products_alias.shop) @@ to_tsquery('pg_catalog.swedish', 'AeroMoov&Air&Layer™&Group&2&Sittdyna&Mörkgrå&One&Size:*|329.00|AeroMoov|Liggdelar|Duovagnar|Barnvagnar|Solskydd')
        AND products_alias.id != 810429
        GROUP BY products_alias.id ORDER BY rank DESC
        LIMIT 4
        OFFSET 0;

Limit  (cost=47631.19..47631.20 rows=4 width=928) (actual time=4401.654..4401.656 rows=4 loops=1)
  ->  Sort  (cost=47631.19..47656.90 rows=10284 width=928) (actual time=4401.652..4401.653 rows=4 loops=1)
        Sort Key: (ts_rank_cd(to_tsvector('swedish'::regconfig, ((((((products_alias.name)::text || (products_alias.price)::text) || products_alias.description) || (products_alias.brand)::text) || (products_alias.category)::text) || (products_alias.shop)::text)), '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)) DESC
        Sort Method: top-N heapsort  Memory: 31kB
        ->  GroupAggregate  (cost=27625.67..47476.93 rows=10284 width=928) (actual time=31.780..4382.917 rows=6634 loops=1)
              Group Key: products_alias.id
              ->  Gather Merge  (cost=27625.67..44420.18 rows=20203 width=892) (actual time=31.096..88.389 rows=13451 loops=1)
                    Workers Planned: 2
                    Workers Launched: 2
                    ->  Nested Loop Left Join  (cost=26625.65..41088.23 rows=8418 width=892) (actual time=24.549..52.293 rows=4484 loops=3)
                          ->  Merge Left Join  (cost=26625.22..26646.92 rows=4285 width=888) (actual time=24.513..29.039 rows=2212 loops=3)
                                Merge Cond: (products_alias.id = uip.products_id)
                                ->  Sort  (cost=26622.18..26632.89 rows=4285 width=884) (actual time=24.430..26.065 rows=2211 loops=3)
                                      Sort Key: products_alias.id
                                      Sort Method: external merge  Disk: 2808kB
                                      Worker 0:  Sort Method: quicksort  Memory: 3261kB
                                      Worker 1:  Sort Method: quicksort  Memory: 2112kB
                                      ->  Parallel Bitmap Heap Scan on products products_alias  (cost=283.70..26363.68 rows=4285 width=884) (actual time=8.825..17.986 rows=2211 loops=3)
                                            Recheck Cond: (to_tsvector('swedish'::regconfig, ((((((name)::text || (price)::text) || description) || (brand)::text) || (category)::text) || (shop)::text)) @@ '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)
                                            Filter: (id <> 810429)
                                            Rows Removed by Filter: 0
                                            Heap Blocks: exact=2563
                                            ->  Bitmap Index Scan on npdbcs_swedish_custom_index  (cost=0.00..281.13 rows=10284 width=0) (actual time=10.858..10.859 rows=6635 loops=1)
                                                  Index Cond: (to_tsvector('swedish'::regconfig, ((((((name)::text || (price)::text) || description) || (brand)::text) || (category)::text) || (shop)::text)) @@ '''aeromoov'' & ''air'' & ''layer'' & ''group'' & ''2'' & ''sittdyn'' & ''mörkgrå'' & ''one'' & ''siz'':* | ''329.00'' | ''aeromoov'' | ''liggdel'' | ''duovagn'' | ''barnvagn'' | ''solskyd'''::tsquery)
                                ->  Sort  (cost=3.05..3.18 rows=53 width=8) (actual time=0.070..0.086 rows=59 loops=3)
                                      Sort Key: uip.products_id
                                      Sort Method: quicksort  Memory: 27kB
                                      Worker 0:  Sort Method: quicksort  Memory: 27kB
                                      Worker 1:  Sort Method: quicksort  Memory: 27kB
                                      ->  Seq Scan on user_ip_product uip  (cost=0.00..1.53 rows=53 width=8) (actual time=0.030..0.040 rows=59 loops=3)
                          ->  Index Scan using idx_cdfc73564584665a on product_category cpt  (cost=0.42..3.34 rows=3 width=8) (actual time=0.007..0.009 rows=2 loops=6636)
                                Index Cond: (product_id = products_alias.id)
Planning Time: 0.660 ms
Execution Time: 4402.940 ms

would be great if it spent 0.660 ms. How to optimize this query ?


问:
Razor in-line if statement not working?
I've got an exception throwing at this line, and can't figure out why...maybe someone else can spot it

```<code><img src="@{Model.Image != null ? Model.Image.FileName : "";}" width="200px" id="ImagePreview"/>
</code>```

The exception I'm getting is:

```<code>error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
</code>```

答:
Try wrapping it in parenthesis instead of curly brackets:</p>

```<code><img src="@(Model.Image != null ? Model.Image.FileName : "")" width="200px" id="ImagePreview"/>
</code>```

Title: Razor in-line if statement not working?

Body:
I've got an exception throwing at this line, and can't figure out why...maybe someone else can spot it

The exception I'm getting is:

error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Body:
Try wrapping it in parenthesis instead of curly brackets:

<img src="@(Model.Image != null ? Model.Image.FileName : "")" width="200px" id="ImagePreview"/>


问:
Is there a way to change the way Google Sheets Query Group sorts? By both capitals and letter case?
I have a simple query function that returns a range of names and sums,  grouped by the names.

```<code>=QUERY('Mamut inklipp'!C:R;"select F, sum(R) group by F";0)
</code>```

This sorts by the names, but case sensitive. A-Z all comes before a-z. Therefore "Eve" comes before "adam". To me that is just plain wrong.

Is there a way to change the the sorting method?

答:
You should be able to work around that. Pre-processing the data ('before the query') might be an option. Here's a little example.

I hope that works for you?

Note: Depending on your locale, you may have to use commas instead of semi-colons as argument separators (in the formula).

Body:
I have a simple query function that returns a range of names and sums,  grouped by the names.

=QUERY('Mamut inklipp'!C:R;"select F, sum(R) group by F";0)

This sorts by the names, but case sensitive. A-Z all comes before a-z. Therefore "Eve" comes before "adam". To me that is just plain wrong.

Is there a way to change the the sorting method?


问:
Updating the nested array element value in Mongo DB
I'm new to MERN, I have created a system for the teachers to check the assignment.
My Schema looks like this

const mongoose = require('mongoose')
const xyzSchema = new mongoose.Schema({
    user:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'user_collections'
    },
    assignments:[{
        title_assignment:{
            type:String,
            required:true
        },
        description_assignment:{
            type:String,
            required:true
        },
        created_at:{
            type:Date,
            required:true,
            default:Date.now()
        },
        files:[],
        submitted:[{
            user:{
                type:mongoose.Schema.Types.ObjectId,
                ref:'user_collections'
            },
            files:[],
            created_at:{
                type:Date,
                required:true,
                default:Date.now()
            },
            checked:{
                type:Boolean,
                default:false
            }
        }],
        due_dt:{
            type:Date,
            required:true
        }
    }],
})

module.exports = mongoose.model('abc',xyzSchema)```
</div>
</div>
</p>

<p>On Click of <strong>checked</strong> on frontend, I wan't to update the value of "checked" to true from "false".</p>

<p>My Route looks like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>router.put('/assignments/check',
auth,
async(req,res)=>{

    try {
        let check = await Classroom.findOne(
            {"assignments._id":req.body.assignment_id,"assignments.submitted.user":req.body.user_id},
            {$set:{"assignments.$.submitted.$.checked":"true"}}}
        )
        res.json(check)
    } catch (error) {
        console.error(error)
    }
})</code>```

This code is not working for me. Can someone please suggest me something?
What I want to do is
1) Find the Aassignment using ID and submitted assignment array using the User ID inside it
2) Change the "checked" value for that user to "true"

答:
You need to use the $[] identifier. With arrayFilters in update.

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up.S[%3Cidentifier%3E]

You also need to convert your Ids to Mongodb object Ids with mongoose.Types.ObjectId() if the Ids are ObjectIds, otherwise it could be that the query works without errors but the fields wont get updated.

```<code>let check = await Classroom.update(
            {},
            { $set: {"assignments.$[assign].submitted.$[submitt].checked": "true" }},
            {
             arrayFilters: [
                  {
                     "assign._id": mongoose.Types.ObjectId(req.body.assignment_id)
                  },
                  {
                     "submitt.user": mongoose.Types.ObjectId(req.body.user_id)
                  }
               ]
            }
</code>```

The $ identifier works only for 1 level of depth, if its more then you need to use arrayFilters

Body:
I'm new to MERN, I have created a system for the teachers to check the assignment.
My Schema looks like this

const mongoose = require('mongoose')
const xyzSchema = new mongoose.Schema({
    user:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'user_collections'
    },
    assignments:[{
        title_assignment:{
            type:String,
            required:true
        },
        description_assignment:{
            type:String,
            required:true
        },
        created_at:{
            type:Date,
            required:true,
            default:Date.now()
        },
        files:[],
        submitted:[{
            user:{
                type:mongoose.Schema.Types.ObjectId,
                ref:'user_collections'
            },
            files:[],
            created_at:{
                type:Date,
                required:true,
                default:Date.now()
            },
            checked:{
                type:Boolean,
                default:false
            }
        }],
        due_dt:{
            type:Date,
            required:true
        }
    }],
})

module.exports = mongoose.model('abc',xyzSchema)

On Click of checked on frontend, I wan't to update the value of "checked" to true from "false".

My Route looks like this

router.put('/assignments/check',
auth,
async(req,res)=>{

    try {
        let check = await Classroom.findOne(
            {"assignments._id":req.body.assignment_id,"assignments.submitted.user":req.body.user_id},
            {$set:{"assignments.$.submitted.$.checked":"true"}}}
        )
        res.json(check)
    } catch (error) {
        console.error(error)
    }
})

This code is not working for me. Can someone please suggest me something?
What I want to do is
1) Find the Aassignment using ID and submitted assignment array using the User ID inside it
2) Change the "checked" value for that user to "true"

Body:
You need to use the $[] identifier. With arrayFilters in update.

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up.S[%3Cidentifier%3E]

You also need to convert your Ids to Mongodb object Ids with mongoose.Types.ObjectId() if the Ids are ObjectIds, otherwise it could be that the query works without errors but the fields wont get updated.

let check = await Classroom.update(
            {},
            { $set: {"assignments.$[assign].submitted.$[submitt].checked": "true" }},
            {
             arrayFilters: [
                  {
                     "assign._id": mongoose.Types.ObjectId(req.body.assignment_id)
                  },
                  {
                     "submitt.user": mongoose.Types.ObjectId(req.body.user_id)
                  }
               ]
            }

The $ identifier works only for 1 level of depth, if its more then you need to use arrayFilters