问:
Asp.Net Core - Read Files
I need your help again. I have been working on a project in asp.net and I have had some doubts.

The project consists of reading an xml file and saving the data in a database.
I was able to read the data, but now I have a question
The question is...

I have this xml file.

    -<products>

-<product>

<name>Ball</name>

<price>15</price>

<quantity>2</quantity>

-<description>

<comment>aaa</comment>

</description>

-<description>

<comment>bbb</comment>

</description>

-<age>

<number>12</number>

</age>

</product>
</products>```
</div>
</div>
</p>

<p>And this is the program.</p>

``` private List<Product> ProcessImport(string path)
    {
        XDocument xDocument = XDocument.Load(path);
        List<Product> products = xDocument.Descendants("product").Select
            (p => new Product()
            {
               Id = Convert.ToInt32(p.Element("id").Value),
               Name=p.Element("name").Value,
               Quantity = Convert.ToInt32(p.Element("quantity").Value),
               Price = Convert.ToInt32(p.Element("price").Value),
               Description = p.Element("description").Element("comment")

            }).ToList();

        foreach(var product in products)
        {
            var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
            if (productInfo != null)
            {
                productInfo.Id = product.Id;
                productInfo.Name = product.Name;
                productInfo.Quantity = product.Quantity;
                productInfo.Price = product.Price;
                productInfo.Description= product.Description;

            }

            else
            {

                db.Products.Add(product);
            }

            db.SaveChanges();
        }

        return products;

    }
```

My question is, the program above only reads the first description.

What do I have to insert so that he can read both descriptions?
(I think the ideal would be to create two tables and then make the connection between them)

But now I wanted help to get this done.

Thanks!!

答:
As a note,your xml file does not contain id node,but you need to read the id node data in your ProcessImport method.If you do not contain id node,you could not read the data in your code.

For your requirement,here is a working demo:

Model:

```<code>public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public Description[] Description { get; set; }
}
public class Description
{
    public string Comment { get; set; }
}
</code>```

Controller:

```<code>private List<Product> ProcessImport()
{
    XDocument xDocument = XDocument.Load("test.xml");
    List<Product> products = xDocument.Descendants("product").Select
        (p => new Product()
        {
            Id = Convert.ToInt32(p.Element("id").Value),
            Name = p.Element("name").Value,
            Quantity = Convert.ToInt32(p.Element("quantity").Value),
            Price = Convert.ToInt32(p.Element("price").Value),
            Description = p.Descendants("description").Select(d => new Description()
            {
                Comment = d.Element("comment").Value
            }).ToArray()

        }).ToList();

    //do your stuff...
    return products;
}
</code>```

Result:

My test.xml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<products>
  <product>
    <id>100</id>
    <name>Ball</name>
    <price>15</price>
    <quantity>2</quantity>
    <description>
      <comment>aaa</comment>
    </description>
    <description>
      <comment>bbb</comment>
    </description>
    <age>
      <number>12</number>
    </age>
  </product>
</products>
</code>```

Title: Asp.Net Core - Read Files

Body:
I need your help again. I have been working on a project in asp.net and I have had some doubts.

The project consists of reading an xml file and saving the data in a database.
I was able to read the data, but now I have a question
The question is...

I have this xml file.

    -<products>

-<product>

<name>Ball</name>

<price>15</price>

<quantity>2</quantity>

-<description>

<comment>aaa</comment>

</description>

-<description>

<comment>bbb</comment>

</description>

-<age>

<number>12</number>

</age>

</product>
</products>

And this is the program.

 private List<Product> ProcessImport(string path)
    {
        XDocument xDocument = XDocument.Load(path);
        List<Product> products = xDocument.Descendants("product").Select
            (p => new Product()
            {
               Id = Convert.ToInt32(p.Element("id").Value),
               Name=p.Element("name").Value,
               Quantity = Convert.ToInt32(p.Element("quantity").Value),
               Price = Convert.ToInt32(p.Element("price").Value),
               Description = p.Element("description").Element("comment")

            }).ToList();

        foreach(var product in products)
        {
            var productInfo = db.Products.SingleOrDefault(p => p.Id.Equals(product.Id));
            if (productInfo != null)
            {
                productInfo.Id = product.Id;
                productInfo.Name = product.Name;
                productInfo.Quantity = product.Quantity;
                productInfo.Price = product.Price;
                productInfo.Description= product.Description;

            }

            else
            {

                db.Products.Add(product);
            }

            db.SaveChanges();
        }

        return products;

    }

My question is, the program above only reads the first description.

What do I have to insert so that he can read both descriptions?
(I think the ideal would be to create two tables and then make the connection between them)

But now I wanted help to get this done.

Thanks!!

Body:
As a note,your xml file does not contain id node,but you need to read the id node data in your ProcessImport method.If you do not contain id node,you could not read the data in your code.

For your requirement,here is a working demo:

Model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public Description[] Description { get; set; }
}
public class Description
{
    public string Comment { get; set; }
}

Controller:

private List<Product> ProcessImport()
{
    XDocument xDocument = XDocument.Load("test.xml");
    List<Product> products = xDocument.Descendants("product").Select
        (p => new Product()
        {
            Id = Convert.ToInt32(p.Element("id").Value),
            Name = p.Element("name").Value,
            Quantity = Convert.ToInt32(p.Element("quantity").Value),
            Price = Convert.ToInt32(p.Element("price").Value),
            Description = p.Descendants("description").Select(d => new Description()
            {
                Comment = d.Element("comment").Value
            }).ToArray()

        }).ToList();

    //do your stuff...
    return products;
}

Result:

My test.xml:

<?xml version="1.0" encoding="utf-8" ?>
<products>
  <product>
    <id>100</id>
    <name>Ball</name>
    <price>15</price>
    <quantity>2</quantity>
    <description>
      <comment>aaa</comment>
    </description>
    <description>
      <comment>bbb</comment>
    </description>
    <age>
      <number>12</number>
    </age>
  </product>
</products>


来源: stackexchange

问:
How to force VS2019 ignore exceptions inside "try" section
Just installed VS2019 and noticed one uncomfortable thing: in Debug it stops ("falls") at the each exception, even inside try sections. How can I force it to ignore these exceptions, go to catch and work further?

After answer of Perry Qian-MSFT. Now I see this when I have UNHANDLED exception.

Translation: "application is in pause mode". And call stack is empty.

答:
How to force VS2019 ignore exceptions inside “try” section

First, I agree with dixv and thanks for his help.

Current VS IDE can ignore specific exceptions as required.Under Debug-->Windows-->Exception settings

You can record the previous exception's name and search under it and then  uncheck it.

Note

After that, please uncheck Just My Code option, otherwise the exception may still be interrupted.

Tools-->Options-->Debugging-->General-->Just My Code

Update 1

If you enable that feature and also want to see the detailed info about that exception without breaking Debugging, you can add these code in catch

```<code> try
{

xxxxxxxxxxxxxxx

}
catch (Exception e) {

    Debug.WriteLine("=============================");
    Debug.WriteLine(e.Message);
    Debug.WriteLine(e.Source);
    Debug.WriteLine(e.StackTrace);
    Debug.WriteLine("=============================");

}
</code>```

It will show the specific info about that exception in output window:

More info, you can refer to this issue.

Update 2

When you face that situation, you can just click on View Detail of that exception window, it will call Watch Widow and then when you click on StackTrace, it will show the related error file name and related line to you.

Hope it will help you.

ContentLicense: CC BY-SA 4.0

Body:
How to force VS2019 ignore exceptions inside “try” section

First, I agree with dixv and thanks for his help.

Current VS IDE can ignore specific exceptions as required.Under Debug-->Windows-->Exception settings

You can record the previous exception's name and search under it and then  uncheck it.

Note

After that, please uncheck Just My Code option, otherwise the exception may still be interrupted.

Tools-->Options-->Debugging-->General-->Just My Code

Update 1

If you enable that feature and also want to see the detailed info about that exception without breaking Debugging, you can add these code in catch

 try
{

xxxxxxxxxxxxxxx

}
catch (Exception e) {

    Debug.WriteLine("=============================");
    Debug.WriteLine(e.Message);
    Debug.WriteLine(e.Source);
    Debug.WriteLine(e.StackTrace);
    Debug.WriteLine("=============================");

}

It will show the specific info about that exception in output window:

More info, you can refer to this issue.

Update 2

When you face that situation, you can just click on View Detail of that exception window, it will call Watch Widow and then when you click on StackTrace, it will show the related error file name and related line to you.

Hope it will help you.


问:
Mapping arrays from csv file for tree hierarchy visualization using NodeJS
I'm trying to show the relationship between SQL tables in visualization. I have three columns in a csv sheet (columns: Target, Source, JoinSource).

Column Target has a table name in each cell, say A1, A2, A3....... An.

Column Source has arrays with multiple elements. The elements have an index as a prefix. A sample array would look like: (I've changed the actual data to dummy data and all these elements are actually SQL tables)

```<code>[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth... P10 Red, P10.1 Blue, P10.1.1 Copper]
</code>```

The structure of Column JoinSource is similar to Source but with different elements. A sample array from JoinSource would like:

```<code>[P3 Orange, P2.2 Charlie, P1.1 Mushroom, P7 Cyclone, P7.1 Hurricane.... P10.2 Typhoon]
</code>```

Every table has a alphanumerical prefix. The prefix P is just an arbitrary variable used for simplicity purpose, so we can safely ignore it.

The numerical prefixes 1, 2, 2.1, 10.1.1 denote the relationship between tables. If it's a whole number then it is directly connected to the table in column Target. If there's a decimal then it is directly connected to the table either in Source or JoinSource.

To put simply, A1 is the parent table - P1 Apple is the child of A1; and P1.1 Mushroom is the child of P1 Apple.

Similarly, P10 Red is the child of A1; P10.1 Blue is the child of P10 Red; P10.1.1 Copper is the child of P10.1 Blue.

The parent/child relationship depends on the number of decimal places in the index. If there's no decimal it's straight forward. If there's one decimal then it's connected to the table with the same whole number as prefix; if there are two decimals then it's connected to the table with same whole number plus one decimal as prefix.

I hope the above explanation is clear. Now I need to use some logic in NodeJS (for loop, if loop etc) and make the parent-child mapping of tables. Any help is much appreciated.

The data from csv sheet would look like this.

```<code>|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
|    Target  |                           Source                                 |           JoinSource                                                                                |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Fenugreek  | P8 Sirocco, P8.1 Merlin, P9.1 Cancun, P10.1 Force, P11.2 Torque  | P1 Tiger, P2 Lion, P3 Train, P4 Giraffe, P5 Bear, P6 Javelin, P7 Mingo, P8 Mavue, P9 Violet, P10 Jupiter, P11 Pluto |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Chernobyl  | P1 Moro, P2 Cher, P2.1 Rona, P2.2 Mason, P3 Tonga, P4.1 Nagatom  | P1.1 Eba, P2.3 Van, P3.1 Gomin, P4 Evaum, P4.2 Hun                                                                  |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
</code>```

One thing to note from the above table is, there is a P1 in the first row and one more P1 in the second row. These two are different. Each row is independent of each other and the visualization is different for each row as well.

And I need the table names in the visualization, not the indexes. The indexes are only for mapping purpose. For instance, nodes in the tree diagram should be more like Apple, Pluto, Earth etc, not P1, P2.1, P3.1.1.

The final visualization output should be something like this.

答:
Note: your original sample data had missing nodes in the tree hierarchy, which I've filled in manually.

I've transformed the data into the form {id, parentId, name} where P3.1.1 will emit {id: "P3.1.1", parentId: "P3.1", name: "Earth"}.  This can be fed to d3.stratify that will build the hierarchy for you.  I also a {id: "P", name: "Target"} for the root node.

d3-stratify:

https://github.com/d3/d3-hierarchy/blob/master/README.md#stratify

demo

I used this demo for hierarchy with a few adjustments to build the SVG tree:   d3-hierarchy (demo)

label was changed to extract name property by default instead of id, and I've embedded the dimensions directly into the function.

It uses d3 Tidy Tree (demo) to render a d3-hierarchy.

data = `[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth, P10 Red, P10.1 Blue, P10.1.1 Copper, P3 PewPewPew, P3.1 Chopper, P3.2 Twenty, P3.1.2 Two]`
.slice(1,-1).split(', ')
.map(x=>x.match(/^((.*?)(?:\.)?(?:\d*)?) (.*)$/).slice(1))
.map(([id, parentId, name])=>({id, parentId, name}))

data.push({id: 'P', name:'Target'})

document.body.appendChild(graph(d3.stratify()(data)))

function graph(root, {
  label = d => d.data.name,
  highlight = () => false,
  marginLeft = 40
} = {}) {
width=500;
dx=12;
dy=120;
treeLink = d3.linkHorizontal().x(d => d.y).y(d => d.x);
tree = d3.tree().nodeSize([dx, dy]);
  root = tree(root);

  let x0 = Infinity;
  let x1 = -x0;
  root.each(d => {
    if (d.x > x1) x1 = d.x;
    if (d.x < x0) x0 = d.x;
  });

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, x1 - x0 + dx * 2])
      .style("overflow", "visible");

  const g = svg.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("transform", `translate(${marginLeft},${dx - x0})`);

  const link = g.append("g")
    .attr("fill", "none")
    .attr("stroke", "#555")
    .attr("stroke-opacity", 0.4)
    .attr("stroke-width", 1.5)
  .selectAll("path")
    .data(root.links())
    .join("path")
      .attr("stroke", d => highlight(d.source) && highlight(d.target) ? "red" : null)
      .attr("stroke-opacity", d => highlight(d.source) && highlight(d.target) ? 1 : null)
      .attr("d", treeLink);

  const node = g.append("g")
      .attr("stroke-linejoin", "round")
      .attr("stroke-width", 3)
    .selectAll("g")
    .data(root.descendants())
    .join("g")
      .attr("transform", d => `translate(${d.y},${d.x})`);

  node.append("circle")
      .attr("fill", d => highlight(d) ? "red" : d.children ? "#555" : "#999")
      .attr("r", 2.5);

  node.append("text")
      .attr("fill", d => highlight(d) ? "red" : null)
      .attr("dy", "0.31em")
      .attr("x", d => d.children ? -6 : 6)
      .attr("text-anchor", d => d.children ? "end" : "start")
      .text(label)
    .clone(true).lower()
      .attr("stroke", "white");

  return svg.node();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.js" integrity="sha256-LHLWSn9RC2p119R1eT2pO3Om+Ir2G0kTZOJmWQ2//pw=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-array/1.2.2/d3-array.js" integrity="sha256-flJtpBHeLvoTQmeFnm0UuGrCFMGQbK6yrLhaNHyX8kk=" crossorigin="anonymous"></script></code>```

Body:
I'm trying to show the relationship between SQL tables in visualization. I have three columns in a csv sheet (columns: Target, Source, JoinSource).

Column Target has a table name in each cell, say A1, A2, A3....... An.

Column Source has arrays with multiple elements. The elements have an index as a prefix. A sample array would look like: (I've changed the actual data to dummy data and all these elements are actually SQL tables)

[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth... P10 Red, P10.1 Blue, P10.1.1 Copper]

The structure of Column JoinSource is similar to Source but with different elements. A sample array from JoinSource would like:

[P3 Orange, P2.2 Charlie, P1.1 Mushroom, P7 Cyclone, P7.1 Hurricane.... P10.2 Typhoon]

Every table has a alphanumerical prefix. The prefix P is just an arbitrary variable used for simplicity purpose, so we can safely ignore it.

The numerical prefixes 1, 2, 2.1, 10.1.1 denote the relationship between tables. If it's a whole number then it is directly connected to the table in column Target. If there's a decimal then it is directly connected to the table either in Source or JoinSource.

To put simply, A1 is the parent table - P1 Apple is the child of A1; and P1.1 Mushroom is the child of P1 Apple.

Similarly, P10 Red is the child of A1; P10.1 Blue is the child of P10 Red; P10.1.1 Copper is the child of P10.1 Blue.

The parent/child relationship depends on the number of decimal places in the index. If there's no decimal it's straight forward. If there's one decimal then it's connected to the table with the same whole number as prefix; if there are two decimals then it's connected to the table with same whole number plus one decimal as prefix.

I hope the above explanation is clear. Now I need to use some logic in NodeJS (for loop, if loop etc) and make the parent-child mapping of tables. Any help is much appreciated.

The data from csv sheet would look like this.

|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
|    Target  |                           Source                                 |           JoinSource                                                                                |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Fenugreek  | P8 Sirocco, P8.1 Merlin, P9.1 Cancun, P10.1 Force, P11.2 Torque  | P1 Tiger, P2 Lion, P3 Train, P4 Giraffe, P5 Bear, P6 Javelin, P7 Mingo, P8 Mavue, P9 Violet, P10 Jupiter, P11 Pluto |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| Chernobyl  | P1 Moro, P2 Cher, P2.1 Rona, P2.2 Mason, P3 Tonga, P4.1 Nagatom  | P1.1 Eba, P2.3 Van, P3.1 Gomin, P4 Evaum, P4.2 Hun                                                                  |
|------------|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|

One thing to note from the above table is, there is a P1 in the first row and one more P1 in the second row. These two are different. Each row is independent of each other and the visualization is different for each row as well.

And I need the table names in the visualization, not the indexes. The indexes are only for mapping purpose. For instance, nodes in the tree diagram should be more like Apple, Pluto, Earth etc, not P1, P2.1, P3.1.1.

The final visualization output should be something like this.

Body:
Note: your original sample data had missing nodes in the tree hierarchy, which I've filled in manually.

I've transformed the data into the form {id, parentId, name} where P3.1.1 will emit {id: "P3.1.1", parentId: "P3.1", name: "Earth"}.  This can be fed to d3.stratify that will build the hierarchy for you.  I also a {id: "P", name: "Target"} for the root node.

d3-stratify:

https://github.com/d3/d3-hierarchy/blob/master/README.md#stratify

demo

I used this demo for hierarchy with a few adjustments to build the SVG tree:   d3-hierarchy (demo)

label was changed to extract name property by default instead of id, and I've embedded the dimensions directly into the function.

It uses d3 Tidy Tree (demo) to render a d3-hierarchy.

data = `[P1 Apple, P2 Mango, P2.1 Pluto, P3.1.1 Earth, P10 Red, P10.1 Blue, P10.1.1 Copper, P3 PewPewPew, P3.1 Chopper, P3.2 Twenty, P3.1.2 Two]`
.slice(1,-1).split(', ')
.map(x=>x.match(/^((.*?)(?:\.)?(?:\d*)?) (.*)$/).slice(1))
.map(([id, parentId, name])=>({id, parentId, name}))

data.push({id: 'P', name:'Target'})

document.body.appendChild(graph(d3.stratify()(data)))

function graph(root, {
  label = d => d.data.name,
  highlight = () => false,
  marginLeft = 40
} = {}) {
width=500;
dx=12;
dy=120;
treeLink = d3.linkHorizontal().x(d => d.y).y(d => d.x);
tree = d3.tree().nodeSize([dx, dy]);
  root = tree(root);

  let x0 = Infinity;
  let x1 = -x0;
  root.each(d => {
    if (d.x > x1) x1 = d.x;
    if (d.x < x0) x0 = d.x;
  });

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, x1 - x0 + dx * 2])
      .style("overflow", "visible");

  const g = svg.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("transform", `translate(${marginLeft},${dx - x0})`);

  const link = g.append("g")
    .attr("fill", "none")
    .attr("stroke", "#555")
    .attr("stroke-opacity", 0.4)
    .attr("stroke-width", 1.5)
  .selectAll("path")
    .data(root.links())
    .join("path")
      .attr("stroke", d => highlight(d.source) && highlight(d.target) ? "red" : null)
      .attr("stroke-opacity", d => highlight(d.source) && highlight(d.target) ? 1 : null)
      .attr("d", treeLink);

  const node = g.append("g")
      .attr("stroke-linejoin", "round")
      .attr("stroke-width", 3)
    .selectAll("g")
    .data(root.descendants())
    .join("g")
      .attr("transform", d => `translate(${d.y},${d.x})`);

  node.append("circle")
      .attr("fill", d => highlight(d) ? "red" : d.children ? "#555" : "#999")
      .attr("r", 2.5);

  node.append("text")
      .attr("fill", d => highlight(d) ? "red" : null)
      .attr("dy", "0.31em")
      .attr("x", d => d.children ? -6 : 6)
      .attr("text-anchor", d => d.children ? "end" : "start")
      .text(label)
    .clone(true).lower()
      .attr("stroke", "white");

  return svg.node();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.js" integrity="sha256-LHLWSn9RC2p119R1eT2pO3Om+Ir2G0kTZOJmWQ2//pw=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-array/1.2.2/d3-array.js" integrity="sha256-flJtpBHeLvoTQmeFnm0UuGrCFMGQbK6yrLhaNHyX8kk=" crossorigin="anonymous"></script>


问:
HTML list split into equal sized chunks in CSS
I have a list with 8 items as this:

```<code><ul>
  <li>List Item 01</li>
  <li>List Item 02</li>
  <li>List Item 03</li>
  <li>List Item 04</li>
  <li>List Item 05</li>
  <li>List Item 06</li>
  <li>List Item 07</li>
  <li>List Item 08</li>
</ul>
</code>```

With this list, I want to Keep a fixed width space in between item 04 and 05. And first four items should be align to right of that space and last four to align to left as below image I attached.

I tried it something like this:

```<code>ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

ul li:nth-child(4) {
  margin-right: 10em;
}
</code>```

It seems ok for me, but one thing is when the list have 4 or 6 items then it should group 2 or 3.

Can anybody tell what would be the solution for this. Its good if I have CSS only solution.

Thank you.

答:
Its interesting!

Need find the middle one to do something without use js.

So i use odd and even to split in half, then use pseudo-element to become the middle one.

see below.

    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }
    li{
      width: 10em;
      border: 1px solid #000;
    }
    ul li:nth-child(odd) {
      order: 0;
    }
    ul li:nth-child(even) {
      order: 2;
    }
    ul::after {
      content: '';
      display: block;
      width: 10rem;
      order: 1;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
  </ul></code>```

=============================================================

JS

    let num = document.getElementsByTagName('li');
    let half = num.length / 2;
    let li = document.createElement('li');
    num[half].parentNode.insertBefore(li, num[half])```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }
    li{
      width: 10em;
      border: 1px solid #000;
    }
    li:empty{
      border: none;
    }</code>```

item1

item2

item3

item4

item5

item6

item7

item8

```
</div>
</div>
</p>

<p>================================================</p>

<p>JQ</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var li = $('ul li');
    $($('<li>')).insertBefore(li[li.length / 2])</code>```

* {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }

    li {
      width: 10em;
      border: 1px solid #000;
    }

    li:empty {
      border: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
  </ul></code>```

Body:
I have a list with 8 items as this:

List Item 01

List Item 02

List Item 03

List Item 04

List Item 05

List Item 06

List Item 07

List Item 08

With this list, I want to Keep a fixed width space in between item 04 and 05. And first four items should be align to right of that space and last four to align to left as below image I attached.

I tried it something like this:

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

ul li:nth-child(4) {
  margin-right: 10em;
}

It seems ok for me, but one thing is when the list have 4 or 6 items then it should group 2 or 3.

Can anybody tell what would be the solution for this. Its good if I have CSS only solution.

Thank you.

Body:
Its interesting!

Need find the middle one to do something without use js.

So i use odd and even to split in half, then use pseudo-element to become the middle one.

see below.

    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }
    li{
      width: 10em;
      border: 1px solid #000;
    }
    ul li:nth-child(odd) {
      order: 0;
    }
    ul li:nth-child(even) {
      order: 2;
    }
    ul::after {
      content: '';
      display: block;
      width: 10rem;
      order: 1;
    }

  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
  </ul>

=============================================================

JS

    let num = document.getElementsByTagName('li');
    let half = num.length / 2;
    let li = document.createElement('li');
    num[half].parentNode.insertBefore(li, num[half])

    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }
    li{
      width: 10em;
      border: 1px solid #000;
    }
    li:empty{
      border: none;
    }

  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
  </ul>

================================================

JQ

var li = $('ul li');
    $($('<li>')).insertBefore(li[li.length / 2])

* {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
      width: 60%;
      margin: auto;
    }

    li {
      width: 10em;
      border: 1px solid #000;
    }

    li:empty {
      border: none;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
    <li>item5</li>
    <li>item6</li>
    <li>item7</li>
    <li>item8</li>
  </ul>


问:
How to create sub associative array?
I am learning associative arrays. This is what I am doing:

```<code>array_push( $classe ,array(
  'year'=>$annoClasse,
  'section'=>$sezione,
  'student'=>$member->first_name." ".$member->last_name)
);
</code>```

That creates:

```<code>array (
  0 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Stephany Johnson',
  ),
  1 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Sandra White',
  ),
)
</code>```

How would I create something like this? Basically to have each separate property for the student.

```<code>array (
  0 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Stephany',
      'surname' => 'Johnson'
    )
  ),
  1 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Sandra',
      'surname' => 'White'
     ),
   )
 )
</code>```

And how would I then echo the student only?

答:
You can assign anything to the array key, it can be a bool, integer, string, or array. In your case just assign a new array to the student key.</p>

```<code>array_push( $classe, array(
   'year'    => $annoClasse,
   'section' => $sezione,
   'student' => array(
       'name' => $member->first_name,
       'surname' => $member->last_name
   )
));
</code>```

Title: How to create sub associative array?

Body:
I am learning associative arrays. This is what I am doing:

array_push( $classe ,array(
  'year'=>$annoClasse,
  'section'=>$sezione,
  'student'=>$member->first_name." ".$member->last_name)
);

That creates:

array (
  0 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Stephany Johnson',
  ),
  1 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Sandra White',
  ),
)

How would I create something like this? Basically to have each separate property for the student.

array (
  0 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Stephany',
      'surname' => 'Johnson'
    )
  ),
  1 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Sandra',
      'surname' => 'White'
     ),
   )
 )

And how would I then echo the student only?

Body:
You can assign anything to the array key, it can be a bool, integer, string, or array. In your case just assign a new array to the student key.

array_push( $classe, array(
   'year'    => $annoClasse,
   'section' => $sezione,
   'student' => array(
       'name' => $member->first_name,
       'surname' => $member->last_name
   )
));


问:
Group by two columns and count duplicate as 1 in Power BI
I have two columns on a table (List) which has the following

List Table (Input)

Output:

Moreover; I want to create a donut chart to get the output count of specific ERP: Xero and count the rest as 1 so it will be XERO/The Rest of ERP.

答:
Use Advanced groupby option in power query like below.

Note you should select both the columns by holding control key.


问:
How to prevent selection of a SortableJS item when clicking on one of its child elements?
The Issue

I'm using SortableJS to build a draggable tree component. Which means each of my sortable-items has a toggle-arrow as a child element that opens and closes a sub-tree (if there is one).

I'm attempting to use stopPropagation() to prevent the selection of the parent sortable-item if the toggle-arrow is clicked, but it's not working.

It looks like this when closed:

And looks like this when open:

The blue highlight you see in the open state (the second image) is the styling I've chosen for the selectedClass option when using the multiDrag plugin.

This is illustrating that when I click on the toggle-arrow it results in the parent sortable-item being selected.

I don't want this to happen.

The Code

The code for an item in my SortableJS tree component looks like so (using Vue.js, and Pug syntax):

```<code>div.sortable-item
    div.content
        div.toggle-arrow(@click.stop="toggleTree($event)")
        div.icon
        div.title
    div.sub-tree
</code>```

And then I've got a handler for the @click binding on my toggle-arrow element:

```<code>toggleTree = function($event) {
    $event.stopPropagation()
    /// Code for handling the sub-tree toggling goes here.
    /// The sub-tree toggling itself works just fine.
}
</code>```

You can see that I'm declaring @click.stop as the event binding, which should stop the click event from bubbling up from the toggle-arrow child element, but it's not working.

I'm even attempting to use $event.stopPropagation within the handler. But, the event seems to continue to bubble, and thus the parent sortable-item element ends up in a selected state.

I've also tried declaring @click.native.stop as the event binding, but it simply prevents my toggleTree method from firing at all. I'm assuming there's another event handler somewhere within SortableJS that's interfering with the @click.native.stop binding.

Questions

How do I stop propagation of an event when a child element of my sortable-item is clicked?

How is selection handled by the multiDrag plugin? I dug through the code and saw that the select event is fired within the handler of the drop event of the sortable-item, but I'm confused by that. Why is the drop event handler being used to toggle selection of a sortable-item?

Thanks in advance for any light you may be able to shed on this.

答:
Change

```<code>div.toggle-arrow(@click.stop="toggleTree($event)")
</code>```

to

```<code>div.toggle-arrow(@click.native.stop="toggleTree($event)")
</code>```

If all you did in toggleTree was stopPropagation, you could have changed it to:

```<code>div.toggle-arrow(@click.native.stop)
</code>```

Docs.

In short, you're currently stopping propagation on any emitted clicks from the child component (a.k.a. custom Vue event, which doesn't actually need propagation stopped as it doesn't bubble by default). What you want to do is call event.stopPropagation() on the native click event.

An alternative would be to use:

```<code>div.toggle-arrow(@click.native="toggleTree($event)")
</code>```

... and call .stopPropagation() inside toggleTree. Which is precisely what .stop modifier does.

Body:
The Issue

I'm using SortableJS to build a draggable tree component. Which means each of my sortable-items has a toggle-arrow as a child element that opens and closes a sub-tree (if there is one).

I'm attempting to use stopPropagation() to prevent the selection of the parent sortable-item if the toggle-arrow is clicked, but it's not working.

It looks like this when closed:

And looks like this when open:

The blue highlight you see in the open state (the second image) is the styling I've chosen for the selectedClass option when using the multiDrag plugin.

This is illustrating that when I click on the toggle-arrow it results in the parent sortable-item being selected.

I don't want this to happen.

The Code

The code for an item in my SortableJS tree component looks like so (using Vue.js, and Pug syntax):

div.sortable-item
    div.content
        div.toggle-arrow(@click.stop="toggleTree($event)")
        div.icon
        div.title
    div.sub-tree

And then I've got a handler for the @click binding on my toggle-arrow element:

toggleTree = function($event) {
    $event.stopPropagation()
    /// Code for handling the sub-tree toggling goes here.
    /// The sub-tree toggling itself works just fine.
}

You can see that I'm declaring @click.stop as the event binding, which should stop the click event from bubbling up from the toggle-arrow child element, but it's not working.

I'm even attempting to use $event.stopPropagation within the handler. But, the event seems to continue to bubble, and thus the parent sortable-item element ends up in a selected state.

I've also tried declaring @click.native.stop as the event binding, but it simply prevents my toggleTree method from firing at all. I'm assuming there's another event handler somewhere within SortableJS that's interfering with the @click.native.stop binding.

Questions

How do I stop propagation of an event when a child element of my sortable-item is clicked?

How is selection handled by the multiDrag plugin? I dug through the code and saw that the select event is fired within the handler of the drop event of the sortable-item, but I'm confused by that. Why is the drop event handler being used to toggle selection of a sortable-item?

Thanks in advance for any light you may be able to shed on this.

Body:
Change

div.toggle-arrow(@click.stop="toggleTree($event)")

to

div.toggle-arrow(@click.native.stop="toggleTree($event)")

If all you did in toggleTree was stopPropagation, you could have changed it to:

div.toggle-arrow(@click.native.stop)

Docs.

In short, you're currently stopping propagation on any emitted clicks from the child component (a.k.a. custom Vue event, which doesn't actually need propagation stopped as it doesn't bubble by default). What you want to do is call event.stopPropagation() on the native click event.

An alternative would be to use:

div.toggle-arrow(@click.native="toggleTree($event)")

... and call .stopPropagation() inside toggleTree. Which is precisely what .stop modifier does.


问:
Why is AWS Lambda function returning a different response value from backend?
BackEnd: I am using using AWS Lambda Project .NET Core C#

In the backend, I am returning code something like this:

```<code>var response = new APIGatewayProxyResponse
{
      StatusCode = (int)HttpStatusCode.OK,
      Body = Convert.ToBase64String(fooByteArray),
      IsBase64Encoded = true,
      Headers = new Dictionary<string, string> { { "Content-Type", 'application/pdf' }, { "Access-Control-Allow-Origin", "*" } },
};

return response;
</code>```

When I test in the Mock Lambda Test Tool, the value that it is returning is correct (I can literally copy paste the string in the front end and it will return the correct PDF values).

However, when I deploy this in AWS lambda, the response value changed (is lesser) and has some weird data in the PDF (for example, value is suppose to be $12.00, it now returns $12.000)

I tried everything, such as what I usually use:

```<code>Body = JsonConvert.SerializeObject(fooBytesWrappedInModelClass, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }),
</code>```

In the end, it always returns that weird $12.000. I don't want a hack fix on the front end to handle the extra zeroes as the PDF is a huge file and there may be other texts missing.

ADDITIONAL NOTES: I tried the following

Direct convert of byte array to Json serialize object

Converting byte
array into hex (lambda still has missing response values)

The problem is on Lambda itself (since the value there is already different) and not in Api Gateway yet

PDF byte array response has a range of 200K to 320K

Amount of response missing from 320K one was 12K characters

答: By default API Gateway, which is calling the Lambda function, doesn't handle binary data returned from Lambda. You will need to configure API Gateway to pass along the content as binary. Here is the docs about binary content for API Gateway https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html</p>

Body:
BackEnd: I am using using AWS Lambda Project .NET Core C#

In the backend, I am returning code something like this:

var response = new APIGatewayProxyResponse
{
      StatusCode = (int)HttpStatusCode.OK,
      Body = Convert.ToBase64String(fooByteArray),
      IsBase64Encoded = true,
      Headers = new Dictionary<string, string> { { "Content-Type", 'application/pdf' }, { "Access-Control-Allow-Origin", "*" } },
};

return response;

When I test in the Mock Lambda Test Tool, the value that it is returning is correct (I can literally copy paste the string in the front end and it will return the correct PDF values).

However, when I deploy this in AWS lambda, the response value changed (is lesser) and has some weird data in the PDF (for example, value is suppose to be $12.00, it now returns $12.000)

I tried everything, such as what I usually use:

Body = JsonConvert.SerializeObject(fooBytesWrappedInModelClass, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }),

In the end, it always returns that weird $12.000. I don't want a hack fix on the front end to handle the extra zeroes as the PDF is a huge file and there may be other texts missing.

ADDITIONAL NOTES: I tried the following

Direct convert of byte array to Json serialize object

Converting byte
array into hex (lambda still has missing response values)

The problem is on Lambda itself (since the value there is already different) and not in Api Gateway yet

PDF byte array response has a range of 200K to 320K

Amount of response missing from 320K one was 12K characters


问:
Pass Azure devops release pipeline(Classic editor) output variable to multiple jobs in same stage or to multiple stages outside
I am using the release pipeline classic editor and have a requirement of passing an output variable generated in a task to multiple jobs in the same stage or to outside stages. Currently, this output variable is available only inside the same job and I have to write the same task in multiple jobs and stages and I feel it is a redundancy. Is there any way to implement it?.</p>

答:
In the Classic editor, I am afraid that output variables in a different job is not feasible. Please refer to this document .

As a workaround , you can use variables across jobs and stages via variable groups.

First define the variable in the variable group, then update the variable group through rest api or azure cli, and replace the defined variable with the value of the variable generated by the task.

```<code>PUT https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups/{groupId}?api-version=5.1-preview.1
</code>```

Here is a case about update variable group with powershell script.

Another workaround : You can share values across all of the stages by using release pipeline variables. The solution is updating the Release Definition for the Release Pipeline variable in the Stage where the variable is set.

Define a variable in the release definition Variable.

Use REST API Definitions - Update to update the value of the
release definition variable in the agent job.

Use the updated value of the release definition variable in the next
agent job.

The details info about using REST API to update the value of the release definition variable, you can follow this ticket.

For detailed steps and guide, please refer to this blog .

Body:
In the Classic editor, I am afraid that output variables in a different job is not feasible. Please refer to this document .

As a workaround , you can use variables across jobs and stages via variable groups.

First define the variable in the variable group, then update the variable group through rest api or azure cli, and replace the defined variable with the value of the variable generated by the task.

PUT https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups/{groupId}?api-version=5.1-preview.1

Here is a case about update variable group with powershell script.

Another workaround : You can share values across all of the stages by using release pipeline variables. The solution is updating the Release Definition for the Release Pipeline variable in the Stage where the variable is set.

Define a variable in the release definition Variable.

Use REST API Definitions - Update to update the value of the
release definition variable in the agent job.

Use the updated value of the release definition variable in the next
agent job.

The details info about using REST API to update the value of the release definition variable, you can follow this ticket.

For detailed steps and guide, please refer to this blog .


问:
What does $ in Erlang shell output information mean
shell info

when enter the follow Erlang shell command:

```<code>proc_lib:spawn(fun() -> io:format("~p~n",[process_info(self())]) end).
</code>```

The Erlang will show the following info in the picture.

```<code>[{current_function,{erl_eval,do_apply,6}},
 {initial_call,{proc_lib,init_p,3}},
 {status,running},
 {message_queue_len,0},
 {messages,[]},
 {links,[]},
 {dictionary,[{'$ancestors',[<0.32.0>]},
              {'$initial_call',{erl_eval,'-expr/5-fun-3-',0}}]},
 {trap_exit,false},
 {error_handler,error_handler},
 {priority,normal},
 {group_leader,<0.25.0>},
 {total_heap_size,233},
 {heap_size,233},
 {stack_size,27},
 {reductions,72},
 {garbage_collection,[{min_bin_vheap_size,46422},
                      {min_heap_size,233},
                      {fullsweep_after,65535},
                      {minor_gcs,0}]},
 {suspending,[]}]
<0.34.0>
</code>```

What does "$",6 and 5-fun-3- (In case you don't know what I'm referring to, I've uploaded a picture to illustrate)mean in the Erlang shell output info?
Thank you.

答: In Erlang, anything enclosed in single quotes, e.g. '$ancestors' is an atom.

Body:
shell info

when enter the follow Erlang shell command:

proc_lib:spawn(fun() -> io:format("~p~n",[process_info(self())]) end).

The Erlang will show the following info in the picture.

[{current_function,{erl_eval,do_apply,6}},
 {initial_call,{proc_lib,init_p,3}},
 {status,running},
 {message_queue_len,0},
 {messages,[]},
 {links,[]},
 {dictionary,[{'$ancestors',[<0.32.0>]},
              {'$initial_call',{erl_eval,'-expr/5-fun-3-',0}}]},
 {trap_exit,false},
 {error_handler,error_handler},
 {priority,normal},
 {group_leader,<0.25.0>},
 {total_heap_size,233},
 {heap_size,233},
 {stack_size,27},
 {reductions,72},
 {garbage_collection,[{min_bin_vheap_size,46422},
                      {min_heap_size,233},
                      {fullsweep_after,65535},
                      {minor_gcs,0}]},
 {suspending,[]}]
<0.34.0>

What does "$",6 and 5-fun-3- (In case you don't know what I'm referring to, I've uploaded a picture to illustrate)mean in the Erlang shell output info?
Thank you.


问:
Spark/Hadoop can't find file on AWS EMR
I'm trying to read in a text file on Amazon EMR using the python spark libraries.  The file is in the home directory (/home/hadoop/wet0), but spark can't seem to find it.

Line in question:

```<code>lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0])
</code>```

Error:

```<code>pyspark.sql.utils.AnalysisException: u'Path does not exist: hdfs://ip-172-31-19-121.us-west-2.compute.internal:8020/user/hadoop/wet0;'
</code>```

Does the file have to be in a specific directory?  I can't find information about this anywhere on the AWS website.

答:
I don't know if it's just me, but when I tried to solve the problem with the suggestion above, I got an error "path does not exist" in my EMR. I just added one more "/" before user and it worked.

file:///user/hadoop/wet0

Thanks for the help!

ContentLicense: CC BY-SA 3.0

Title: Spark/Hadoop can't find file on AWS EMR

Body:
I'm trying to read in a text file on Amazon EMR using the python spark libraries.  The file is in the home directory (/home/hadoop/wet0), but spark can't seem to find it.

Line in question:

lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0])

Error:

pyspark.sql.utils.AnalysisException: u'Path does not exist: hdfs://ip-172-31-19-121.us-west-2.compute.internal:8020/user/hadoop/wet0;'

Does the file have to be in a specific directory?  I can't find information about this anywhere on the AWS website.


问:
import module in Google Colab from google drive - python
I have a problem with import ipynb file from my google drive. I've tried solutions from:
Importing .py files in Google Colab
How to import custom modules in google colab?

but does not work for me.

```<code># COLAB
from google.colab import files
from google.colab import drive
# SYS
import sys
# IPYNB
!pip install import-ipynb
import import_ipynb
# UTIL
import importlib.util
</code>```

I've tried something like this:

```<code>drive.mount('/content/drive')
sys.path.append('/content/drive/My Drive/Colab Notebooks/')
import Data_Preparation_Library
</code>```

Or this:

```<code>!cp "/content/drive/My Drive/Colab Notebooks/Data_Preparation_Library.ipynb"
import Data_Preparation_Library

</code>```

Here is how my gdrive structure looks like:

Thank You for answers in advance

答:
SOURCE

Step 1
Primarily, you must Mount your google drive in google colab:
Code to below, your files on your google drive is import files/packages inside a google colab.

```<code># Mount your google drive in google colab
from google.colab import drive
drive.mount('/content/drive')
</code>```

Step 2
Secondly, insert the directory to your python path using sys:

```<code># Insert the directory
import sys
sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)
</code>```

Step 3
Now, you can be able to import your module or file stuff from that directory.

```<code># Import your module or file
import my_module
</code>```

Body:
I have a problem with import ipynb file from my google drive. I've tried solutions from:
Importing .py files in Google Colab
How to import custom modules in google colab?

but does not work for me.

# COLAB
from google.colab import files
from google.colab import drive
# SYS
import sys
# IPYNB
!pip install import-ipynb
import import_ipynb
# UTIL
import importlib.util

I've tried something like this:

drive.mount('/content/drive')
sys.path.append('/content/drive/My Drive/Colab Notebooks/')
import Data_Preparation_Library

Or this:

!cp "/content/drive/My Drive/Colab Notebooks/Data_Preparation_Library.ipynb"
import Data_Preparation_Library

Here is how my gdrive structure looks like:

Thank You for answers in advance

Body:
SOURCE

Step 1
Primarily, you must Mount your google drive in google colab:
Code to below, your files on your google drive is import files/packages inside a google colab.

# Mount your google drive in google colab
from google.colab import drive
drive.mount('/content/drive')

Step 2
Secondly, insert the directory to your python path using sys:

# Insert the directory
import sys
sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

Step 3
Now, you can be able to import your module or file stuff from that directory.

# Import your module or file
import my_module


问:
Taking data out of JSONP
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

```<code>jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })
</code>```

At clientside, I have the following script:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});
</code>```

How do I write some of the jsonp content to the screen, i.e.

```<code>channel title: title goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />
</code>```

instead of alerting "success"?

答:
try this:

```<code>for (var i = 0; i < jsonpCallback.rss.channels.length; i++) {
    document.write("<hr/><b>" + i + "</b><br/>");
    document.write("Channel Title=>" + jsonpCallback.rss.channels[i].title );
}

var itemList = jsonpCallback.rss.channels[0].items;

for (var k = 0; k < itemList.length; k++) {
    document.write("<hr/>Item Number:<b>" + k + "</b><br/>");
    document.write("<br/>Item Title=>" + itemList[k].title );
    document.write("<br/>Item Link=>" +  itemList[k].link );
    document.write("<br/>Item Publication Title=>" + itemList[k].pubDate );
    document.write("<br/>Item Description=>" +  itemList[k].description );
}
</code>```

Working DEMO

Title: Taking data out of JSONP

Body:
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })

At clientside, I have the following script:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});

How do I write some of the jsonp content to the screen, i.e.

channel title: title goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

instead of alerting "success"?

Body:
try this:

for (var i = 0; i < jsonpCallback.rss.channels.length; i++) {
    document.write("<hr/><b>" + i + "</b><br/>");
    document.write("Channel Title=>" + jsonpCallback.rss.channels[i].title );
}

var itemList = jsonpCallback.rss.channels[0].items;

for (var k = 0; k < itemList.length; k++) {
    document.write("<hr/>Item Number:<b>" + k + "</b><br/>");
    document.write("<br/>Item Title=>" + itemList[k].title );
    document.write("<br/>Item Link=>" +  itemList[k].link );
    document.write("<br/>Item Publication Title=>" + itemList[k].pubDate );
    document.write("<br/>Item Description=>" +  itemList[k].description );
}

Working DEMO


问:
How to play video url from api request in flutter , i used video player package but not include back or exit screen?
I have Ali Json then there object called video I include url video so how to display this url in app , I use video player but full screen not work and can't control on ui to add button exit or button back in ui video player .</p>

答: Try to use video_player along with chewie, it has more control over the video.</p>


问:
ValueError: Iterable over raw text documents expected, string object received. Predicting new test data with tfidf and selection feature
So i have build a model with sklearn Naive Bayes classifier.
I need to know how to predict a sentence with input

when i just hardcode the sentence its work fine, look like this

```<code>new_sentence = ['its so broken']
new_testdata_tfidf= tfidf.transform(new_sentence)
#transform it to matrix to see the score TFIDF on the training data
fit_feature_selection = selection.transform(new_testdata_tfidf)
#transform the new data to see if the feature remove or not, because after tfidf i use chi2 selection feature.
predicted = classifier.predict(feature_selection )
#then predict it. the classificaiton out, the class is -1 which is the correct answer
</code>```

i need to type the text data with hand as an input so I use like this

```<code>new_sentence = input[('')]
#i input the same sentence its so broken
new_testdata_tfidf= tfidf.transform(new_sentence)
#transform it to matrix to see the score TFIDF on the training data
fit_feature_selection = selection.transform(new_testdata_tfidf)
#transform the new data to see if the feature remove or not, because after tfidf i use chi2 selection feature.
predicted = classifier.predict(feature_selection )
</code>```

but it give me output

```<code>  File "C:\Users\Myfile\OneDrive\Desktop\model.py", line 170, in <module>
   new_testdata_tfidf= tfidf.transform(new_sentence)

  File "E:\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1898, in transform
    X = super().transform(raw_documents)

  File "E:\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1265, in transform
    "Iterable over raw text documents expected, "

ValueError: Iterable over raw text documents expected, string object received.
</code>```

How to resolve this?
any help really appreciated.

答:
Have you tried passing the new sentence as an array? i.e.

```<code>new_testdata_tfidf= tfidf.transform([new_sentence])
</code>```

The first instance you are passing an array with one string element and the other you are simply passing a string

Body:
So i have build a model with sklearn Naive Bayes classifier.
I need to know how to predict a sentence with input

when i just hardcode the sentence its work fine, look like this

new_sentence = ['its so broken']
new_testdata_tfidf= tfidf.transform(new_sentence)
#transform it to matrix to see the score TFIDF on the training data
fit_feature_selection = selection.transform(new_testdata_tfidf)
#transform the new data to see if the feature remove or not, because after tfidf i use chi2 selection feature.
predicted = classifier.predict(feature_selection )
#then predict it. the classificaiton out, the class is -1 which is the correct answer

i need to type the text data with hand as an input so I use like this

new_sentence = input[('')]
#i input the same sentence its so broken
new_testdata_tfidf= tfidf.transform(new_sentence)
#transform it to matrix to see the score TFIDF on the training data
fit_feature_selection = selection.transform(new_testdata_tfidf)
#transform the new data to see if the feature remove or not, because after tfidf i use chi2 selection feature.
predicted = classifier.predict(feature_selection )

but it give me output

  File "C:\Users\Myfile\OneDrive\Desktop\model.py", line 170, in <module>
   new_testdata_tfidf= tfidf.transform(new_sentence)

  File "E:\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1898, in transform
    X = super().transform(raw_documents)

  File "E:\anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1265, in transform
    "Iterable over raw text documents expected, "

ValueError: Iterable over raw text documents expected, string object received.

How to resolve this?
any help really appreciated.

Body:
Have you tried passing the new sentence as an array? i.e.

new_testdata_tfidf= tfidf.transform([new_sentence])

The first instance you are passing an array with one string element and the other you are simply passing a string


问:
Django Rest Framework - Authentication credentials were not provided
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:

```<code>{"detail": "Authentication credentials were not provided."}
</code>```

Views:

```<code>from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated

class OrderViewSet(viewsets.ModelViewSet):
    model = Order
    serializer_class = OrderSerializer
    permission_classes = (IsAuthenticated,)
</code>```

Serializer:

```<code>class OrderSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Order
        fields = ('field1', 'field2')
</code>```

And my URLs:

```<code># -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *

admin.autodiscover()

handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"

router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)

urlpatterns = patterns('',
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
    url(r'^api/', include(router.urls)),
)
</code>```

And then I'm using this command in the console:

```<code>curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'
</code>```

And the error say:

```<code>{"detail": "Authentication credentials were not provided."}
</code>```

答:
For me, I had to prepend my Authorization header with "JWT" instead of "Bearer" or "Token" on Django DRF. Then it started working.
eg -

Authorization: JWT asdflkj2ewmnsasdfmnwelfkjsdfghdfghdv.wlsfdkwefojdfgh

Body:
I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:

{"detail": "Authentication credentials were not provided."}

Views:

from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated

class OrderViewSet(viewsets.ModelViewSet):
    model = Order
    serializer_class = OrderSerializer
    permission_classes = (IsAuthenticated,)

Serializer:

class OrderSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Order
        fields = ('field1', 'field2')

And my URLs:

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *

admin.autodiscover()

handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"

router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)

urlpatterns = patterns('',
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
    url(r'^api/', include(router.urls)),
)

And then I'm using this command in the console:

curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'

And the error say:

{"detail": "Authentication credentials were not provided."}


问:
How do I enter/ find the correct token or error?
I want to create a Discord bot that can remotely start my Minecraft SpigotMC Server, but when I try to run my bot using node bot.js, it outputs an error message,

```<code>(node:19880) UnhandledPromiseRejectionWarning: Error [TOKEN_INVALID]: An invalid token was provided.
    at WebSocketManager.connect (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\websocket\WebSocketManager.js:135:26)
    at Client.login (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\Client.js:221:21)
(node:19880) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19880) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Here is my package.json code:

{
  "name": "Serverstart",
  "version": "1.0.0",
  "description": "Bot doing Bot things",
  "main": "bot.js",
  "author": "PalanixYT",
  "dependencies": {
    "discord.io": "https://github.com/woor/discord.io/tarball/gateway_v6",
    "discord.js": "^12.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "winston": "^3.2.1"
  }
}
```

<p>And my auth.json:(Don't worry, I already renewed my token)</p>

<pre class="lang-js prettyprint-override"><code>{
  "token":"NzE3MTI2NDcyMjM3NTgwMjg4.XtWKZw.go81ay5fCu52yyn-xYiK1eIwTzI"
}
</code>```

If I need to give more information, I am more then willing to do so.

答:
Did you try using this?</p>

```<code>const config = require('path-to-auth.json');

bot.login(config.token);
</code>```

Body:
I want to create a Discord bot that can remotely start my Minecraft SpigotMC Server, but when I try to run my bot using node bot.js, it outputs an error message,

(node:19880) UnhandledPromiseRejectionWarning: Error [TOKEN_INVALID]: An invalid token was provided.
    at WebSocketManager.connect (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\websocket\WebSocketManager.js:135:26)
    at Client.login (C:\Users\David\Desktop\Serverstart\node_modules\discord.js\src\client\Client.js:221:21)
(node:19880) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19880) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my package.json code:

{
  "name": "Serverstart",
  "version": "1.0.0",
  "description": "Bot doing Bot things",
  "main": "bot.js",
  "author": "PalanixYT",
  "dependencies": {
    "discord.io": "https://github.com/woor/discord.io/tarball/gateway_v6",
    "discord.js": "^12.2.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "winston": "^3.2.1"
  }
}

And my auth.json:(Don't worry, I already renewed my token)

{
  "token":"NzE3MTI2NDcyMjM3NTgwMjg4.XtWKZw.go81ay5fCu52yyn-xYiK1eIwTzI"
}

If I need to give more information, I am more then willing to do so.

Body:
Did you try using this?

const config = require('path-to-auth.json');

bot.login(config.token);


问:
Equivalent of "describe table" in PgAdmin3
Question asked and answered:

As many of us know, PostgreSQL does not support describe table or describe view.  As one might find from google, PostgreSQL uses \d+ instead.

However, if one accesses PostgreSQL using PgAdmin (I am actually using PgAdmin3) then \d+ does not work.  What does one do instead?

I thought about this question when playing with the query tool in PgAdmin3.  I had a "well, duh!" moment when I thought to look at the home window of PgAdmin3, and at the tree on the left side of that window.  Under

```<code><servername>
-> <databasename>
-> Schemas
-> <schemaname>
-> Tables
</code>```

was a list of my tables,
and clicking on the table name showed me text
very much like what \d+ would have showed me.

So for the benefit of anyone else who did not discover this right away, here is an answer.

答:
you can use the following command:
\d Table_Name</p>

Body:
Question asked and answered:

As many of us know, PostgreSQL does not support describe table or describe view.  As one might find from google, PostgreSQL uses \d+ instead.

However, if one accesses PostgreSQL using PgAdmin (I am actually using PgAdmin3) then \d+ does not work.  What does one do instead?

I thought about this question when playing with the query tool in PgAdmin3.  I had a "well, duh!" moment when I thought to look at the home window of PgAdmin3, and at the tree on the left side of that window.  Under

<servername>
-> <databasename>
-> Schemas
-> <schemaname>
-> Tables

was a list of my tables,
and clicking on the table name showed me text
very much like what \d+ would have showed me.

So for the benefit of anyone else who did not discover this right away, here is an answer.


问:
Module 'google.cloud.speech_v1.types' has no 'RecognitionAudio' member and Module 'google.cloud.speech_v1.types' has no 'RecognitionConfig' member
I'm using Windows and Python 3.8.3, and using the Cloud Speech-to-Text API from the Google Cloud Platform, and every time I save my code it points to an error

"Module 'google.cloud.speech_v1.types' has no 'RecognitionAudio' member "

and

"Module 'google.cloud.speech_v1.types' has no 'RecognitionConfig' member "

I looked at the documentation and the only thing that talks about is versions prior to Python 2.7, which does not apply to me, does anyone know any solution to this problem?

```<code>import telebot
import requests
from pydub import AudioSegment

import os
import io

from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./chatbotia-279018-759b32f57985.json"

token = "1233361335:AAEO4qSTP6EraU6DvzU"
bot = telebot.TeleBot(token)
downloadAudio = "https://api.telegram.org/file/bot{token}/".format(token = token)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Bem vindo ao bot de escrita, por favor mande um áudio  que lhe será retornado da mesma forma, mas em uma mensagem escrita")
    bot.reply_to(message, "qualquer duvida mande /help.")

@bot.message_handler(commands=['help'])
def send_help(message):
    bot.reply_to(message, " disque 190")

@bot.message_handler(content_types=['voice'])
def handlerAudio(message):

    #get audio from telegram
    messageVoice = message.voice

    #get download link
    audioPath = bot.get_file(messageVoice.file_id).file_path
    audioLink = downloadAudio+audioPath

    #download file
    audioFile = requests.get(audioLink)
    audioName = "audio.ogg"

    #save locally
    open(audioName, 'wb').write(audioFile.content)

    #convert format to .WAV
    AudioSegment.from_file(audioName).export("audio.wav", format="wav")
    sound = AudioSegment.from_wav("audio.wav")
    sound = sound.set_channels(1) #convert mono
    sound.export("audio.wav", format="wav")

client = speech.SpeechClient()

with io.open("audio.wav", 'rb') as audio_file:
        content = audio_file.read()

audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
    encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code='en-US')

response = client.recognize(config, audio)
for result in response.results:
  print(u'Transcript: {}'.format(result.alternatives[0].transcript))

bot.polling()
</code>```

答:
In the documentation and Github's README,  types is imported from from google.cloud.speech_v1 instead of google.cloud.speech.

Have you already tried that?

EDIT: After further analysis, it appears that the errors are warnings from the IDE. Google cloud SDK's import mechanism often causes the IDE to show that kind of warnings but the code still works.

Body:
I'm using Windows and Python 3.8.3, and using the Cloud Speech-to-Text API from the Google Cloud Platform, and every time I save my code it points to an error

"Module 'google.cloud.speech_v1.types' has no 'RecognitionAudio' member "

and

"Module 'google.cloud.speech_v1.types' has no 'RecognitionConfig' member "

I looked at the documentation and the only thing that talks about is versions prior to Python 2.7, which does not apply to me, does anyone know any solution to this problem?

import telebot
import requests
from pydub import AudioSegment

import os
import io

from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./chatbotia-279018-759b32f57985.json"

token = "1233361335:AAEO4qSTP6EraU6DvzU"
bot = telebot.TeleBot(token)
downloadAudio = "https://api.telegram.org/file/bot{token}/".format(token = token)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Bem vindo ao bot de escrita, por favor mande um áudio  que lhe será retornado da mesma forma, mas em uma mensagem escrita")
    bot.reply_to(message, "qualquer duvida mande /help.")

@bot.message_handler(commands=['help'])
def send_help(message):
    bot.reply_to(message, " disque 190")

@bot.message_handler(content_types=['voice'])
def handlerAudio(message):

    #get audio from telegram
    messageVoice = message.voice

    #get download link
    audioPath = bot.get_file(messageVoice.file_id).file_path
    audioLink = downloadAudio+audioPath

    #download file
    audioFile = requests.get(audioLink)
    audioName = "audio.ogg"

    #save locally
    open(audioName, 'wb').write(audioFile.content)

    #convert format to .WAV
    AudioSegment.from_file(audioName).export("audio.wav", format="wav")
    sound = AudioSegment.from_wav("audio.wav")
    sound = sound.set_channels(1) #convert mono
    sound.export("audio.wav", format="wav")

client = speech.SpeechClient()

with io.open("audio.wav", 'rb') as audio_file:
        content = audio_file.read()

audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
    encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code='en-US')

response = client.recognize(config, audio)
for result in response.results:
  print(u'Transcript: {}'.format(result.alternatives[0].transcript))

bot.polling()