问:
Go elasticsearch bulk insert
I have been unable to solve the problem into elasticsearch Bulk method for several days, since I am not strong in Go and started learning it not so long ago, while executing the code :

package main

import (
    "bytes"
    json "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type BulkInsertMetaData struct {
    Index []BulkInsertIndex `json:"index"`
}
type BulkInsertIndex struct {
    Index string `json:"_index"`
    ID    string `json:"_id"`
}

type BulInsertData struct {
    Url string `json:"url"`
}

func main() {
    dataMeta := BulkInsertMetaData{
        Index: []BulkInsertIndex{
            {
                Index: "Test",
                ID:    "1234567890",
            },
        },
    }
    data := BulInsertData{
        Url: "http://XXXX.XX",
    }
    TojsBulInsertData, _ := json.Marshal(data)
    TojsBulkInsertMetaData, _ := json.Marshal(dataMeta)
    BulkMetaData := bytes.NewBuffer(append(TojsBulkInsertMetaData, []byte("\n")...))
    BulkData := bytes.NewBuffer(append(TojsBulInsertData, []byte("\n")...))
    log.Println(BulkMetaData)
    log.Println(BulkData)
    respMetaData, err := http.Post("http://127.0.0.1:9200/_bulk", "application/json", BulkMetaData)
    if err != nil {
        log.Println(err)
    }
    body, err := ioutil.ReadAll(respMetaData.Body)
    if err != nil {
        log.Println(err)
    }
    fmt.Println(string(body))
    respBulkData, err := http.Post("http://127.0.0.1:9200/_bulk", "application/json", BulkData)
    if err != nil {
        log.Println(err)
    }
    body2, err := ioutil.ReadAll(respBulkData.Body)
    if err != nil {
        log.Println(err)
    }
    fmt.Println(string(body2))
}
```
<p>but i get an error:</p>
```2022/02/09 14:37:02 {"index":[{"_index":"Test","_id":"1234567890"}]}

2022/02/09 14:37:02 {"url":"http://XXXX.XX"}

{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [START_ARRAY]"}],"type":"illegal_argument_exception","reason":"Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [START_ARRAY]"},"status":400}
```

please help and explain what I'm doing wrong, I searched the Internet for the answer to my question but did not find
I test insert when using REST client passes without problems

答:
BulkMetaData should be {"index":{"_index":"Test","_id":"1234567890"}} (without []) and it should be sent to /_bulk together with BulkData, as a single payload:

```<code>{"index":{"_index":"Test","_id":"1234567890"}}
{"url":"http://XXXX.XX"}
</code>```

Title: Go elasticsearch bulk insert

Body:
I have been unable to solve the problem into elasticsearch Bulk method for several days, since I am not strong in Go and started learning it not so long ago, while executing the code :

package main

import (
    "bytes"
    json "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type BulkInsertMetaData struct {
    Index []BulkInsertIndex `json:"index"`
}
type BulkInsertIndex struct {
    Index string `json:"_index"`
    ID    string `json:"_id"`
}

type BulInsertData struct {
    Url string `json:"url"`
}

func main() {
    dataMeta := BulkInsertMetaData{
        Index: []BulkInsertIndex{
            {
                Index: "Test",
                ID:    "1234567890",
            },
        },
    }
    data := BulInsertData{
        Url: "http://XXXX.XX",
    }
    TojsBulInsertData, _ := json.Marshal(data)
    TojsBulkInsertMetaData, _ := json.Marshal(dataMeta)
    BulkMetaData := bytes.NewBuffer(append(TojsBulkInsertMetaData, []byte("\n")...))
    BulkData := bytes.NewBuffer(append(TojsBulInsertData, []byte("\n")...))
    log.Println(BulkMetaData)
    log.Println(BulkData)
    respMetaData, err := http.Post("http://127.0.0.1:9200/_bulk", "application/json", BulkMetaData)
    if err != nil {
        log.Println(err)
    }
    body, err := ioutil.ReadAll(respMetaData.Body)
    if err != nil {
        log.Println(err)
    }
    fmt.Println(string(body))
    respBulkData, err := http.Post("http://127.0.0.1:9200/_bulk", "application/json", BulkData)
    if err != nil {
        log.Println(err)
    }
    body2, err := ioutil.ReadAll(respBulkData.Body)
    if err != nil {
        log.Println(err)
    }
    fmt.Println(string(body2))
}

but i get an error:

2022/02/09 14:37:02 {"index":[{"_index":"Test","_id":"1234567890"}]}

2022/02/09 14:37:02 {"url":"http://XXXX.XX"}

{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [START_ARRAY]"}],"type":"illegal_argument_exception","reason":"Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [START_ARRAY]"},"status":400}

please help and explain what I'm doing wrong, I searched the Internet for the answer to my question but did not find
I test insert when using REST client passes without problems

Body:
BulkMetaData should be {"index":{"_index":"Test","_id":"1234567890"}} (without []) and it should be sent to /_bulk together with BulkData, as a single payload:

{"index":{"_index":"Test","_id":"1234567890"}}
{"url":"http://XXXX.XX"}


来源: stackexchange

问:
How to make page-break work with flexbox?
I have an HTML structure as follows:

.container {
display: flex;
flex-direction: column;
}
.item {
height: 500px;
margin-bottom: 20px;
}
.item:nth-child(1){
background: blue;
}
.item:nth-child(2){
background: green;
}
.item:nth-child(3){
background: red;
}
.item:nth-child(4){
background: yellow;
}
.item:nth-child(5){
background: orange;
}
.item:nth-child(6){
background: violet;
}
 @media print {
 .item{
  page-break-before: always;
 }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="window.print()">Print</button>
<div class="container">
<div class="item" style="order: 4;">Four</div>
<div class="item" style="order: 3;">Three</div>
<div class="item" style="order: 5;">Five</div>
<div class="item" style="order: 2;">Two</div>
<div class="item" style="order: 0;">Zero</div>
<div class="item" style="order: 1;">One</div>
</div></code>```

The order is being set from javascript based on some conditions. I would like the page to be printed where each div.item starting on different pages.

@media print {
.item{
   page-break-before: always;
}
}```

Is there a way to achieve this as pagebreak won't work with flexbox and I need to keep the order in which the items are printed on page.

答:
this code doesn't solve the problem to the end, but it can give you new ideas on how to use it in your project

    function printdiv(printpage) {
      var headstr = "<title></title>";
      var footstr = "";
      var newstr = document.all.item(printpage).innerHTML;
      var oldstr = document.body.innerHTML;
      document.body.innerHTML = headstr + newstr + footstr;
      window.print();
      document.body.innerHTML = oldstr;
      return false;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  //HTML Page //Other content you wouldn't like to print
  <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">

  <div id="div_print">
    <h1 style="Color:Red">The Div content which you want to print</h1>
  </div>
  //Other content you wouldn't like to print //Other content you wouldn't like to print</code>```

plugin helps to print different divs github

ContentLicense: CC BY-SA 4.0

Body:
I have an HTML structure as follows:

.container {
display: flex;
flex-direction: column;
}
.item {
height: 500px;
margin-bottom: 20px;
}
.item:nth-child(1){
background: blue;
}
.item:nth-child(2){
background: green;
}
.item:nth-child(3){
background: red;
}
.item:nth-child(4){
background: yellow;
}
.item:nth-child(5){
background: orange;
}
.item:nth-child(6){
background: violet;
}
 @media print {
 .item{
  page-break-before: always;
 }
 }

<button onclick="window.print()">Print</button>

Four

Three

Five

Two

Zero

One

The order is being set from javascript based on some conditions. I would like the page to be printed where each div.item starting on different pages.

@media print {
.item{
   page-break-before: always;
}
}

Is there a way to achieve this as pagebreak won't work with flexbox and I need to keep the order in which the items are printed on page.

Body:
this code doesn't solve the problem to the end, but it can give you new ideas on how to use it in your project

    function printdiv(printpage) {
      var headstr = "<html><head><title></title></head><body>";
      var footstr = "</body>";
      var newstr = document.all.item(printpage).innerHTML;
      var oldstr = document.body.innerHTML;
      document.body.innerHTML = headstr + newstr + footstr;
      window.print();
      document.body.innerHTML = oldstr;
      return false;
    }

  //HTML Page //Other content you wouldn't like to print
  <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">

  <div id="div_print">
    <h1 style="Color:Red">The Div content which you want to print</h1>
  </div>
  //Other content you wouldn't like to print //Other content you wouldn't like to print

plugin helps to print different divs github


问:
Is there a way to put the image just next to the paragraph using flex properties?
I tried setting justify-content to space-between as but that didn't work either.

The image just seems to come just below the paragraph.
But I want it to look like this.

Home.jsx

```<code>import '../App.css';
import './Home.css';
import pic from './portfolio-image.jpeg';
import React, { Component } from 'react';

function Home(){
    return(
        <div className='safe-area'>
            <div id = 'home-container'>

                <div id = 'home-text-container'>
                    <div id='home-head'>
                        Hi, I'm <Name>.
                    </div>

                    <div id = 'home-body'>
                        I am passionate about software and web development. I like solve interesting and new problems through my expertise in coding.
                        I like to work with React, Firebase, MongoDB, Express, Python and more.
                    </div>
                </div>

                <div id = 'image-social-container'>
                    <img src= {pic} />

                </div>

            </div>
        </div>
    );
}

export default Home;
</code>```

Home.css

```<code>#home-container{
    display: flex;
    flex-flow: row wrap;

    align-content: center;
    justify-content: space-between;

    height: 75vh;
    margin-left: 2cm;
    margin-right: 2cm;

    background-color: black;
}

#home-text-container{
    display: flex;
    flex-direction: column;

    width: 50%;
    line-height: 40px;
}

#home-head{
    font-family: 'Roboto', sans-serif;
    font-size: 210%;
    font-weight: 400;
    color: #b8fff1;
}

#home-body{
    font-family: 'Roboto', sans-serif;
    font-size: 140%;
    font-weight: 300;
    color: #b8fff1;
}

#image-social-container{
    display: flex;
    flex-direction: column;
}

#image-social-container img{
    width: 15%;
    border-radius: 10%;

    align-self: flex-end;
}
</code>```

答: You could try to use flex-direction: column on the container.

Body:
I tried setting justify-content to space-between as but that didn't work either.

The image just seems to come just below the paragraph.
But I want it to look like this.

Home.jsx

import '../App.css';
import './Home.css';
import pic from './portfolio-image.jpeg';
import React, { Component } from 'react';

function Home(){
    return(

                        Hi, I'm <Name>.

                        I am passionate about software and web development. I like solve interesting and new problems through my expertise in coding.
                        I like to work with React, Firebase, MongoDB, Express, Python and more.

    );
}

export default Home;

Home.css

#home-container{
    display: flex;
    flex-flow: row wrap;

    align-content: center;
    justify-content: space-between;

    height: 75vh;
    margin-left: 2cm;
    margin-right: 2cm;

    background-color: black;
}

#home-text-container{
    display: flex;
    flex-direction: column;

    width: 50%;
    line-height: 40px;
}

#home-head{
    font-family: 'Roboto', sans-serif;
    font-size: 210%;
    font-weight: 400;
    color: #b8fff1;
}

#home-body{
    font-family: 'Roboto', sans-serif;
    font-size: 140%;
    font-weight: 300;
    color: #b8fff1;
}

#image-social-container{
    display: flex;
    flex-direction: column;
}

#image-social-container img{
    width: 15%;
    border-radius: 10%;

    align-self: flex-end;
}


问:
How to display image from JSON in MVC 3?
I need to display an image from my database. I post a form with some data with Json. After that, I get the result from the database. It's almost the same as a reaction in facebook. You post your comment and you will get your comment formatted and your profileimage on the side.

I managed to get the data back but I don't know how to get the image on the screen...
Should I try to create and url? I tryed that but I don't know how to resolve the url in a javascript file.

Sorry, i'm new with Json and MVC 3.

Thanks

答: It is a bit stupid... I forgot that you could just use the controller and then the action. I did ImageController and not Image so the action wasn't found. Thats why I thought that this wouldn't worked. I now make an url property on the server and send that with Json. That property is rendered in the src attribute of the image tag.</p>

ContentLicense: CC BY-SA 3.0


问:
"Import could not be resolved" reported by Pyright

I've just started using Pyright. Running it on files that run perfectly well I get plenty of errors.

This question is similar, but refers to one's own modules.

For example Import "numpy" could not be resolved. What does it mean, and how do I resolve it?

答: Setting the interpreter as Python with current version worked just fine for me. You can do it by clicking Python in lower left corner and selecting your project.</p>


问:
Module not found: Can't resolve '@material/core/Grid'
I cloned a repository that uses MUI and the following components are already imported when I cloned (they work)

```<code>import Card from '@mui/material/Card'
import CardActions from '@mui/material/CardActions'
import CardContent from '@mui/material/CardContent'
import CardMedia from '@mui/material/CardMedia'
import Typography from '@mui/material/Typography'
</code>```

then I tried to import Grid from '@material/core/Grid' but got the error Module not found: Can't resolve '@material/core/Grid' even though I ran the following commands both in the repository folder as well as "/Downloads":

```<code>npm install @material-ui/core
npm install
npm install @material-ui/core/Grid
</code>```

I can provide more info if needed

答:
You see how all the working components are @mui/material/SOMETHING?

Also see the documentation for Grid.

It's import Grid from '@mui/material/Grid'; not from '@material/core/Grid'.

Body:
I cloned a repository that uses MUI and the following components are already imported when I cloned (they work)

import Card from '@mui/material/Card'
import CardActions from '@mui/material/CardActions'
import CardContent from '@mui/material/CardContent'
import CardMedia from '@mui/material/CardMedia'
import Typography from '@mui/material/Typography'

then I tried to import Grid from '@material/core/Grid' but got the error Module not found: Can't resolve '@material/core/Grid' even though I ran the following commands both in the repository folder as well as "/Downloads":

npm install @material-ui/core
npm install
npm install @material-ui/core/Grid

I can provide more info if needed


问:
How to get two lines of text fixed at positions?
How can I achieve from this

to this

when resizing the browser.
For your information, these are the lines of lyrics with chords. I want to achieve exact same fixed position of chords above lyrics to make it responsive. I am using HTML, CSS.
Anybody, please help.

.lines {
    margin: 5px 0;
}

.lyrics,.notes {
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
    color: rgb(45, 45, 45);
    font-weight: 600;
}

.lines>span:first-child:after {
    content: "\A";
    white-space: pre-line;
}

.notes {
    color: rgb(0, 150, 0);
    background-color: rgb(241, 241, 241);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lines">
        <span>                             <span class="notes">G</span>                 <span class="notes">Em</span></span>
        <span class="lyrics">Well, I found a girl, beautiful and sweet</span>
        </div>

        <div class="lines">
        <span>                      <span class="notes">C</span>                                                                            <span class="notes">D</span></span>
        <span class="lyrics">Oh, I never knew you were the someone waiting for me</span>
        </div></code>```

答:
this way...

(()=>  // IIFE code on load for lyrics presentation
  {
  const rgxCut   = /(?=\[)|(?<=\])/;

  document.querySelectorAll('div.lyrics p').forEach( pLine =>
    {
    let newP = pLine.textContent
    .replaceAll('] [','] [')
    .split(rgxCut)
    .map( el =>
      {
      if (el[0]!=='[') return el
      let chord = el.substring(1,el.length-1)
      return `<span class="chord" data-chord="${chord}"></span>`
      })
    pLine.innerHTML = newP.join('')
    })
  }
)()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* --- for testing --- */
body {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 20px;
  }
.reSizable {
  resize   : both;
  overflow : scroll;
  padding  : .5em;
  border   : 1px solid orange;
  }
/* ------------------- */

div.lyrics p  {
  line-height : 2.5em;
  }
div.lyrics p span[data-chord] {
  position : relative
  }
div.lyrics p span[data-chord]::after {
  position   : absolute;
  top         : -1.2em;
  left        : -.1em;
  line-height : 1.2em;
  padding     : 0 .2em;
  font-size   : .9em;
  color       : darkgreen;
  background  : lightgrey;
  content     : attr(data-chord);
  }</code>```

Well, I found a [G]girl, beauti[Em]full and sweet

Oh, I never [C]knew you where the someone waiting for [D]me

```

Body:
How can I achieve from this

to this

when resizing the browser.
For your information, these are the lines of lyrics with chords. I want to achieve exact same fixed position of chords above lyrics to make it responsive. I am using HTML, CSS.
Anybody, please help.

.lines {
    margin: 5px 0;
}

.lyrics,.notes {
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
    color: rgb(45, 45, 45);
    font-weight: 600;
}

.lines>span:first-child:after {
    content: "\A";
    white-space: pre-line;
}

.notes {
    color: rgb(0, 150, 0);
    background-color: rgb(241, 241, 241);
}

                                     G                 Em
        Well, I found a girl, beautiful and sweet

                              C                                                                            D
        Oh, I never knew you were the someone waiting for me

Body:
this way...

(()=>  // IIFE code on load for lyrics presentation
  {
  const rgxCut   = /(?=\[)|(?<=\])/;

  document.querySelectorAll('div.lyrics p').forEach( pLine =>
    {
    let newP = pLine.textContent
    .replaceAll('] [',']&emsp;[')
    .split(rgxCut)
    .map( el =>
      {
      if (el[0]!=='[') return el
      let chord = el.substring(1,el.length-1)
      return `<span class="chord" data-chord="${chord}"></span>`
      })
    pLine.innerHTML = newP.join('')
    })
  }
)()

/* --- for testing --- */
body {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 20px;
  }
.reSizable {
  resize   : both;
  overflow : scroll;
  padding  : .5em;
  border   : 1px solid orange;
  }
/* ------------------- */

div.lyrics p  {
  line-height : 2.5em;
  }
div.lyrics p span[data-chord] {
  position : relative
  }
div.lyrics p span[data-chord]::after {
  position   : absolute;
  top         : -1.2em;
  left        : -.1em;
  line-height : 1.2em;
  padding     : 0 .2em;
  font-size   : .9em;
  color       : darkgreen;
  background  : lightgrey;
  content     : attr(data-chord);
  }

<div class="reSizable">

    <div class="lyrics">
      <p>Well, I found a [G]girl, beauti[Em]full and sweet</p>
      <p>Oh, I never [C]knew you where the someone waiting for [D]me</p>
    </div>

</div>


问:
SQLite complains about null values in a column lacking a NOT NULL constraint
I'm getting a curious error when inserting a record into a SQLite table.
This is from the logs of a customer:

Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'NOT NULL constraint failed: Events.details'.
   at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
   at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
   at SqliteDemo.LogEvent(...) in ...
```
<p>The pertinent bit of diagnostics is obviously this:</p>
```SQLite Error 19: 'NOT NULL constraint failed: Events.details'
```
<p>…which seems clear enough, except for one thing: The <code>details</code> column lacks a <code>NOT NULL</code> constraint:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE IF NOT EXISTS Events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name STRING NOT NULL,
    time INTEGER NOT NULL,
    code INTEGER NOT NULL,
    details STRING,
    message STRING NOT NULL,
    status INTEGER NOT NULL )
</code>```

I don't know the values that failed to insert, so an obvious next step would be to improve my diagnostics and wait for it to happen again. Or I could just add null guards to
make sure it never happens again and forget about the whole thing.

But I'm curious:

Is it possible that SQLite's diagnostics are in error, and that it is one of the
NOT NULL columns that is the actual culprit?

Why don't my unit tests have a problem with null detail values?

Can this be related to SQLite's dynamic approach to typing?

…or something completely different?

Any ideas?

Environment

Targeting .NET Framework 4.8 on Windows 10

Using Microsoft.Data.Sqlite 5.0.14

(not System.Data.SQLite – though I'm unsure whether the distinction is relevant).

Code

I can't post our production code here.
Instead, here is a complete, stand-alone C# program that I believe closely parallels the production code in all pertinent aspects.

using System;
using Microsoft.Data.Sqlite;

class SqliteDemo
{
    static void Main()
    {
        SqliteDemo demo = new SqliteDemo();
        demo.LogEvent("name 1", DateTime.Now, 42, "details", "message 1", 0);
        demo.LogEvent("name 2", DateTime.Now, 42, null, "message 2", 0); //*** Works...
    }

    readonly string connectionString = new SqliteConnectionStringBuilder
    {
        DataSource = "Test.db",
        Mode = SqliteOpenMode.ReadWriteCreate,
    }.ConnectionString;

    const string CreateTableSql =
        @"CREATE TABLE IF NOT EXISTS Events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name STRING NOT NULL,
            time INTEGER NOT NULL,
            code INTEGER NOT NULL,
            details STRING,
            message STRING NOT NULL,
            status INTEGER NOT NULL
        )";

    int LogEvent(string name, DateTime time,
            int code, string details, string message, short status)
    {
        using (SqliteConnection connection = CreateOpenConnection())
        {
            using (SqliteCommand command = CreateCommand(connection,
                "INSERT INTO Events(name, time, code, details, message, status) " +
                "VALUES(@name, @time, @code, @details, @message, @status)"))
            {
                AddParameter(command, "name", name);
                AddParameter(command, "time", time);
                AddParameter(command, "code", code);
                AddParameter(command, "details", details);
                AddParameter(command, "message", message);
                AddParameter(command, "status", status);

                return command.ExecuteNonQuery(); //*** SOMETIMES throws
            }
        }
    }

    static void AddParameter(SqliteCommand command, string name, object value)
    {
        command.Parameters.Add(new SqliteParameter(name, value ?? DBNull.Value));
    }

    static SqliteCommand CreateCommand(SqliteConnection connection, string sql)
    {
        SqliteCommand command = connection.CreateCommand();
        command.CommandText = sql;
        return command;
    }

    SqliteConnection CreateOpenConnection()
    {
        SqliteConnection connection = new SqliteConnection(connectionString);
        connection.Open();
        CreateTableIfNecessary(connection);
        return connection;
    }

    void CreateTableIfNecessary(SqliteConnection connection)
    {
        using (SqliteCommand command = CreateCommand(connection, CreateTableSql))
        {
            command.ExecuteNonQuery();
        }
    }
}
```

答: From your code, it looks like you are passing message to your procedure, and in one case its value is null. But in a create table script you have a constraint message STRING NOT NULL which throws an error on insert (as null is not allowed to message column). Try to put empty string instead of null and see if the same error occurs.

Body:
I'm getting a curious error when inserting a record into a SQLite table.
This is from the logs of a customer:

Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'NOT NULL constraint failed: Events.details'.
   at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
   at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
   at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
   at SqliteDemo.LogEvent(...) in ...

The pertinent bit of diagnostics is obviously this:

SQLite Error 19: 'NOT NULL constraint failed: Events.details'

…which seems clear enough, except for one thing: The details column lacks a NOT NULL constraint:

CREATE TABLE IF NOT EXISTS Events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name STRING NOT NULL,
    time INTEGER NOT NULL,
    code INTEGER NOT NULL,
    details STRING,
    message STRING NOT NULL,
    status INTEGER NOT NULL )

I don't know the values that failed to insert, so an obvious next step would be to improve my diagnostics and wait for it to happen again. Or I could just add null guards to
make sure it never happens again and forget about the whole thing.

But I'm curious:

Is it possible that SQLite's diagnostics are in error, and that it is one of the
NOT NULL columns that is the actual culprit?

Why don't my unit tests have a problem with null detail values?

Can this be related to SQLite's dynamic approach to typing?

…or something completely different?

Any ideas?

Environment

Targeting .NET Framework 4.8 on Windows 10

Using Microsoft.Data.Sqlite 5.0.14

(not System.Data.SQLite – though I'm unsure whether the distinction is relevant).

Code

I can't post our production code here.
Instead, here is a complete, stand-alone C# program that I believe closely parallels the production code in all pertinent aspects.

using System;
using Microsoft.Data.Sqlite;

class SqliteDemo
{
    static void Main()
    {
        SqliteDemo demo = new SqliteDemo();
        demo.LogEvent("name 1", DateTime.Now, 42, "details", "message 1", 0);
        demo.LogEvent("name 2", DateTime.Now, 42, null, "message 2", 0); //*** Works...
    }

    readonly string connectionString = new SqliteConnectionStringBuilder
    {
        DataSource = "Test.db",
        Mode = SqliteOpenMode.ReadWriteCreate,
    }.ConnectionString;

    const string CreateTableSql =
        @"CREATE TABLE IF NOT EXISTS Events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name STRING NOT NULL,
            time INTEGER NOT NULL,
            code INTEGER NOT NULL,
            details STRING,
            message STRING NOT NULL,
            status INTEGER NOT NULL
        )";

    int LogEvent(string name, DateTime time,
            int code, string details, string message, short status)
    {
        using (SqliteConnection connection = CreateOpenConnection())
        {
            using (SqliteCommand command = CreateCommand(connection,
                "INSERT INTO Events(name, time, code, details, message, status) " +
                "VALUES(@name, @time, @code, @details, @message, @status)"))
            {
                AddParameter(command, "name", name);
                AddParameter(command, "time", time);
                AddParameter(command, "code", code);
                AddParameter(command, "details", details);
                AddParameter(command, "message", message);
                AddParameter(command, "status", status);

                return command.ExecuteNonQuery(); //*** SOMETIMES throws
            }
        }
    }

    static void AddParameter(SqliteCommand command, string name, object value)
    {
        command.Parameters.Add(new SqliteParameter(name, value ?? DBNull.Value));
    }

    static SqliteCommand CreateCommand(SqliteConnection connection, string sql)
    {
        SqliteCommand command = connection.CreateCommand();
        command.CommandText = sql;
        return command;
    }

    SqliteConnection CreateOpenConnection()
    {
        SqliteConnection connection = new SqliteConnection(connectionString);
        connection.Open();
        CreateTableIfNecessary(connection);
        return connection;
    }

    void CreateTableIfNecessary(SqliteConnection connection)
    {
        using (SqliteCommand command = CreateCommand(connection, CreateTableSql))
        {
            command.ExecuteNonQuery();
        }
    }
}


问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
const Dict *dict means this is a pointer to constant Dict values

you could modify the pointer, but not the values;

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?


问:
How to concatenate a newly added file to pandas dataframe?
I am trying to write a script which will be grabbing newly added csv file from the folder and adding it to one big file. Basically, I want all of the csv files added to a particular folder, being stored in one resulting csv file. I have a code below which generates the list of files and I am selecting the newly added file there:

```<code>def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp)
                fh[f] = fs

    return total_size

def new_file(fp):
    print("New File {0}!".format(fp))

def changed_file(fp):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/Users/.../Desktop/files',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(200)
        print("File list:\n{0}".format(file_history))
        print(list(dict.keys(file_history))[-1])
</code>```

I don't really know how to create this empty pandas data frame to which this latest added file will be added on a regular basis (that's why I have a time.sleep there). In the end I want to have this big csv file with all the files added to it.

Please, help :(

P.S. I am new to Python, so please don't judge if it is super simple..

答:
Are you going to be using Pandas to process the data in the csv or only to concatenate the files?

If you simply want to append each csv file to the big one, then why not use python io for speed and simplicity. Assuming that all csv files use the same type of formatting that is.

I have updated the new_file method to append to the big csv using io. I have added an append_pandas function which is not used but should help you if you must use pandas to do the job. I haven't tested the pandas function, there are more things to consider like the format of the csv files. Check out the documentation for more details.

```<code>import os
import time

def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None,**kwargs):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp,**kwargs)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp, **kwargs)
                fh[f] = fs

    return total_size

def is_csv(f):
    # you can add more to check here
    return 'csv' in f

def append_csv(s,d,skip_header=1):

    with open(s,'r') as readcsv:
        with open(d,'a') as appendcsv:
            for line in readcsv:
                if(skip_header < 1):
                    appendcsv.write(line)
                else:
                    skip_header -= 1

            if not "\n" in line:
                appendcsv.write("\n")

def append_pandas(s,d):
    # i haven't tested this
    pd = pandas.read_csv(s)
    pdb = pandas.read_csv(d)
    newpd = pdb.append(pd)
    DataFrame.to_csv(d)

def new_file(fp, **kwargs):
    if is_csv(fp):
        print("Appending {0}!".format(fp))
        bcsv = kwargs.get('append_to_csv','/default/path/to/big.csv')
        skip = kwargs.get('skip_header',1)
        append_csv(fp,bcsv,skip)

def changed_file(fp, **kwargs):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/tmp/test/',new_file,changed_file, append_to_csv ='/tmp/big.csv', skip_header = 1)
        if total and ns != total:
            print("Total size changed from {0} to {1}".format(total,ns))
            total = ns
        time.sleep(10)
        print("File list:\n{0}".format(file_history))

</code>```

Body:
I am trying to write a script which will be grabbing newly added csv file from the folder and adding it to one big file. Basically, I want all of the csv files added to a particular folder, being stored in one resulting csv file. I have a code below which generates the list of files and I am selecting the newly added file there:

def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp)
                fh[f] = fs

    return total_size

def new_file(fp):
    print("New File {0}!".format(fp))

def changed_file(fp):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/Users/.../Desktop/files',new_file,changed_file)
        if total and nt != total:
            print("Total size changed from {0} to {1}".format(total,nt))
            total = nt
        time.sleep(200)
        print("File list:\n{0}".format(file_history))
        print(list(dict.keys(file_history))[-1])

I don't really know how to create this empty pandas data frame to which this latest added file will be added on a regular basis (that's why I have a time.sleep there). In the end I want to have this big csv file with all the files added to it.

Please, help :(

P.S. I am new to Python, so please don't judge if it is super simple..

Body:
Are you going to be using Pandas to process the data in the csv or only to concatenate the files?

If you simply want to append each csv file to the big one, then why not use python io for speed and simplicity. Assuming that all csv files use the same type of formatting that is.

I have updated the new_file method to append to the big csv using io. I have added an append_pandas function which is not used but should help you if you must use pandas to do the job. I haven't tested the pandas function, there are more things to consider like the format of the csv files. Check out the documentation for more details.

import os
import time

def check_dir(fh,start_path='/Users/.../Desktop/files',new_cb=None,changed_cb=None,**kwargs):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                fs = os.path.getsize(fp)
                total_size += fs
                if f in fh:
                    if fh[f] == fs:
                        # file unchanged
                        pass
                    else:
                        if changed_cb:
                            changed_cb(fp,**kwargs)
                else:
                    #new file
                    if new_cb:
                        new_cb(fp, **kwargs)
                fh[f] = fs

    return total_size

def is_csv(f):
    # you can add more to check here
    return 'csv' in f

def append_csv(s,d,skip_header=1):

    with open(s,'r') as readcsv:
        with open(d,'a') as appendcsv:
            for line in readcsv:
                if(skip_header < 1):
                    appendcsv.write(line)
                else:
                    skip_header -= 1

            if not "\n" in line:
                appendcsv.write("\n")

def append_pandas(s,d):
    # i haven't tested this
    pd = pandas.read_csv(s)
    pdb = pandas.read_csv(d)
    newpd = pdb.append(pd)
    DataFrame.to_csv(d)

def new_file(fp, **kwargs):
    if is_csv(fp):
        print("Appending {0}!".format(fp))
        bcsv = kwargs.get('append_to_csv','/default/path/to/big.csv')
        skip = kwargs.get('skip_header',1)
        append_csv(fp,bcsv,skip)

def changed_file(fp, **kwargs):
    print("File {0} changed!".format(fp))

if __name__ == '__main__':
    file_history={}
    total = 0

    while(True):
        nt = check_dir(file_history,'/tmp/test/',new_file,changed_file, append_to_csv ='/tmp/big.csv', skip_header = 1)
        if total and ns != total:
            print("Total size changed from {0} to {1}".format(total,ns))
            total = ns
        time.sleep(10)
        print("File list:\n{0}".format(file_history))


问:
Parse a string between 2 delimiters
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

```<code>substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
</code>```

It will work if I remove the ">", so i am at a lost of my next step

```<code>SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc
</code>```

Desired output would be except for site I would just want "Skyline":
output

答:
Please try the following solution.

It will work starting from SQL Server 2016 onwards.

We are converting the Site column into a JSON array.
After that it is very easy to pickup a needed token based on its position.

SQL

```<code>-- DDL and sample data population, start
DECLARE @RawAnalog TABLE (ID INT IDENTITY PRIMARY KEY, Site VARCHAR(100));
INSERT INTO @RawAnalog (Site) VALUES
('XRDCWPDBSADX02:SKYLINE-NAE04/FC-1'),
('XRDCWPDBSADX02:SKYLINE-NAE04/FC-2');
-- DDL and sample data population, end

SELECT *
    , Token  = JSON_VALUE(s, '$[1]')
FROM @RawAnalog
    CROSS APPLY (VALUES ('["'+REPLACE(STRING_ESCAPE(REPLACE(Site,':','-'),'json'),'-','","')+'"]')) As j(s);
</code>```

Output

```<code>+----+-----------------------------------+----------------------------------------------+---------+
| ID |               Site                |                      s                       |  Token  |
+----+-----------------------------------+----------------------------------------------+---------+
|  1 | XRDCWPDBSADX02:SKYLINE-NAE04/FC-1 | ["XRDCWPDBSADX02","SKYLINE","NAE04\/FC","1"] | SKYLINE |
|  2 | XRDCWPDBSADX02:SKYLINE-NAE04/FC-2 | ["XRDCWPDBSADX02","SKYLINE","NAE04\/FC","2"] | SKYLINE |
+----+-----------------------------------+----------------------------------------------+---------+
</code>```

Title: Parse a string between 2 delimiters

Body:
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)

It will work if I remove the ">", so i am at a lost of my next step

SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc

Desired output would be except for site I would just want "Skyline":
output

Body:
Please try the following solution.

It will work starting from SQL Server 2016 onwards.

We are converting the Site column into a JSON array.
After that it is very easy to pickup a needed token based on its position.

SQL

-- DDL and sample data population, start
DECLARE @RawAnalog TABLE (ID INT IDENTITY PRIMARY KEY, Site VARCHAR(100));
INSERT INTO @RawAnalog (Site) VALUES
('XRDCWPDBSADX02:SKYLINE-NAE04/FC-1'),
('XRDCWPDBSADX02:SKYLINE-NAE04/FC-2');
-- DDL and sample data population, end

SELECT *
    , Token  = JSON_VALUE(s, '$[1]')
FROM @RawAnalog
    CROSS APPLY (VALUES ('["'+REPLACE(STRING_ESCAPE(REPLACE(Site,':','-'),'json'),'-','","')+'"]')) As j(s);

Output

+----+-----------------------------------+----------------------------------------------+---------+
| ID |               Site                |                      s                       |  Token  |
+----+-----------------------------------+----------------------------------------------+---------+
|  1 | XRDCWPDBSADX02:SKYLINE-NAE04/FC-1 | ["XRDCWPDBSADX02","SKYLINE","NAE04\/FC","1"] | SKYLINE |
|  2 | XRDCWPDBSADX02:SKYLINE-NAE04/FC-2 | ["XRDCWPDBSADX02","SKYLINE","NAE04\/FC","2"] | SKYLINE |
+----+-----------------------------------+----------------------------------------------+---------+


问:
How to add a condition to a for loop in Kotlin?
I know that in Java, it is possible to do the following:

```<code>boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}
</code>```

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?

答:
there is no such option in Kotlin (availabe constructions in HERE), but you can add additional check and break keyword

```<code>for (i in 0..array.length) {
    if (!condition) break; // quit loop without further iteration
    //rest of code
</code>```

Body:
I know that in Java, it is possible to do the following:

boolean condition = true;

for(int i=0; i<array.length && condition; i++){

}

If the condition is false, the for loop stops,
but, how to do the same in Kotlin?

Body:
there is no such option in Kotlin (availabe constructions in HERE), but you can add additional check and break keyword

for (i in 0..array.length) {
    if (!condition) break; // quit loop without further iteration
    //rest of code


问:
Convert Integers to Dollar Format in Oracle Database
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

```<code>SELECT value AS "Valuation" FROM estimates;
</code>```

Result:

Instead, I would like to show:

```<code>$115,508
$38,150
$92,832
$116,222
</code>```

How can I convert the integers into dollar $ format?

答:
Can get rid of the left spaces if you really want that:

```<code>SQL> SELECT ltrim(to_char(value,'$999,999')) AS "Valuation" FROM estimates;

Valuation
---------
$115,508
$38,150
$92,832
$116,222
</code>```

Bobby

Body:
I'm using Oracle Database version 12.1.0.2.0. I'm running a query that returns integers that is actually a dollar amount:

SELECT value AS "Valuation" FROM estimates;

Result:

Instead, I would like to show:

$115,508
$38,150
$92,832
$116,222

How can I convert the integers into dollar $ format?

Body:
Can get rid of the left spaces if you really want that:

SQL> SELECT ltrim(to_char(value,'$999,999')) AS "Valuation" FROM estimates;

Valuation
---------
$115,508
$38,150
$92,832
$116,222

Bobby


问:
receive in flask json converted and form data
I have a API in flask. The objetive is to receive a converted csv file (function in javascript) and form data in flask separate. Form data is metadata and csv file converted to json is data.
I'm only getting the form data, the json file i'm getting none.

My json converted from csv file it's store in variable result and form data is stored in formdata. I send the two variable separated. I'm receiving all the data that i insert in HTML. The JSON that result from a function that convert csv files to json i'm not getting in flask side.

```<code>HTML
<!DOCTYPE html>
<html lang="PT">
  <head>
    <meta charset="utf-8">
    <title>Register</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="/static/sendform.js"> </script>
    <link href="{{url_for('static', filename='css/mainpage.css')}}" rel="stylesheet" type="text/css">
  </head>
  <body>
    <div id="upper_left"></div>
      <div id="upper_right"></div>
      <div id="lower_left"></div>
      <div id="lower_right"></div>
    <div class="container">
      <div class="title">Metadados - Dados relacionados com o Atleta</div>
      <form action="index" method="post">
        <div class="user-details">
          <div class="input-box">
            <span class="details">Nome Completo</span>
            <input type="text" name="fullName" placeholder="Introduza o nome completo do atleta">
          </div>
          <div class="input-box">
            <span class="details">Data de Nascimento</span>
            <input type="text" name="birthdate" placeholder="Introduza a data de nascimento do atleta">
          </div>
          <div class="input-box">
            <span class="details">Altura</span>
            <input type="text" name="height" placeholder="Introduza a altura do atleta em cm">
          </div>
          <div class="input-box">
            <span class="details">Peso</span>
            <input type="text" name="weight" placeholder="Introduza o peso do atleta em kg">
          </div>
          <div class="input-box">
            <span class="details">Tamanho da Piscina</span>
            <input type="text" name="poolsize" placeholder="Introduza o tamanho da piscina">
          </div>
          <div class="input-box">
            <span class="details">Modalidade</span>
            <input type="text" name="modality" placeholder="Introduza a modalidade">
          </div>
          <div class="input-box">
            <span class="details">Estilo(s) de Natação</span>
            <input type="text" name="swimStyle" placeholder="Introduza o estilo(s) de natação">
          </div>
          <div class="input-box">
            <span class="details">Género</span>
            <select name="gender">
              <option value ="gender">Selecionar genéro</option>
              <option value ="masculino">Masculino</option>
              <option value ="feminino">Feminino</option>
            </select>
          <div class="input-box">
            <span class="details">Escalão Etário</span>
            <select name="gender-title">
              <option value ="gender-title">Select gender group</option>
              <option value ="Escola_de_natacao">ESCOLA DE NATACAO</option>
              <option value ="grupos_de_natacao_desportiva">GRUPOS DE FORMACAO DESPORTIVA</option>
              <option value ="cadeteA">CADETES A</option>
              <option value ="cadeteB">CADETES B</option>
              <option value ="infatilB">INFANTIS B</option>
              <option value ="infatilA">INFANTIS A</option>
              <option value ="juvenilB">JUVENIS B</option>
              <option value ="juvenilA">JUVENIS A</option>
              <option value ="junior">JUNIORES</option>
              <option value ="senior">SENIORES</option>
            </select>
          </div>
          <div class="title">Metadados Envio de dados</div>
          <div class="input-box">
            <span class="details">Utilizador Id</span>
            <input type="text" name="userId" placeholder="Introduza o seu Id">
          </div>
          <div class="input-box">
            <span class="details">Token</span>
            <input type="text" name="token" placeholder="Introduza o token">
          </div>
          <p>Selecionar o ficheiro localmente:</p>
          <input name="myFile" type="file" accept=".txt,.xlsx, .xls, .csv" >
          <div class="button">
            <input type="submit" id="btn-post" value="Enviar dados" onclick="do_ajax();">
            <div class="input-box"></dix>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>
</code>```

Javascript

```<code>function do_ajax() {
  var input = document.querySelector('input').files;
  if(!input.length){
    alert("No file selected");
    return;
  }
  var file = input[0];
  var reader = new FileReader();
  reader.onload = (function() {
    return function(e) {
      var fileData = e.target.result.trim().split('\n').map(row => row.split(','));
      var HEADERS = ["time", "yaw", "pitch", "roll", "heading", "ax", "ay", "az", "gx", "gy", "gz", "mx", "my", "mz"];
      const RESULT = {};
      // Assign every heading to the result.
      for (const HEADING of HEADERS) RESULT[HEADING] = [];
      fileData.map(row =>
          // Each row → each column, number of columns === number of headers
          row.map((column, i) =>
            RESULT[HEADERS[i]]
            .push(Number(column))
          ));
        console.log(RESULT);
      };
  })(file);
    reader.readAsText(file);;
    let fullName = document.getElementById('fullName').value;
    let birthdate = document.getElementById('birthdate').value;
    let height = document.getElementById('height').value;
    let weight = document.getElementById('weight').value;
    let poolsize = document.getElementById('poolsize').value;
    let modality = document.getElementById('modality').value;
    let swimStyle = document.getElementById('swimStyle').value;
    var tel = document.getElementById('gender').value;
    var sel = document.getElementById('gender-title').value;
    console.log(sel.value);
    const formdata = new FormData();
    formdata.append("fullName", fullName)
    formdata.append("birthdate",birthdate)
    formdata.append("weight",weight)
    formdata.append("height",height)
    formdata.append("poolsize",poolsize)
    formdata.append("modality",modality)
    formdata.append("swimStyle",swimStyle)
    formdata.append("gender",tel)
    formdata.append("gender-title",sel)
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/index', true);
    xhr.send(formdata);
    xhr.send(JSON.stringify(RESULT));
  };
</code>```
```<code>FLASK

from flask import Flask, request, render_template
import pymongo
import json

app = Flask(__name__)
app.debug = True

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == "POST":
        name = request.form["fullName"]
        birthdate =request.form["birthdate"]
        poolsize =request.form["poolsize"]
        height =request.form["height"]
        weight =request.form["weight"]
        modality =request.form["modality"]
        swimStyle =request.form["swimStyle"]
        gender = request.form["gender"]
        gender_title = request.form["gender-title"]
        output = request.get_json()
        print(output)
        print (name,birthdate,poolsize,height,weight,modality,swimStyle)
        alldata = { "sessionData": output,
                   "metadata":{ "birthdate": birthdate, "Name": name,
                                "Weight": height,"Pool_size":poolsize,
                                "Weight":weight,"Gender":gender,"Gender_title":gender_title,
                                "modality":modality, "swimStyle": swimStyle}}
        return alldata,200
    else:
        return render_template('index.html')

if __name__ == "__main__":
    app.run()

</code>```

答:
A data transfer can only conform to one format. This formatting is either an encoding for a form or corresponds to JSON formatting.

You can still send the data within one request.
Either you add the JSON-formatted data as a field to the form, or you convert the form data into a JSON structure.

With the first variant, it is necessary to read the JSON data manually on the server side. You can use the python json library for this. For the latter, the framework does this work.

A third option is to transfer the file within the form and simply read it on the server side.

Whichever option you choose, don't forget to validate the inputs.

In the following example, all form data is converted to JSON and sent to the server. I shortened the code a bit for clarity.

The version of adding JSON formatted data to the form data should be self-explanatory.

I think the best solution is to read the file server side.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Read CSV to JSON</title>
  </head>
  <body>
    <form name="my-form" method="post" enctype="" enctype="multipart/form-data">
      <input type="text" name="name" />
      <!-- ... -->
      <input type="file" name="csv" allow="text/csv" />
      <input type="submit" />
    </form>

    <script type="text/javascript">
      ((uri) => {

        function readCSV(file, delim=',') {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onerror = reject;
            reader.onload = (evt) => {
              resolve(evt.target.result.split(/\r\n|\n/).map(line => line.split(delim)));
            };
            reader.readAsText(file);
          });
        }

        function serialize(formData) {
          const data = {};
          for (const [k, v] of formData) data[k] = v;
          return data;
        }

        // Register a listener for submit events and suppress the default behavior of the form.
        const form = document.querySelector('form[name="my-form"]');
        form.addEventListener('submit', async evt => {
          evt.preventDefault();

          if(!evt.target.csv.files.length) {
            alert('No file selected.');
            return;
          }

          const file = evt.target.csv.files[0];
          const formData = new FormData(evt.target);
          formData.delete('csv');
          // Conversion of the form data into an object.
          const data = serialize(formData);
          // Reading and converting the file into a list of objects.
          // Adding the list to the previous object.
          data['csv'] = await readCSV(file, ',')
            .then(csv => {
              const head = ['time', 'yaw', 'pitch', 'roll', 'heading', 'ax',
                            'ay', 'az', 'gx', 'gy', 'gz', 'mx', 'my', 'mz'];
              return csv.map(row => {
                let r = {};
                row.forEach((col, i) => r[head[i]] = Number(col));
                return r;
              });
            });

          // Sending the JSON data to the server.
          fetch(uri, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          }).then(resp => resp.json())
            .then(data => console.log(data));
        });

      })({{ url_for('.data') | tojson }});
    </script>
  </body>
</html>
</code>```
```<code>from flask import Flask
from flask import (
    jsonify,
    render_template,
    request,
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/data', methods=['POST'])
def data():
    data = request.json
    print(data)
    return jsonify(success=True)
</code>```

Body:
I have a API in flask. The objetive is to receive a converted csv file (function in javascript) and form data in flask separate. Form data is metadata and csv file converted to json is data.
I'm only getting the form data, the json file i'm getting none.

My json converted from csv file it's store in variable result and form data is stored in formdata. I send the two variable separated. I'm receiving all the data that i insert in HTML. The JSON that result from a function that convert csv files to json i'm not getting in flask side.

HTML
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Register</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="{{url_for('static', filename='css/mainpage.css')}}" rel="stylesheet" type="text/css">

Metadados - Dados relacionados com o Atleta

      <form action="index" method="post">

            Nome Completo
            <input type="text" name="fullName" placeholder="Introduza o nome completo do atleta">

            Data de Nascimento
            <input type="text" name="birthdate" placeholder="Introduza a data de nascimento do atleta">

            Altura
            <input type="text" name="height" placeholder="Introduza a altura do atleta em cm">

            Peso
            <input type="text" name="weight" placeholder="Introduza o peso do atleta em kg">

            Tamanho da Piscina
            <input type="text" name="poolsize" placeholder="Introduza o tamanho da piscina">

            Modalidade
            <input type="text" name="modality" placeholder="Introduza a modalidade">

            Estilo(s) de Natação
            <input type="text" name="swimStyle" placeholder="Introduza o estilo(s) de natação">

            Género
            <select name="gender">
              <option value ="gender">Selecionar genéro</option>
              <option value ="masculino">Masculino</option>
              <option value ="feminino">Feminino</option>
            </select>

            Escalão Etário
            <select name="gender-title">
              <option value ="gender-title">Select gender group</option>
              <option value ="Escola_de_natacao">ESCOLA DE NATACAO</option>
              <option value ="grupos_de_natacao_desportiva">GRUPOS DE FORMACAO DESPORTIVA</option>
              <option value ="cadeteA">CADETES A</option>
              <option value ="cadeteB">CADETES B</option>
              <option value ="infatilB">INFANTIS B</option>
              <option value ="infatilA">INFANTIS A</option>
              <option value ="juvenilB">JUVENIS B</option>
              <option value ="juvenilA">JUVENIS A</option>
              <option value ="junior">JUNIORES</option>
              <option value ="senior">SENIORES</option>
            </select>

Metadados Envio de dados

            Utilizador Id
            <input type="text" name="userId" placeholder="Introduza o seu Id">

            Token
            <input type="text" name="token" placeholder="Introduza o token">

Selecionar o ficheiro localmente:

          <input name="myFile" type="file" accept=".txt,.xlsx, .xls, .csv" >

            <input type="submit" id="btn-post" value="Enviar dados" onclick="do_ajax();">

</dix>

      </form>

Javascript

function do_ajax() {
  var input = document.querySelector('input').files;
  if(!input.length){
    alert("No file selected");
    return;
  }
  var file = input[0];
  var reader = new FileReader();
  reader.onload = (function() {
    return function(e) {
      var fileData = e.target.result.trim().split('\n').map(row => row.split(','));
      var HEADERS = ["time", "yaw", "pitch", "roll", "heading", "ax", "ay", "az", "gx", "gy", "gz", "mx", "my", "mz"];
      const RESULT = {};
      // Assign every heading to the result.
      for (const HEADING of HEADERS) RESULT[HEADING] = [];
      fileData.map(row =>
          // Each row → each column, number of columns === number of headers
          row.map((column, i) =>
            RESULT[HEADERS[i]]
            .push(Number(column))
          ));
        console.log(RESULT);
      };
  })(file);
    reader.readAsText(file);;
    let fullName = document.getElementById('fullName').value;
    let birthdate = document.getElementById('birthdate').value;
    let height = document.getElementById('height').value;
    let weight = document.getElementById('weight').value;
    let poolsize = document.getElementById('poolsize').value;
    let modality = document.getElementById('modality').value;
    let swimStyle = document.getElementById('swimStyle').value;
    var tel = document.getElementById('gender').value;
    var sel = document.getElementById('gender-title').value;
    console.log(sel.value);
    const formdata = new FormData();
    formdata.append("fullName", fullName)
    formdata.append("birthdate",birthdate)
    formdata.append("weight",weight)
    formdata.append("height",height)
    formdata.append("poolsize",poolsize)
    formdata.append("modality",modality)
    formdata.append("swimStyle",swimStyle)
    formdata.append("gender",tel)
    formdata.append("gender-title",sel)
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/index', true);
    xhr.send(formdata);
    xhr.send(JSON.stringify(RESULT));
  };

FLASK

from flask import Flask, request, render_template
import pymongo
import json

app = Flask(__name__)
app.debug = True

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    if request.method == "POST":
        name = request.form["fullName"]
        birthdate =request.form["birthdate"]
        poolsize =request.form["poolsize"]
        height =request.form["height"]
        weight =request.form["weight"]
        modality =request.form["modality"]
        swimStyle =request.form["swimStyle"]
        gender = request.form["gender"]
        gender_title = request.form["gender-title"]
        output = request.get_json()
        print(output)
        print (name,birthdate,poolsize,height,weight,modality,swimStyle)
        alldata = { "sessionData": output,
                   "metadata":{ "birthdate": birthdate, "Name": name,
                                "Weight": height,"Pool_size":poolsize,
                                "Weight":weight,"Gender":gender,"Gender_title":gender_title,
                                "modality":modality, "swimStyle": swimStyle}}
        return alldata,200
    else:
        return render_template('index.html')

if __name__ == "__main__":
    app.run()

Body:
A data transfer can only conform to one format. This formatting is either an encoding for a form or corresponds to JSON formatting.

You can still send the data within one request.
Either you add the JSON-formatted data as a field to the form, or you convert the form data into a JSON structure.

With the first variant, it is necessary to read the JSON data manually on the server side. You can use the python json library for this. For the latter, the framework does this work.

A third option is to transfer the file within the form and simply read it on the server side.

Whichever option you choose, don't forget to validate the inputs.

In the following example, all form data is converted to JSON and sent to the server. I shortened the code a bit for clarity.

The version of adding JSON formatted data to the form data should be self-explanatory.

I think the best solution is to read the file server side.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Read CSV to JSON</title>
  </head>
  <body>
    <form name="my-form" method="post" enctype="" enctype="multipart/form-data">
      <input type="text" name="name" />
      <!-- ... -->
      <input type="file" name="csv" allow="text/csv" />
      <input type="submit" />
    </form>

    <script type="text/javascript">
      ((uri) => {

        function readCSV(file, delim=',') {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onerror = reject;
            reader.onload = (evt) => {
              resolve(evt.target.result.split(/\r\n|\n/).map(line => line.split(delim)));
            };
            reader.readAsText(file);
          });
        }

        function serialize(formData) {
          const data = {};
          for (const [k, v] of formData) data[k] = v;
          return data;
        }

        // Register a listener for submit events and suppress the default behavior of the form.
        const form = document.querySelector('form[name="my-form"]');
        form.addEventListener('submit', async evt => {
          evt.preventDefault();

          if(!evt.target.csv.files.length) {
            alert('No file selected.');
            return;
          }

          const file = evt.target.csv.files[0];
          const formData = new FormData(evt.target);
          formData.delete('csv');
          // Conversion of the form data into an object.
          const data = serialize(formData);
          // Reading and converting the file into a list of objects.
          // Adding the list to the previous object.
          data['csv'] = await readCSV(file, ',')
            .then(csv => {
              const head = ['time', 'yaw', 'pitch', 'roll', 'heading', 'ax',
                            'ay', 'az', 'gx', 'gy', 'gz', 'mx', 'my', 'mz'];
              return csv.map(row => {
                let r = {};
                row.forEach((col, i) => r[head[i]] = Number(col));
                return r;
              });
            });

          // Sending the JSON data to the server.
          fetch(uri, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
          }).then(resp => resp.json())
            .then(data => console.log(data));
        });

      })({{ url_for('.data') | tojson }});
    </script>
  </body>
</html>

from flask import Flask
from flask import (
    jsonify,
    render_template,
    request,
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/data', methods=['POST'])
def data():
    data = request.json
    print(data)
    return jsonify(success=True)


问:
Multiprocessing in nested loops?
I have a nested loop with a huge range of data. In some point it takes hours to calculated the values. I was wondering if somehow I can speed it up by using multiproccessing package of python. Here is my code:

```<code>def update_selections(all_selection):
    selections_filtered_all = []
    selections_filtered_all_minus_1 = []
    for n, values in enumerate(all_selection):
         items_set = set()
         sum_length = 0
         for y in values:
             items_set.update(y)
             sum_length += 1
         if len(sum_length) == 300000000:
              selections_filtered_all.append(1)

    selections_filtered_all_minus_1.exted(selections_filtered_all)
</code>```

By following this answer, this is my way, however it's not working:

```<code>def update_selections(all_selection):
    selections_filtered_all = []
    selections_filtered_all_minus_1 = []
    pool = Pool()
    for n, x in enumerate(all_selection):
        pool.map(process_selections, x)

    selections_filtered_all_minus_1.exted(selections_filtered_all)

def process_selections(values):
    items_set = set()
    sum_length = 0
    for y in values:
        items_set.update(y)
        sum_length += 1
    if len(sum_length) == 300000000:
        selections_filtered_all.append(1)

    return essences_set, sum_length, selections_filtered_all

all_selection = ['xfRxx', 'asdeEFD', ...]
update_selections(all_selection)
</code>```

I don't understand how to bring pool() in a loop. Any suggestion would be appreciated

答:
Try this (but see my notes following):

from multiprocessing import Pool

def process_selection(values):
    items_set = set()
    sum_length = 0
    for y in values:
        items_set.update(y)
        sum_length += 1
    return 1 if len(sum_length) == 300000000 else None

def update_selections(all_selection):
    selections_filtered_all_minus_1 = []
    pool = Pool()
    # Just keep the 1 values:
    selections_filtered_all = list(filter(lambda x: x == 1, pool.map(process_selection, all_section)))
    # You mean extend, right?
    selections_filtered_all_minus_1.extend(selections_filtered_all)
```
<p><strong>Notes</strong></p>
<p>There is something a little odd about function <code>process_selection</code> (and your original logic). It creates a set that is never used to any purpose. In essence you are just counting the number of elements in variable <code>values</code> and you can save a lot of time by not creating the set and adding elements to it. In fact, if <code>values</code> implements the <code>len</code> method, you do not even need a loop.</p>
<p>If, however, the intention was to get a count of the number of elements in <code>values</code> <em>after removing duplicates</em>, then you should be taking the length of the set:</p>
<pre class="lang-py prettyprint-override"><code>def process_selection(values):
    items_set = set(values)
    return 1 if len(items_set) == 300000000 else None
</code>```

This makes the function far less CPU intensive than before and it becomes less clear to what extent multiprocessing will improve performance. The problem is that it appears that you are passing very large data items across address spaces, which in itself carries large overhead.

I am also assuming that the number of elements in the all_selection iterable is not very large even if each of these elements may be quite large. If this assumption is erroneous, you might wish to look into using the imap method instead of the map methods with a suitable chunksize argument. Doing so will prevent the creation of a large list result which is only going to be filtered into another list (imap instead returns an iterable that when iterated gives each result one by one and would be more memory efficient and perfectly suitable as input to filter).

Title: Multiprocessing in nested loops?

Body:
I have a nested loop with a huge range of data. In some point it takes hours to calculated the values. I was wondering if somehow I can speed it up by using multiproccessing package of python. Here is my code:

def update_selections(all_selection):
    selections_filtered_all = []
    selections_filtered_all_minus_1 = []
    for n, values in enumerate(all_selection):
         items_set = set()
         sum_length = 0
         for y in values:
             items_set.update(y)
             sum_length += 1
         if len(sum_length) == 300000000:
              selections_filtered_all.append(1)

    selections_filtered_all_minus_1.exted(selections_filtered_all)

By following this answer, this is my way, however it's not working:

def update_selections(all_selection):
    selections_filtered_all = []
    selections_filtered_all_minus_1 = []
    pool = Pool()
    for n, x in enumerate(all_selection):
        pool.map(process_selections, x)

    selections_filtered_all_minus_1.exted(selections_filtered_all)

def process_selections(values):
    items_set = set()
    sum_length = 0
    for y in values:
        items_set.update(y)
        sum_length += 1
    if len(sum_length) == 300000000:
        selections_filtered_all.append(1)

    return essences_set, sum_length, selections_filtered_all

all_selection = ['xfRxx', 'asdeEFD', ...]
update_selections(all_selection)

I don't understand how to bring pool() in a loop. Any suggestion would be appreciated

Body:
Try this (but see my notes following):

from multiprocessing import Pool

def process_selection(values):
    items_set = set()
    sum_length = 0
    for y in values:
        items_set.update(y)
        sum_length += 1
    return 1 if len(sum_length) == 300000000 else None

def update_selections(all_selection):
    selections_filtered_all_minus_1 = []
    pool = Pool()
    # Just keep the 1 values:
    selections_filtered_all = list(filter(lambda x: x == 1, pool.map(process_selection, all_section)))
    # You mean extend, right?
    selections_filtered_all_minus_1.extend(selections_filtered_all)

Notes

There is something a little odd about function process_selection (and your original logic). It creates a set that is never used to any purpose. In essence you are just counting the number of elements in variable values and you can save a lot of time by not creating the set and adding elements to it. In fact, if values implements the len method, you do not even need a loop.

If, however, the intention was to get a count of the number of elements in values after removing duplicates, then you should be taking the length of the set:

def process_selection(values):
    items_set = set(values)
    return 1 if len(items_set) == 300000000 else None

This makes the function far less CPU intensive than before and it becomes less clear to what extent multiprocessing will improve performance. The problem is that it appears that you are passing very large data items across address spaces, which in itself carries large overhead.

I am also assuming that the number of elements in the all_selection iterable is not very large even if each of these elements may be quite large. If this assumption is erroneous, you might wish to look into using the imap method instead of the map methods with a suitable chunksize argument. Doing so will prevent the creation of a large list result which is only going to be filtered into another list (imap instead returns an iterable that when iterated gives each result one by one and would be more memory efficient and perfectly suitable as input to filter).


问:
Qt styling Material.accent (a button) brigther than expected
Using the Qt Quick Application as a template. I'm following this documentation about styling https://doc.qt.io/qt-6/qtquickcontrols2-material.html. Here is the code:

```<code>import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Controls.Material
import QtQuick.Window

ApplicationWindow {
    id: window
    width: 1024
    height: 720
    visible: true
    title: qsTr("My Test")

    Material.theme: Material.Dark
    Material.primary: Material.Blue
    Material.accent: Material.Blue

    header: ToolBar {
        RowLayout {
            anchors.fill: parent
            ToolButton {
                font.pixelSize: 20
                text: qsTr("‹")
                onClicked: stack.pop()
            }
            Label {
                font.pixelSize: 20
                text: "My app"
                elide: Label.ElideRight
                horizontalAlignment: Qt.AlignHCenter
                verticalAlignment: Qt.AlignVCenter
                Layout.fillWidth: true
            }
            ToolButton {
                font.pixelSize: 20
                text: qsTr("⋮")
                onClicked: menu.open()
            }
        }
    }

    Button{
        text: qsTr("????")
        highlighted: true
    }
}
</code>```

And I'm obtaining this output:

My question is why the button is brigther than the header content? Am I not using the same material?
I'm using qt 6.2.2. SO: Linux mint

答:
As @Amfasis suggested, using:

```<code>Material.accent: Material.color(Material.Blue)
</code>```

will make it work properly.

Body:
Using the Qt Quick Application as a template. I'm following this documentation about styling https://doc.qt.io/qt-6/qtquickcontrols2-material.html. Here is the code:

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Controls.Material
import QtQuick.Window

ApplicationWindow {
    id: window
    width: 1024
    height: 720
    visible: true
    title: qsTr("My Test")

    Material.theme: Material.Dark
    Material.primary: Material.Blue
    Material.accent: Material.Blue

    header: ToolBar {
        RowLayout {
            anchors.fill: parent
            ToolButton {
                font.pixelSize: 20
                text: qsTr("‹")
                onClicked: stack.pop()
            }
            Label {
                font.pixelSize: 20
                text: "My app"
                elide: Label.ElideRight
                horizontalAlignment: Qt.AlignHCenter
                verticalAlignment: Qt.AlignVCenter
                Layout.fillWidth: true
            }
            ToolButton {
                font.pixelSize: 20
                text: qsTr("⋮")
                onClicked: menu.open()
            }
        }
    }

    Button{
        text: qsTr("????")
        highlighted: true
    }
}

And I'm obtaining this output:

My question is why the button is brigther than the header content? Am I not using the same material?
I'm using qt 6.2.2. SO: Linux mint

Body:
As @Amfasis suggested, using:

Material.accent: Material.color(Material.Blue)

will make it work properly.


问:
ASP.NET Core Health Checks: Returning pre-evaluated results
I'm evaluating the use of Microsoft Health Checks to improve routing of our internal load balancer. So far I'm very happy with the functionality provided by this feature and the community around it. However there's one thing I did not find yet and wanted to ask if it is possible out of the box:

The Health Checks seem to retrieve their own status as soon as they are requested. But because our service might have a hard time processing a lot of request in that given moment, the query to a thrid-party component like the SQL Server might take it's time to respond. Therefore, we would like to pre-evaluate that health check periodically (like every few seconds) and return that state when the health check api gets called.

The reason is, that we want our load balancer to get the health state as quickly as possible. Using pre-evaluated results seems to be good enough for our use case.

Now the question is: Is it possible to add a kind of "poll" or "auto-update" mechanism to the ASP.NET Core health checks? Or does this mean I have to implement my own health check returning values from a background service which pre-evaluates the results periodically?

Please note, I want to use pre-evaluated results on each request which is NOT HTTP Caching where the live result is cached for the next requests.

答:
Another alternative is using Scrutor, and decorating HealthCheckService.
If you want to be paranoid about having multiple threads re-publishing, you'd have to add a locking mechanism while fetching the HealthCheckReport from the inner HealthCheckService. A decent example is here.

using System.Reflection;
using HealthCheckCache;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

// used by the Decorator CachingHealthCheckService
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();

// register all IHealthCheck types - basically builder.Services.AddTransient<AlwaysHealthy>(), but across all types in this assembly.
var healthServices = builder.Services.Scan(scan =>
    scan.FromCallingAssembly()
        .AddClasses(filter => filter.AssignableTo<IHealthCheck>())
        .AsSelf()
        .WithTransientLifetime()
);

// Register HealthCheckService, so it can be decorated.
var healthCheckBuilder = builder.Services.AddHealthChecks();
// Decorate the implementation with a cache
builder.Services.Decorate<HealthCheckService>((inner, provider) =>
    new CachingHealthCheckService(inner,
        provider.GetRequiredService<IHttpContextAccessor>(),
        provider.GetRequiredService<IMemoryCache>()
    )
);

// Register all the IHealthCheck instances in the container
// this has to be a for loop, b/c healthCheckBuilder.Add will modify the builder.Services - ServiceCollection
for (int i = 0; i < healthServices.Count; i++)
{
    ServiceDescriptor serviceDescriptor = healthServices[i];
    var isHealthCheck = serviceDescriptor.ServiceType.IsAssignableTo(typeof(IHealthCheck)) && serviceDescriptor.ServiceType == serviceDescriptor.ImplementationType;
    if (isHealthCheck)
    {
        healthCheckBuilder.Add(new HealthCheckRegistration(
            serviceDescriptor.ImplementationType.Name,
            s => (IHealthCheck)ActivatorUtilities.GetServiceOrCreateInstance(s, serviceDescriptor.ImplementationType),
            failureStatus: null,
            tags: null)
        );
    }

}

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapHealthChecks("/health", new HealthCheckOptions()
{
    AllowCachingResponses = true, // allow caching at Http level
});

app.Run();

public class CachingHealthCheckService : HealthCheckService
{
    private readonly HealthCheckService _innerHealthCheckService;
    private readonly IHttpContextAccessor _contextAccessor;
    private readonly IMemoryCache _cache;
    private const string CacheKey = "CachingHealthCheckService:HealthCheckReport";

    public CachingHealthCheckService(HealthCheckService innerHealthCheckService, IHttpContextAccessor contextAccessor, IMemoryCache cache)
    {
        _innerHealthCheckService = innerHealthCheckService;
        _contextAccessor = contextAccessor;
        _cache = cache;
    }

    public override async Task<HealthReport> CheckHealthAsync(Func<HealthCheckRegistration, bool>? predicate, CancellationToken cancellationToken = new CancellationToken())
    {
        HttpContext context = _contextAccessor.HttpContext;

        var forced = !string.IsNullOrEmpty(context.Request.Query["force"]);
        context.Response.Headers.Add("X-Health-Forced", forced.ToString());
        var cached = _cache.Get<HealthReport>(CacheKey);
        if (!forced && cached != null)
        {
            context.Response.Headers.Add("X-Health-Cached", "True");
            return cached;
        }
        var healthReport = await _innerHealthCheckService.CheckHealthAsync(predicate, cancellationToken);
        if (!forced)
        {
            _cache.Set(CacheKey, healthReport, TimeSpan.FromSeconds(30));
        }
        context.Response.Headers.Add("X-Health-Cached", "False");
        return healthReport;
    }
}
```


问:
Integrating Bison/Flex/Yacc into XCode
Is there a simple way for integrating Bison/Flex/Yacc into XCode?

I want to write my own language to be parsed, which interacts with my ObjC objects.

But the tools will only take STDIN as input, and will only produce C code, instead of ObjC.  They're basically only seem useful for command-line tools, otherwise they need massive pain to override the output every time I regenerate the parser code.

答: This is all ancient - but you can just redefine YACC to whatever, and LEX to whatever as User-Defined settings.</p>

Title: Integrating Bison/Flex/Yacc into XCode


问:
Python: get values from dictionary of dictionaries
I have a dictionary of dictionaries that looks like this:

{'info': {'status': 'OK',
          'data': {'account': [{'currency': 'USD',
                                'name': 'United States Dollar',
                                'amount': '100',
                                'used': '20',
                                'total': '120'},
                               {'currency': 'EUR',
                                'name': 'Euro',
                                'amount': '150',
                                'used': '35',
                                'total': '185'}]}},
 'USD': {'amount': 100, 'used': 20, 'total': 120},
 'EUR': {'amount': 150, 'used': 35, 'total': 185},
 'amount': {'USD': 100, 'EUR': 150},
 'used': {'USD': 20, 'EUR': 35},
 'total': {'USD': 120, 'EUR': 185}}
```
<p>What I want to get from this is a currency list:</p>
```currency_list = ['USD','EUR']
```
<p>and I would like to get a currency name list:</p>
```currency_list = ['United States Dollar','Euro']
```

How can I access the dictionaries?

Thank you

答:
If your dictionary is saved in a variable named yourdictionary you can use the following code.

```<code>data = yourdictionary['info'].get('data').get('account')

currency_list = [dat['currency'] for dat in data]
currency_name_list = [dat['name'] for dat in data]
</code>```

Here list comprehension is used to locate all currencies and names in the dictionary.

Body:
I have a dictionary of dictionaries that looks like this:

{'info': {'status': 'OK',
          'data': {'account': [{'currency': 'USD',
                                'name': 'United States Dollar',
                                'amount': '100',
                                'used': '20',
                                'total': '120'},
                               {'currency': 'EUR',
                                'name': 'Euro',
                                'amount': '150',
                                'used': '35',
                                'total': '185'}]}},
 'USD': {'amount': 100, 'used': 20, 'total': 120},
 'EUR': {'amount': 150, 'used': 35, 'total': 185},
 'amount': {'USD': 100, 'EUR': 150},
 'used': {'USD': 20, 'EUR': 35},
 'total': {'USD': 120, 'EUR': 185}}

What I want to get from this is a currency list:

currency_list = ['USD','EUR']

and I would like to get a currency name list:

currency_list = ['United States Dollar','Euro']

How can I access the dictionaries?

Thank you

Body:
If your dictionary is saved in a variable named yourdictionary you can use the following code.

data = yourdictionary['info'].get('data').get('account')

currency_list = [dat['currency'] for dat in data]
currency_name_list = [dat['name'] for dat in data]

Here list comprehension is used to locate all currencies and names in the dictionary.


问:
Iterating over map to create key vault secrets throws error if secret doesn't exist
I have a map of key vault secrets that I would want to use in an application.  Some of these already exist in Azure Key Vault:

```<code>variable "keyvault_secrets" {
  type = map(string)
  default = {
    service_bus = "AzureWebJobsServiceBus",
    mongo_connection = "MongoConnection",
    sendgrid_api_key = "SendgridApiKey",
    twilio_auth_token = "TwilioAccountAuthToken",
    twilio_sid = "TwilioAccountSid",
    twilio_message_service_sid = "TwilioMessageServiceSid",
    resdis_session_connection = "RedisSessionConnection"
  }
}
</code>```

I then have the following blocks to create the key vault and secrets:

```<code>data "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
}

resource "azurerm_key_vault_access_policy" "api" {
  key_vault_id = azurerm_key_vault.default.id
  object_id = azurerm_app_service.api[0].identity[0].principal_id
  tenant_id = data.azurerm_client_config.current.tenant_id
  depends_on = [azurerm_app_service.api]
  key_permissions = []
  secret_permissions = [
    "Get"
  ]
}

resource "azurerm_key_vault" "default" {
  location = var.azure_location
  name = "kv-quiztime-${terraform.workspace}-001"
  resource_group_name = azurerm_resource_group.default[0].name
  sku_name = module.vars.env["keyvault_plan_sku"]["name"]
  tenant_id = data.azurerm_client_config.current.tenant_id
  tags = local.common_tags
}

resource "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
  value = data.azurerm_key_vault_secret.these[each.key] ? data.azurerm_key_vault_secret.these[each.key].value : "not set"
  content_type = "Connection String"
}
</code>```

However, when I run terraform plan I get the following error:

Error: KeyVault Secret "RedisSessionConnection" (KeyVault URI "https://kv-[hidden]-dev-001.vault.azure.net/") does not exist
│
│   with data.azurerm_key_vault_secret.these["resdis_session_connection"],
│   on keyvaults.tf line 2, in data "azurerm_key_vault_secret" "these":
│    2: data "azurerm_key_vault_secret" "these" {

Because it doesn't exist, I would expect it to be created.  What am I doing wrong? Or do I have incorrect expectations?

答:
The error "does not exist" is from data.azurerm_key_vault_secret.these. Data sources must exist, otherwise you get that error. You can't query a data of a resource that does not exist. TF does not support such functionality nor it has no way to check for the existence beforehand.

You would have to design your own custom data source to implement working with resources that may or may not exist.

Body:
I have a map of key vault secrets that I would want to use in an application.  Some of these already exist in Azure Key Vault:

variable "keyvault_secrets" {
  type = map(string)
  default = {
    service_bus = "AzureWebJobsServiceBus",
    mongo_connection = "MongoConnection",
    sendgrid_api_key = "SendgridApiKey",
    twilio_auth_token = "TwilioAccountAuthToken",
    twilio_sid = "TwilioAccountSid",
    twilio_message_service_sid = "TwilioMessageServiceSid",
    resdis_session_connection = "RedisSessionConnection"
  }
}

I then have the following blocks to create the key vault and secrets:

data "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
}

resource "azurerm_key_vault_access_policy" "api" {
  key_vault_id = azurerm_key_vault.default.id
  object_id = azurerm_app_service.api[0].identity[0].principal_id
  tenant_id = data.azurerm_client_config.current.tenant_id
  depends_on = [azurerm_app_service.api]
  key_permissions = []
  secret_permissions = [
    "Get"
  ]
}

resource "azurerm_key_vault" "default" {
  location = var.azure_location
  name = "kv-quiztime-${terraform.workspace}-001"
  resource_group_name = azurerm_resource_group.default[0].name
  sku_name = module.vars.env["keyvault_plan_sku"]["name"]
  tenant_id = data.azurerm_client_config.current.tenant_id
  tags = local.common_tags
}

resource "azurerm_key_vault_secret" "these" {
  for_each = var.keyvault_secrets
  key_vault_id = azurerm_key_vault.default.id
  name = each.value
  value = data.azurerm_key_vault_secret.these[each.key] ? data.azurerm_key_vault_secret.these[each.key].value : "not set"
  content_type = "Connection String"
}

However, when I run terraform plan I get the following error:

Error: KeyVault Secret "RedisSessionConnection" (KeyVault URI "https://kv-[hidden]-dev-001.vault.azure.net/") does not exist
│
│   with data.azurerm_key_vault_secret.these["resdis_session_connection"],
│   on keyvaults.tf line 2, in data "azurerm_key_vault_secret" "these":
│    2: data "azurerm_key_vault_secret" "these" {

Because it doesn't exist, I would expect it to be created.  What am I doing wrong? Or do I have incorrect expectations?


答:
given that this info you posted in a var dic just do:

currency_list = [value["currency"] for value in dic["info"]["data"]["account"]]

currency_list_name = [value["name"] for value in dic["info"]["data"]["account"]]

Title: Python: get values from dictionary of dictionaries