问:
PHP javascript refresh div breaks page with multiple timers after setInterval runs
I have a page fetching multiple data for a table. One of the data columns has a date and time value
from where a countdown timer runs.Each row has it's own countdown timer and it's working well.

However after I included javascript code to refresh the table after every 10 seconds and get new records inserted into the database, the page breaks and only displays the first timer in the countdown column timers. The tables uses datatable js library. Any recommended way that can enable the page div container to load the page correctly with javascript setinterval function will be highly appreciated.
The code below is what I use for refreshing the page div container

```<code><script type="text/javascript">
$(document).ready(function() {
  $.ajaxSetup({
    cache: false
  });
  setInterval(function() {
    var url = "loaded.php";
    $('#loaded_orders').load(url + " #loaded_orders").fadeIn('slow');
  }, 10000);
});
</code>```

This code I use to start the count down timer in the table columns. The table is wrapped in the div with the id "loaded_orders"

```<code><table class="table table-bordered table stripped table hover" data-order='[[ 0, " desc" ]]' id="dataTable" width="100%" cellspacing="0">
      <thead>
        <tr>
          <th>ID </th>
          <th>Order No</th>
          <th>Order title</th>
          <th>Actual Deadline</th>
          <th>Assigned Writer</th>
          <th>Inserted By</th>
          <th>Action</th>
        </tr>
      </thead>
      <tfoot>
        <tr>
          <th>ID </th>
          <th>Order No.</th>
          <th>Order title</th>
          <th>Actual Deadline</th>
          <th>Assigned Writer</th>
          <th>Inserted By</th>
          <th>Action</th>
        </tr>
      </tfoot>
      <tbody>
        <?php while ($row = $result->fetch_assoc()) {
          //echo json_encode($row);
        ?>
          <tr>
            <td><?= $row['id']; ?> </td>
            <td><?= $row['orderno']; ?></td>
            <td> <?= $row['ordertitle']; ?> </td>
            <td>
              <script src="./js/countdown.js" type="text/javascript"></script>
              <script>
                u_d = ("d" + "<?= $row['id']; ?>");
                u_h = ("h" + "<?= $row['id']; ?>");
                u_m = ("m" + "<?= $row['id']; ?>");
                u_s = ("s" + "<?= $row['id']; ?>");
                ty = "<?= $row['actdeadline']; ?>";

                document.write("<div class='writerDeadl'><p class='timer'><span id='" + u_d + "'></span> Day(s) <span id='" + u_h + "'></span>:<span id='" + u_m + "'></span>:<span id='" + u_s + "'></span></p></div>");

                countdown(ty, u_d, u_h, u_m, u_s);
              </script>
            </td>
            <td><?= $row['asswriter'];  ?> </td>
            <td><?= $row['inserted_by']; ?></td>
            <td><a href="details.php?details=<?= $row['id']; ?>" class="badge badge-primary p-2" target="_blank">Details</a> |
              <a href="includes/action.php?deleted=<?= $row['id']; ?>&page=loaded" class="badge badge-danger p-2" onclick="return confirm('Are you sure you want to delete this Record?');">del<i class="fas fa-trash "></i></a> |
              <a href="edit_order.php?edit=<?= $row['id']; ?>&page=loaded" class="badge badge-secondary p-2">Edit<i class="fas fa-edit"></i></a> |
              <a href="includes/action.php?send=<?= $row['id']; ?>" class="badge badge-success p-2" onclick="return confirm('Are you sure you want to send this order?');">send<i class="fas fa-paper-plane"></i></a> |
              <a href="includes/action.php?scancel=<?= $row['id']; ?>" class="badge badge-dark p-2" onclick="return confirm('Are you sure you want to cancel this order?');">cancel</a>
            </td>
          </tr>
        <?php } ?>
      </tbody>
    </table>
</code>```

The code below is for countdown.js file

```<code>function countdown(endDate, uid_d, uid_h, uid_m, uid_s) {
let timer, days, hours, minutes, seconds;

endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
    return;
}

if (uid_d != null) {
    timer = setInterval(calculate, 1000);
}

function calculate() {
    let startDate = new Date();

    startDate = new Date(
        startDate.getUTCFullYear(),
        startDate.getUTCMonth(),
        startDate.getUTCDate(),
        startDate.getUTCHours(),
        startDate.getUTCMinutes(),
        startDate.getUTCSeconds()
    );

    let timeRemaining = parseInt((endDate - startDate.getTime()) / 1000);

    if (timeRemaining >= 0) {
        days = parseInt(timeRemaining / 86400);
        timeRemaining = timeRemaining % 86400;

        hours = parseInt(timeRemaining / 3600);
        timeRemaining = timeRemaining % 3600;

        minutes = parseInt(timeRemaining / 60);
        timeRemaining = timeRemaining % 60;

        seconds = parseInt(timeRemaining);

        document.getElementById(uid_d).innerHTML = parseInt(days, 10);
        document.getElementById(uid_h).innerHTML = ("0" + hours).slice(-2);
        document.getElementById(uid_m).innerHTML = ("0" + minutes).slice(-2);
        document.getElementById(uid_s).innerHTML = ("0" + seconds).slice(-2);
    } else {
        return;
    }
}
</code>```

}

答: I discovered the only way to refresh datatables with setInterval without losing datatbles functionality is to use json data then draw the table. After ding that everything is working well.</p>

Body:
I have a page fetching multiple data for a table. One of the data columns has a date and time value
from where a countdown timer runs.Each row has it's own countdown timer and it's working well.

However after I included javascript code to refresh the table after every 10 seconds and get new records inserted into the database, the page breaks and only displays the first timer in the countdown column timers. The tables uses datatable js library. Any recommended way that can enable the page div container to load the page correctly with javascript setinterval function will be highly appreciated.
The code below is what I use for refreshing the page div container

            <?= $row['asswriter'];  ?>
            <?= $row['inserted_by']; ?>
            <a href="details.php?details=<?= $row['id']; ?>" class="badge badge-primary p-2" target="_blank">Details |
              <a href="includes/action.php?deleted=<?= $row['id']; ?>&page=loaded" class="badge badge-danger p-2" onclick="return confirm('Are you sure you want to delete this Record?');">del |
              <a href="edit_order.php?edit=<?= $row['id']; ?>&page=loaded" class="badge badge-secondary p-2">Edit |
              <a href="includes/action.php?send=<?= $row['id']; ?>" class="badge badge-success p-2" onclick="return confirm('Are you sure you want to send this order?');">send |
              <a href="includes/action.php?scancel=<?= $row['id']; ?>" class="badge badge-dark p-2" onclick="return confirm('Are you sure you want to cancel this order?');">cancel

        <?php } ?>

The code below is for countdown.js file

function countdown(endDate, uid_d, uid_h, uid_m, uid_s) {
let timer, days, hours, minutes, seconds;

endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
    return;
}

if (uid_d != null) {
    timer = setInterval(calculate, 1000);
}

function calculate() {
    let startDate = new Date();

    startDate = new Date(
        startDate.getUTCFullYear(),
        startDate.getUTCMonth(),
        startDate.getUTCDate(),
        startDate.getUTCHours(),
        startDate.getUTCMinutes(),
        startDate.getUTCSeconds()
    );

    let timeRemaining = parseInt((endDate - startDate.getTime()) / 1000);

    if (timeRemaining >= 0) {
        days = parseInt(timeRemaining / 86400);
        timeRemaining = timeRemaining % 86400;

        hours = parseInt(timeRemaining / 3600);
        timeRemaining = timeRemaining % 3600;

        minutes = parseInt(timeRemaining / 60);
        timeRemaining = timeRemaining % 60;

        seconds = parseInt(timeRemaining);

        document.getElementById(uid_d).innerHTML = parseInt(days, 10);
        document.getElementById(uid_h).innerHTML = ("0" + hours).slice(-2);
        document.getElementById(uid_m).innerHTML = ("0" + minutes).slice(-2);
        document.getElementById(uid_s).innerHTML = ("0" + seconds).slice(-2);
    } else {
        return;
    }
}

}


来源: stackexchange

问:
How to concatenate XML children in FILTERXML
I may have an XML string like this

```<code><data>
    <a> “one” </a>
    <a> “three” </a>
    <a> “two” </a>
</data>
</code>```

which, in an Excel cell would look like this.

```<code>[A2] = "<data><a>one</a><a>three</a><a>two</a></data>"
</code>```

I want to extract the numbers "two" and "three", in that sequence, using the FILTERXML() function. I know how to do that with this formula.

```<code>=FILTERXML(A2,"/data/a[3]") & FILTERXML(A2","/data/a[2]"))
</code>```

However, there must be a way to join the two elements in a single function call, like

```<code>=FILTERXML(A2,"/data/a[3]" & "/data/a[2]")
</code>```

In fact, I imagine that it should be even simpler than that. Can anyone show me how to do that?

答:
Alternative by addressing node positions directly

If the output order doesn't matter you can apply the AND logic juxtaposing both subordinated conditions in brackets within the XPath string:

```<code>    =FILTERXML(A2,"//a[position()>=2][position()<=3]")
</code>```

(Side note: an additional OR condition would have been written into the bracket separated by |)

If however you persist on getting the third item first you'll need the INDEX() function in addition:

```<code>    =INDEX(FILTERXML(A2,"//a[position()>=2][position()<=3]"),{2;1})
</code>```

Note: Pay attention to the semi-colon notation for vertical alignment (colon notation in most languages for a "flat" representation) as well as to the index arguments now interchanging two xml contents only,
i.e. getting the second one first and the first one at last :-)

ContentLicense: CC BY-SA 4.0

Body:
I may have an XML string like this

<data>
     “one”
     “three”
     “two”
</data>

which, in an Excel cell would look like this.

[A2] = "<data>onethreetwo</data>"

I want to extract the numbers "two" and "three", in that sequence, using the FILTERXML() function. I know how to do that with this formula.

=FILTERXML(A2,"/data/a[3]") & FILTERXML(A2","/data/a[2]"))

However, there must be a way to join the two elements in a single function call, like

=FILTERXML(A2,"/data/a[3]" & "/data/a[2]")

In fact, I imagine that it should be even simpler than that. Can anyone show me how to do that?

Body:
Alternative by addressing node positions directly

If the output order doesn't matter you can apply the AND logic juxtaposing both subordinated conditions in brackets within the XPath string:

    =FILTERXML(A2,"//a[position()>=2][position()<=3]")

(Side note: an additional OR condition would have been written into the bracket separated by |)

If however you persist on getting the third item first you'll need the INDEX() function in addition:

    =INDEX(FILTERXML(A2,"//a[position()>=2][position()<=3]"),{2;1})

Note: Pay attention to the semi-colon notation for vertical alignment (colon notation in most languages for a "flat" representation) as well as to the index arguments now interchanging two xml contents only,
i.e. getting the second one first and the first one at last :-)


问:
btrfs-transacti kills my VMWare guests, because it makes I/O unresponsive
Most of the time when BTRFS maintenance starts with process btrfs-transacti, my VMWare guest cannot access disk and restarts. Is there anything I can do? I tried to give to guest machine high io priority with ionice, but that does not help.</p>

答: OK, no one answers, so my answer can come handy. The CPU usage of btrfs-transactio (and the cleaner process) can be limited with tool cpulimit. It sits in background and if btrfs-transacti takes too much cpu, it will throttle it. That should theoretically give more space to I/O processes of vmware guests.</p>


问:
Trouble with nested ifelse statement in R
I'm trying to run a nested ifelse statement in R.  Here's a look at the structure of my data using the glimpse() function from the tidyverse:

```<code>Rows: 22,104
Columns: 9
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
</code>```

I'm trying to get R to look at the Age column and if the value is within a certain range, for it to put the geological age name into a new column called AgeName.  If the value is not within the range, I want it to move on to the next age range and so on and so forth.  Here's my code so far:

```<code>pbdb_tidyish$AgeName <- ifelse(56>=pbdb_tidyish$Age&&47.8<pbdb_tidyish$Age,
                               "Ypresian",
                               ifelse(47.8>=pbdb_tidyish$Age&&41.2<pbdb_tidyish$Age,
                                      "Lutetian",
                                      ifelse(41.2>=pbdb_tidyish$Age&&37.8<pbdb_tidyish$Age,
                                             "Bartonian",
                                             ifelse(37.8>=pbdb_tidyish$Age&&33.9<=pbdb_tidyish$Age,
                                                    "Priabonian",NA))))
</code>```

When I run this code, it creates the new column but fills the whole column with "Priabonian" so the dataset now looks like this:

```<code>Rows: 22,104
Columns: 10
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
$ AgeName                 <chr> "Priabonian", "Priabonian", "Priabonian", "Priabonia...
</code>```

Does anyone have any idea where I'm going wrong? I think it's just looking at the first Age value, running the ifelse statement then filling the whole column with the result of that as opposed to moving on to the next row.

Thanks,

Carolina

答:
I think whenever you find yourself writing nested ifelse statements you should stop and ask yourself whether there might be a better way to achieve what you're trying to do. For example, the following single function call does what you are trying to achieve, and is easier to understand and maintain:

```<code>cut(pdb$tidyish, breaks = c(33.9, 37.8, 41.2, 47.8, 56),
    labels = c("Priabonian", "Bartonian", "Lutetian", "Ypresian"))

</code>```

Body:
I'm trying to run a nested ifelse statement in R.  Here's a look at the structure of my data using the glimpse() function from the tidyverse:

Rows: 22,104
Columns: 9
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...

I'm trying to get R to look at the Age column and if the value is within a certain range, for it to put the geological age name into a new column called AgeName.  If the value is not within the range, I want it to move on to the next age range and so on and so forth.  Here's my code so far:

pbdb_tidyish$AgeName <- ifelse(56>=pbdb_tidyish$Age&&47.8<pbdb_tidyish$Age,
                               "Ypresian",
                               ifelse(47.8>=pbdb_tidyish$Age&&41.2<pbdb_tidyish$Age,
                                      "Lutetian",
                                      ifelse(41.2>=pbdb_tidyish$Age&&37.8<pbdb_tidyish$Age,
                                             "Bartonian",
                                             ifelse(37.8>=pbdb_tidyish$Age&&33.9<=pbdb_tidyish$Age,
                                                    "Priabonian",NA))))

When I run this code, it creates the new column but fills the whole column with "Priabonian" so the dataset now looks like this:

Rows: 22,104
Columns: 10
$ `Formation/Locality`    <chr> "Montmartre", "Montmartre", "Montmartre", "Fur", "Me...
$ Location                <chr> "Ile-de-France Region, France", "Ile-de-France Regio...
$ Environment             <chr> "terrestrial", "terrestrial", "terrestrial", "offsho...
$ `Palaeolongitude(N/-S)` <dbl> 47.4, 47.4, 47.4, 52.3, 46.9, 42.9, 47.5, 46.9, 46.2...
$ `Palaeolatitude(E/-W)`  <dbl> 1.6, 1.6, 1.6, 5.4, 4.8, 1.9, -5.2, 4.8, -93.6, -111...
$ TaxonomicLevel          <chr> "Order", "Order", "Order", "Order", "Order", "Order"...
$ TaxonomicName           <chr> "Upupiformes", "Upupiformes", "Upupiformes", "Trogon...
$ MinMax                  <chr> "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa", "MaxMa"...
$ Age                     <dbl> 37.2, 37.2, 37.2, 55.8, 48.6, 37.2, 48.6, 48.6, 55.8...
$ AgeName                 <chr> "Priabonian", "Priabonian", "Priabonian", "Priabonia...

Does anyone have any idea where I'm going wrong? I think it's just looking at the first Age value, running the ifelse statement then filling the whole column with the result of that as opposed to moving on to the next row.

Thanks,

Carolina

Body:
I think whenever you find yourself writing nested ifelse statements you should stop and ask yourself whether there might be a better way to achieve what you're trying to do. For example, the following single function call does what you are trying to achieve, and is easier to understand and maintain:

cut(pdb$tidyish, breaks = c(33.9, 37.8, 41.2, 47.8, 56),
    labels = c("Priabonian", "Bartonian", "Lutetian", "Ypresian"))


问:
Excluding items selectively from Sitecore's Lucene search index - works when rebuilding with IndexViewer, but not when using Sitecore's built-in tools
On a site powered by Sitecore 6.2, I need to give the user the ability to selectively exclude items from search results.

To accomplish this, I have added a checkbox field entitled "Include in Search Results", and I created a custom database crawler to check that field's value:

~\App_Config\Include\Search Indexes\Website.config:

```<code><search>
  <configuration type="Sitecore.Search.SearchConfiguration, Sitecore.Kernel" singleInstance="true">
    <indexes hint="list:AddIndex">
      <index id="website" singleInstance="true" type="Sitecore.Search.Index, Sitecore.Kernel">
        ...

        <locations hint="list:AddCrawler">
          <master type="MyProject.Lib.Search.Indexing.CustomCrawler, MyProject">
            ...
          </master>

          <!-- Similar entry for web database. -->
        </locations>
      </index>
    </indexes>
  </configuration>
</search>
</code>```

~\Lib\Search\Indexing\CustomCrawler.cs:

```<code>using Lucene.Net.Documents;
using Sitecore.Search.Crawlers;
using Sitecore.Data.Items;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    /// <summary>
    ///   Determines if the item should be included in the index.
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    protected override bool IsMatch(Item item)
    {
      if (item["include in search results"] != "1")
      {
        return false;
      }

      return base.IsMatch(item);
    }
  }
}
</code>```

What's interesting is, if I rebuild the index using the Index Viewer application, everything behaves as normal.  Items whose "Include in Search Results" checkbox is not checked will not be included in the search index.

However, when I use the search index rebuilder in the Sitecore Control Panel application or when the IndexingManager auto-updates the search index, all items are included, regardless of the state of their "Include in Search Results" checkbox.

I've also set numerous breakpoints in my custom crawler class, and the application never hits any of them when I rebuild the search index using the built-in indexer.  When I use Index Viewer, it does hit all the breakpoints I've set.

How do I get Sitecore's built-in indexing processes to respect my "Include in Search Results" checkbox?

答: Sitecore 6.2 uses the both old and newer search api, hence the differneces in how the index gets built I believe. CMS 6.5 (soon to be released) just uses the newer api - e.g., Sitecore.Search</p>

ContentLicense: CC BY-SA 3.0

Body:
On a site powered by Sitecore 6.2, I need to give the user the ability to selectively exclude items from search results.

To accomplish this, I have added a checkbox field entitled "Include in Search Results", and I created a custom database crawler to check that field's value:

~\App_Config\Include\Search Indexes\Website.config:

<search>
  <configuration type="Sitecore.Search.SearchConfiguration, Sitecore.Kernel" singleInstance="true">
    <indexes hint="list:AddIndex">
      <index id="website" singleInstance="true" type="Sitecore.Search.Index, Sitecore.Kernel">
        ...

        <locations hint="list:AddCrawler">
          <master type="MyProject.Lib.Search.Indexing.CustomCrawler, MyProject">
            ...
          </master>

        </locations>
      </index>
    </indexes>
  </configuration>
</search>

~\Lib\Search\Indexing\CustomCrawler.cs:

using Lucene.Net.Documents;
using Sitecore.Search.Crawlers;
using Sitecore.Data.Items;

namespace MyProject.Lib.Search.Indexing
{
  public class CustomCrawler : DatabaseCrawler
  {
    ///
    ///   Determines if the item should be included in the index.
    ///
    /// <param name="item"></param>
    /// <returns></returns>
    protected override bool IsMatch(Item item)
    {
      if (item["include in search results"] != "1")
      {
        return false;
      }

      return base.IsMatch(item);
    }
  }
}

What's interesting is, if I rebuild the index using the Index Viewer application, everything behaves as normal.  Items whose "Include in Search Results" checkbox is not checked will not be included in the search index.

However, when I use the search index rebuilder in the Sitecore Control Panel application or when the IndexingManager auto-updates the search index, all items are included, regardless of the state of their "Include in Search Results" checkbox.

I've also set numerous breakpoints in my custom crawler class, and the application never hits any of them when I rebuild the search index using the built-in indexer.  When I use Index Viewer, it does hit all the breakpoints I've set.

How do I get Sitecore's built-in indexing processes to respect my "Include in Search Results" checkbox?


问:
How to provide multi-level settings inside docker-compose.yml for docker based elasticsearch setup
We have docker based elasticsearch cluster for multi-nodes architecture. We provide elasticsearch config as environment variables for respective nodes in docker-compose.yml. We are not using elasticsearch.yml as config file inside docker-compose file.

We need to implement slack notification as elasticsearch watcher alerts. Using following inside elasticsearch.yml, we can enable slack notification:

```<code>xpack.notification.slack:   account:
    monitoring:
      url: <WEB-HOOK-URL>
      message_defaults:
        from: x-pack
        icon: http://example.com/images/watcher-icon.jpg
        attachment:
          fallback: "X-Pack Notification"
          color: "#36a64f"
          title: "X-Pack Notification"
          title_link: "https://www.elastic.co/guide/en/x-pack/current/index.html"
          text: "One of your watches generated this notification."
          mrkdwn_in: "pretext, text"
</code>```

The question is, this above config is compatible with elasticsearch.yml, what is its equivalent config using docker-compose.yml without using elasticsearch.yml ?

答:
These config should be given as follows:

```<code>xpack.notification.slack.account.monitoring.url: <WEB-HOOK-URL>
xpack.notification.slack.account.monitoring.message_defaults.from: x-pack
</code>```

docker-compose.yml accepts these config as env config.

Body:
We have docker based elasticsearch cluster for multi-nodes architecture. We provide elasticsearch config as environment variables for respective nodes in docker-compose.yml. We are not using elasticsearch.yml as config file inside docker-compose file.

We need to implement slack notification as elasticsearch watcher alerts. Using following inside elasticsearch.yml, we can enable slack notification:

xpack.notification.slack:   account:
    monitoring:
      url: <WEB-HOOK-URL>
      message_defaults:
        from: x-pack
        icon: http://example.com/images/watcher-icon.jpg
        attachment:
          fallback: "X-Pack Notification"
          color: "#36a64f"
          title: "X-Pack Notification"
          title_link: "https://www.elastic.co/guide/en/x-pack/current/index.html"
          text: "One of your watches generated this notification."
          mrkdwn_in: "pretext, text"

The question is, this above config is compatible with elasticsearch.yml, what is its equivalent config using docker-compose.yml without using elasticsearch.yml ?

Body:
These config should be given as follows:

xpack.notification.slack.account.monitoring.url: <WEB-HOOK-URL>
xpack.notification.slack.account.monitoring.message_defaults.from: x-pack

docker-compose.yml accepts these config as env config.


问:
My nested function isn't operating as I would like
My makeRows function isn't working as I would expect, I'm not sure if I'm going about this the right way. When I press "clear all" the prompt runs to make new rows and columns but the mouseOver class isn't being added back to the whole grid, only the bottom part.

const container = document.getElementById("container");

function makeRows(rows, cols) {
  container.style.setProperty("--grid-rows", rows);
  container.style.setProperty("--grid-cols", cols);
  for (c = 0; c < rows * cols; c++) {
    const cell = document.createElement("div");
    container.appendChild(cell).className = "grid-item mouseOver";
  }
}

window.onload = makeRows(16, 16);

const btn = document.querySelector("button");
const div = container.getElementsByTagName("div");

function reset() {
  [].forEach.call(div, function (el) {
    el.classList.remove("mouseOver");
  });
  let num = prompt("How many rows and cols?");
  makeRows(num, num);
}

btn.addEventListener("click", reset);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --grid-cols: 1;
  --grid-rows: 1;
}

#container {
  display: grid;
  grid-template-rows: repeat(var(--grid-rows), 1fr);
  grid-template-columns: repeat(var(--grid-cols), 1fr);
}

.grid-item {
  padding: 1rem;
  border: 1px solid #ddd;
  text-align: center;
}

.mouseOver {
  transition: 0s 10s;
}

.mouseOver:hover {
  background-color: aqua;
  transition: 0s;
}

#btn {
  max-width: 100%;
  width: 100%;
  padding: 1rem;
  margin-bottom: 1rem;
  margin-top: 1rem;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch-A-Sketch</title>
    <link rel="stylesheet" href="etch.css" />

    <button id="btn">Clear All</button>

```

答:
To remove all items with class grid-item use this iteration in your reset function:

```<code>function reset() {
  document.querySelectorAll('.grid-item').forEach(e => e.parentNode.removeChild(e));
  let num = prompt("How many rows and cols?");
  makeRows(num, num);
}
</code>```

This selects all elements with class grid-item and for each found div it selects its parent node and removes itself from it.

Body:
My makeRows function isn't working as I would expect, I'm not sure if I'm going about this the right way. When I press "clear all" the prompt runs to make new rows and columns but the mouseOver class isn't being added back to the whole grid, only the bottom part.

const container = document.getElementById("container");

function makeRows(rows, cols) {
  container.style.setProperty("--grid-rows", rows);
  container.style.setProperty("--grid-cols", cols);
  for (c = 0; c < rows * cols; c++) {
    const cell = document.createElement("div");
    container.appendChild(cell).className = "grid-item mouseOver";
  }
}

window.onload = makeRows(16, 16);

const btn = document.querySelector("button");
const div = container.getElementsByTagName("div");

function reset() {
  [].forEach.call(div, function (el) {
    el.classList.remove("mouseOver");
  });
  let num = prompt("How many rows and cols?");
  makeRows(num, num);
}

btn.addEventListener("click", reset);

:root {
  --grid-cols: 1;
  --grid-rows: 1;
}

#container {
  display: grid;
  grid-template-rows: repeat(var(--grid-rows), 1fr);
  grid-template-columns: repeat(var(--grid-cols), 1fr);
}

.grid-item {
  padding: 1rem;
  border: 1px solid #ddd;
  text-align: center;
}

.mouseOver {
  transition: 0s 10s;
}

.mouseOver:hover {
  background-color: aqua;
  transition: 0s;
}

#btn {
  max-width: 100%;
  width: 100%;
  padding: 1rem;
  margin-bottom: 1rem;
  margin-top: 1rem;
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Etch-A-Sketch</title>
    <link rel="stylesheet" href="etch.css" />

    <button id="btn">Clear All</button>

Body:
To remove all items with class grid-item use this iteration in your reset function:

function reset() {
  document.querySelectorAll('.grid-item').forEach(e => e.parentNode.removeChild(e));
  let num = prompt("How many rows and cols?");
  makeRows(num, num);
}

This selects all elements with class grid-item and for each found div it selects its parent node and removes itself from it.


问:
Error while reading avro file in spark code in Scala IDE
I am creating a data frame by reading avro file but getting error while reading the file in spark application in scala IDE.

```<code>package dataFrameBasics

import org.apache.spark.sql.SparkSession

object WorkingWithAvroFile {
  def main(ar : Array[String]): Unit={
    val ss= SparkSession.builder().master("local")
    .appName("Working with Avro File")
    .getOrCreate()

    val avroDF= ss.read
    .format("com.databricks.spark.avro")
    .load("C:/Spark_Files/userdata1.avro")

    avroDF.printSchema()
    avroDF.show(10)
    println("Count:"+avroDF.count())

  }

}
</code>```

On Console ,giving below error:
Exception in thread "main" java.lang.ClassNotFoundException: Failed to find data source: org.apache.spark.sql.avro.AvroFileFormat. Please find packages at http://spark.apache.org/third-party-projects.html

On Problems tab, giving below error:

spark-avro_2.11-3.2.0.jar of SparkCourseAsMavenProject build path is cross-compiled with an incompatible version of Scala (2.11.0). In case this report is mistaken, this check can be disabled in the compiler preference page.

In pom.xml,added dependency:

```<code><dependency>
        <groupId>com.databricks</groupId>
<artifactId>spark-avro_2.11</artifactId>
<version>3.2.0</version>
</dependency>
</code>```

Tried different versions of this library , but still its giving the same error.

答:
```<code>@QuickSilver-- continuing stack trace

**********
20/05/28 19:53:50 INFO FileSourceStrategy: Pruning directories with:
20/05/28 19:53:50 INFO FileSourceStrategy: Post-Scan Filters:
20/05/28 19:53:50 INFO FileSourceStrategy: Output Data Schema: struct<registration_dttm: string, id: bigint, first_name: string, last_name: string, email: string ... 11 more fields>
20/05/28 19:53:50 INFO FileSourceScanExec: Pushed Filters:
20/05/28 19:53:50 INFO deprecation: mapred.output.compress is deprecated. Instead, use mapreduce.output.fileoutputformat.compress
20/05/28 19:53:50 INFO AvroFileFormat: Compressing Avro output using the snappy codec
20/05/28 19:53:50 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter
20/05/28 19:53:50 INFO CodeGenerator: Code generated in 22.138244 ms
20/05/28 19:53:50 INFO MemoryStore: Block broadcast_5 stored as values in memory (estimated size 220.3 KB, free 350.6 MB)
20/05/28 19:53:51 INFO MemoryStore: Block broadcast_5_piece0 stored as bytes in memory (estimated size 20.6 KB, free 350.6 MB)
20/05/28 19:53:51 INFO BlockManagerInfo: Added broadcast_5_piece0 in memory on Lenovo-PC:50976 (size: 20.6 KB, free: 351.2 MB)
20/05/28 19:53:51 INFO SparkContext: Created broadcast 5 from save at WorkingWithAvroFile.scala:27
20/05/28 19:53:51 INFO FileSourceScanExec: Planning scan with bin packing, max size: 4287865 bytes, open cost is considered as scanning 4194304 bytes.
20/05/28 19:53:51 INFO SparkContext: Starting job: save at WorkingWithAvroFile.scala:27
20/05/28 19:53:51 INFO DAGScheduler: Got job 2 (save at WorkingWithAvroFile.scala:27) with 1 output partitions
20/05/28 19:53:51 INFO DAGScheduler: Final stage: ResultStage 3 (save at WorkingWithAvroFile.scala:27)
20/05/28 19:53:51 INFO DAGScheduler: Parents of final stage: List()
20/05/28 19:53:51 INFO DAGScheduler: Missing parents: List()
20/05/28 19:53:51 INFO DAGScheduler: Submitting ResultStage 3 (MapPartitionsRDD[11] at save at WorkingWithAvroFile.scala:27), which has no missing parents
20/05/28 19:53:51 INFO MemoryStore: Block broadcast_6 stored as values in memory (estimated size 135.4 KB, free 350.4 MB)
20/05/28 19:53:51 INFO MemoryStore: Block broadcast_6_piece0 stored as bytes in memory (estimated size 48.6 KB, free 350.4 MB)
20/05/28 19:53:51 INFO BlockManagerInfo: Added broadcast_6_piece0 in memory on Lenovo-PC:50976 (size: 48.6 KB, free: 351.2 MB)
20/05/28 19:53:51 INFO SparkContext: Created broadcast 6 from broadcast at DAGScheduler.scala:1163
20/05/28 19:53:51 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 3 (MapPartitionsRDD[11] at save at WorkingWithAvroFile.scala:27) (first 15 tasks are for partitions Vector(0))
20/05/28 19:53:51 INFO TaskSchedulerImpl: Adding task set 3.0 with 1 tasks
20/05/28 19:53:51 INFO TaskSetManager: Starting task 0.0 in stage 3.0 (TID 3, localhost, executor driver, partition 0, PROCESS_LOCAL, 7732 bytes)
20/05/28 19:53:51 INFO Executor: Running task 0.0 in stage 3.0 (TID 3)
20/05/28 19:53:51 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter
**20/05/28 19:53:51 ERROR Executor: Exception in task 0.0 in stage 3.0 (TID 3)
java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro**
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
20/05/28 19:53:52 WARN TaskSetManager: Lost task 0.0 in stage 3.0 (TID 3, localhost, executor driver): java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

20/05/28 19:53:52 ERROR TaskSetManager: Task 0 in stage 3.0 failed 1 times; aborting job
20/05/28 19:53:52 INFO TaskSchedulerImpl: Removed TaskSet 3.0, whose tasks have all completed, from pool
20/05/28 19:53:52 INFO TaskSchedulerImpl: Cancelling stage 3
20/05/28 19:53:52 INFO TaskSchedulerImpl: Killing all running tasks in stage 3: Stage cancelled
20/05/28 19:53:52 INFO DAGScheduler: ResultStage 3 (save at WorkingWithAvroFile.scala:27) failed in 0.880 s due to Job aborted due to stage failure: Task 0 in stage 3.0 failed 1 times, most recent failure: Lost task 0.0 in stage 3.0 (TID 3, localhost, executor driver)**: java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro**
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
20/05/28 19:53:52 INFO DAGScheduler: Job 2 failed: save at WorkingWithAvroFile.scala:27, took 0.916810 s
20/05/28 19:53:52 ERROR FileFormatWriter: Aborting job 39b6cdd2-d53c-4cb0-afa4-8d21a34d4638.
**org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 3.0 failed 1 times, most recent failure: Lost task 0.0 in stage 3.0 (TID 3, localhost, executor driver): java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro**
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:1891)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:1879)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:1878)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:52)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1878)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:927)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:927)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:927)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2112)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2061)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2050)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:738)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:167)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:170)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:83)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:81)
    at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:676)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:80)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:127)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:75)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:290)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:229)
    at dataFrameBasics.WorkingWithAvroFile$.main(WorkingWithAvroFile.scala:27)
    at dataFrameBasics.WorkingWithAvroFile.main(WorkingWithAvroFile.scala)
Caused by: java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
20/05/28 19:53:52 WARN FileUtil: Failed to delete file or dir [C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\.part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro.crc]: it still exists.
20/05/28 19:53:52 WARN FileUtil: Failed to delete file or dir [C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro]: it still exists.
Exception in thread "main" org.apache.spark.SparkException: Job aborted.
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:198)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:170)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:83)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:81)
    at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:676)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:80)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:127)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:75)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:290)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:229)
    at dataFrameBasics.WorkingWithAvroFile$.main(WorkingWithAvroFile.scala:27)
    at dataFrameBasics.WorkingWithAvroFile.main(WorkingWithAvroFile.scala)
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 3.0 failed 1 times, most recent failure: Lost task 0.0 in stage 3.0 (TID 3, localhost, executor driver): java.io.IOException: (null) entry in command string: null chmod 0644 C:\Users\santosh\Scala\Workspace\SparkCourseAsMavenProject\output_destination\avro_file\_temporary\0\_temporary\attempt_20200528195351_0003_m_000000_3\part-00000-370dab6e-2c60-4b7c-82d6-e6c3645b538c-c000.avro
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:762)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:859)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:842)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:661)
    at org.apache.hadoop.fs.ChecksumFileSystem$1.apply(ChecksumFileSystem.java:501)
    at org.apache.hadoop.fs.ChecksumFileSystem$FsOperation.run(ChecksumFileSystem.java:482)
    at org.apache.hadoop.fs.ChecksumFileSystem.setPermission(ChecksumFileSystem.java:498)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:467)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:433)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:908)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:889)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:786)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:775)
    at org.apache.spark.sql.avro.AvroOutputWriter$$anon$1.getAvroFileOutputStream(AvroOutputWriter.scala:58)
    at org.apache.avro.mapreduce.AvroKeyOutputFormat.getRecordWriter(AvroKeyOutputFormat.java:105)
    at org.apache.spark.sql.avro.AvroOutputWriter.<init>(AvroOutputWriter.scala:61)
    at org.apache.spark.sql.avro.AvroOutputWriterFactory.newInstance(AvroOutputWriterFactory.scala:43)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:123)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$15(FileFormatWriter.scala:177)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:411)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:1891)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:1879)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:1878)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:52)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1878)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:927)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:927)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:927)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2112)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2061)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2050)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:738)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:167)
    ... 21 more
</code>```

Body:
I am creating a data frame by reading avro file but getting error while reading the file in spark application in scala IDE.

package dataFrameBasics

import org.apache.spark.sql.SparkSession

object WorkingWithAvroFile {
  def main(ar : Array[String]): Unit={
    val ss= SparkSession.builder().master("local")
    .appName("Working with Avro File")
    .getOrCreate()

    val avroDF= ss.read
    .format("com.databricks.spark.avro")
    .load("C:/Spark_Files/userdata1.avro")

    avroDF.printSchema()
    avroDF.show(10)
    println("Count:"+avroDF.count())

  }

}

On Console ,giving below error:
Exception in thread "main" java.lang.ClassNotFoundException: Failed to find data source: org.apache.spark.sql.avro.AvroFileFormat. Please find packages at http://spark.apache.org/third-party-projects.html

On Problems tab, giving below error:

spark-avro_2.11-3.2.0.jar of SparkCourseAsMavenProject build path is cross-compiled with an incompatible version of Scala (2.11.0). In case this report is mistaken, this check can be disabled in the compiler preference page.

In pom.xml,added dependency:

<dependency>
        <groupId>com.databricks</groupId>
<artifactId>spark-avro_2.11</artifactId>
<version>3.2.0</version>
</dependency>

Tried different versions of this library , but still its giving the same error.


问:
Roam array of arrays by position in Python
I have this array of arrays:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

```<code>AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
</code>```

I've tried with

```<code>for i in A:
   for j in i:
      #code
</code>```

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

答:
I tried a begineer Friendly way </p>

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
AUX = []
n = 0
while n != len(A):
    AUX.append([i[n] for i in A])
    n = n + 1
</code>```

Body:
I have this array of arrays:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I've tried with

for i in A:
   for j in i:
      #code

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

Body:
I tried a begineer Friendly way

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
AUX = []
n = 0
while n != len(A):
    AUX.append([i[n] for i in A])
    n = n + 1


问:
When accessing C++ API from C via a wrapper, how do I access enum types?
I have a C program which I need to connect to a C++ API.  I asked on here and was given great advice, leading to creating a "wrapper".

So, in the API there is a type called "APIName::ReturnCode", and I wanted to create a C equivalent, so I've done the following:

In c_api.h:

```<code>#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif

typedef void* API_ReturnCode_t;
EXTERNC API_ReturnCode_t api_returncode_init();
EXTERNC void api_returncode_destroy(API_ReturnCode_t rc);

#undef EXTERNC
</code>```

in c_api.cpp:

```<code>#include "c_api.h"
#include "/path/to/api/api.h"

API_ReturnCode_t api_returncode_init() {
        return new APIName::ReturnCode;
}

void api_returncode_destroy(API_ReturnCode_t untyped_ptr) {
        APIName::ReturnCode* typed_ptr = static_cast< APIName::ReturnCode*>(untyped_ptr);
        delete typed_ptr;
}
</code>```

So I compile that into a library and include it in my main program, and I can use things like:

```<code>API_ReturnCode rc;
</code>```

to define a variable.

However, my next issue is how to define enumerated types in a similar way.  So, the api has the following definition for error codes:

```<code>namespace APIName {

    typedef enum ReturnCode_enum ReturnCode;

    enum ReturnCode_enum {
        RC_OK                               ,   // success
        RC_ERROR                            ,   // general error
        RC_NOT_AVAILABLE                    ,   // feature is not available
    };
}
</code>```

How do I recreate this in my wrapper so that I can do something like this in my code:

```<code>API_ReturnCode rc = API_RC_OK;
</code>```

Thank you.

答:
I wouldn't hide error code enums in opaque handles.

Create a new enum and convertion functions in the c_api.cpp file

c_api.h

```<code>typedef enum {
    RC_OK,
    RC_ERROR,
    RC_NOT_AVAILABLE
} ReturnCode_copy;

ReturnCode_copy some_function(...);
</code>```

c_api.cpp

```<code>static ReturnCode_copy convert(APIName::ReturnCode code) {
    switch(code) {
        //return correct ReturnCode_copy
    }
}

ReturnCode_copy some_function(...) {
    auto code = //some api function returning error code
    return convert(code);
}
</code>```

or you could be naughty and just copy the values directly in your new enum and just static_cast directly without the convert function.

Body:
I have a C program which I need to connect to a C++ API.  I asked on here and was given great advice, leading to creating a "wrapper".

So, in the API there is a type called "APIName::ReturnCode", and I wanted to create a C equivalent, so I've done the following:

In c_api.h:

#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif

typedef void* API_ReturnCode_t;
EXTERNC API_ReturnCode_t api_returncode_init();
EXTERNC void api_returncode_destroy(API_ReturnCode_t rc);

#undef EXTERNC

in c_api.cpp:

#include "c_api.h"
#include "/path/to/api/api.h"

API_ReturnCode_t api_returncode_init() {
        return new APIName::ReturnCode;
}

void api_returncode_destroy(API_ReturnCode_t untyped_ptr) {
        APIName::ReturnCode* typed_ptr = static_cast< APIName::ReturnCode*>(untyped_ptr);
        delete typed_ptr;
}

So I compile that into a library and include it in my main program, and I can use things like:

API_ReturnCode rc;

to define a variable.

However, my next issue is how to define enumerated types in a similar way.  So, the api has the following definition for error codes:

namespace APIName {

    typedef enum ReturnCode_enum ReturnCode;

    enum ReturnCode_enum {
        RC_OK                               ,   // success
        RC_ERROR                            ,   // general error
        RC_NOT_AVAILABLE                    ,   // feature is not available
    };
}

How do I recreate this in my wrapper so that I can do something like this in my code:

API_ReturnCode rc = API_RC_OK;

Thank you.

Body:
I wouldn't hide error code enums in opaque handles.

Create a new enum and convertion functions in the c_api.cpp file

c_api.h

typedef enum {
    RC_OK,
    RC_ERROR,
    RC_NOT_AVAILABLE
} ReturnCode_copy;

ReturnCode_copy some_function(...);

c_api.cpp

static ReturnCode_copy convert(APIName::ReturnCode code) {
    switch(code) {
        //return correct ReturnCode_copy
    }
}

ReturnCode_copy some_function(...) {
    auto code = //some api function returning error code
    return convert(code);
}

or you could be naughty and just copy the values directly in your new enum and just static_cast directly without the convert function.


问:
creating a dict within a dict
i'm trying to get this output:

```<code>[{'A':{'a':1, 'b':2, 'c':3}}, {'B':{'a':4, 'b':5, 'c':6}}]
</code>```

from this:

```<code>list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
</code>```

And i tried this:

```<code>list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
main_list =[]
for i in range(len(list1)):
    db1 = dict(zip(list2,list1[i]))
    for j in range(len(list3)):
        db2 = dict(zip(list3[j],db1))
        main_list.append(db2)
print(main_list)
</code>```

Any help would be really appreciated

答:
This could be done more compactly using the below list comprehension. Essentially you start by element-wise zipping list3 (your keys) against list1 which will have your sublists. Then for each of those pairs, you zip list2 (which will be the inner keys) against the current sublist, which will serve as the values of the inner dictionary.

```<code>>>> [{k: dict(zip(list2, sub))} for k,sub in zip(list3, list1)]
[{'A': {'a': 1, 'b': 2, 'c': 3}}, {'B': {'a': 4, 'b': 5, 'c': 6}}]
</code>```

For what it's worth, the issue with your current code is simply a missing ) above the line that you indicated. However, a more terse way to achieve your desired output would be using the above list comprehension.

Title: creating a dict within a dict

Body:
i'm trying to get this output:

[{'A':{'a':1, 'b':2, 'c':3}}, {'B':{'a':4, 'b':5, 'c':6}}]

from this:

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']

And i tried this:

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
main_list =[]
for i in range(len(list1)):
    db1 = dict(zip(list2,list1[i]))
    for j in range(len(list3)):
        db2 = dict(zip(list3[j],db1))
        main_list.append(db2)
print(main_list)

Any help would be really appreciated

Body:
This could be done more compactly using the below list comprehension. Essentially you start by element-wise zipping list3 (your keys) against list1 which will have your sublists. Then for each of those pairs, you zip list2 (which will be the inner keys) against the current sublist, which will serve as the values of the inner dictionary.

>>> [{k: dict(zip(list2, sub))} for k,sub in zip(list3, list1)]
[{'A': {'a': 1, 'b': 2, 'c': 3}}, {'B': {'a': 4, 'b': 5, 'c': 6}}]

For what it's worth, the issue with your current code is simply a missing ) above the line that you indicated. However, a more terse way to achieve your desired output would be using the above list comprehension.


问:
Having trouble coding a REACT onChange
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

```<code>handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}
</code>```

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

```<code>npx create-react-app test --template typescript
</code>```

with no changes to the generated configuration files.

The state was declared as

```<code>state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}
</code>```

Any ideas ?

答:
I finally found my problem (or at least how to make my sample work).

in tsconfig.json I added the following compilerOption

```<code>"suppressImplicitAnyIndexErrors": true
</code>```

this code now works

```<code>  upd = (e:React.ChangeEvent<HTMLSelectElement>) => {
    let qq = Object.assign({}, this.state);
    qq.frm[e.target.name] = e.target.value;
    this.setState(qq);
  }
</code>```

wheres previously the line

```<code>qq.frm[e.target.name] = e.target.value;
</code>```

failed saying

```<code>Parameter 'e' implicitly has an 'any' type. TS7006
</code>```

Title: Having trouble coding a REACT onChange

Body:
I'm new to REACT and I'm having trouble trying to figure out not only the onChange event props, but many of the others. Its the props being passed in thats getting me. eg

handleSubmit(e) {
  let s = this.state;
  s.data[e.target.name] = e.target.value;
  this.setState(s);
}

its given like this in pretty much all the examples I have seen (the declaration of the function) and always complains about e in the function def as being implicitly an 'any' type. If I declare it as e:any it stops complaining, but then I cant get the s.data[e.target.name] to work as it says I cant have an 'any' type as an index. I cant figure out how it's meant to be declared, or if I have a configuration issue somewhere. It works if I replace e.target.name with a string constant like 'myarray'.

The REACT app was generated with a plain

npx create-react-app test --template typescript

with no changes to the generated configuration files.

The state was declared as

state = {
  data: { fldName: 'something', anotherField: 'somethingelse'}
}

Any ideas ?

Body:
I finally found my problem (or at least how to make my sample work).

in tsconfig.json I added the following compilerOption

"suppressImplicitAnyIndexErrors": true

this code now works

  upd = (e:React.ChangeEvent<HTMLSelectElement>) => {
    let qq = Object.assign({}, this.state);
    qq.frm[e.target.name] = e.target.value;
    this.setState(qq);
  }

wheres previously the line

qq.frm[e.target.name] = e.target.value;

failed saying

Parameter 'e' implicitly has an 'any' type. TS7006


问:
Python: Verify Credit Card digits
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

```<code>def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output
</code>```

答:
It seems like there are a few fundamental errors in your code. I will list them down for you:

Boolean values start with a capital

there are no indentations after your if and else statements

Your output will always print none as your function does not return anything.

```<code>def verify(number):
    list_number=list(number)
    if list_number[0]==4 and list_number[3]==list_number[5]+1 and list_number.sum() % 4==0 and int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
        return True
     else:
        return False
input = "4094-3460-2754"
output = verify(input)
print(output)```

```

Title: Python: Verify Credit Card digits

Body:
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output

Body:
It seems like there are a few fundamental errors in your code. I will list them down for you:

Boolean values start with a capital

there are no indentations after your if and else statements

Your output will always print none as your function does not return anything.

def verify(number):
    list_number=list(number)
    if list_number[0]==4 and list_number[3]==list_number[5]+1 and list_number.sum() % 4==0 and int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
        return True
     else:
        return False
input = "4094-3460-2754"
output = verify(input)
print(output)```


问:
My symmetric difference function is returning none and I can't understand why
Trying to solve freecodecamp's symmetric difference challenge (https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/find-the-symmetric-difference), I wrote the following function:

```<code>def symdiff(*args):
    dump = [x for x in args[0] if x in args[1]]
    result = [x for x in args[0] + args[1] if x not in dump]
    if len(args) == 2:
        return result
    else:
        symdiff(result, *args[2:])
var = symdiff([1, 2, 3], [3, 2, 0], [7, 2, 6])
print(var)
</code>```

The value of var turns out to be None. Why is that? I expected it to be [7, 2, 6, 1, 0]. I entered a print(result) just before return result and it printed the correct answer.

答:
In your else block, you need to return symdiff.

```<code>def symdiff(*args):
    dump = [x for x in args[0] if x in args[1]]
    result = [x for x in args[0] + args[1] if x not in dump]
    if len(args) == 2:
        return result
    else:
        return symdiff(result, *args[2:])
var = symdiff([1, 2, 3], [3, 2, 0], [7, 2, 6])
print(var)
</code>```

The above code should work.

Body:
Trying to solve freecodecamp's symmetric difference challenge (https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/find-the-symmetric-difference), I wrote the following function:

def symdiff(*args):
    dump = [x for x in args[0] if x in args[1]]
    result = [x for x in args[0] + args[1] if x not in dump]
    if len(args) == 2:
        return result
    else:
        symdiff(result, *args[2:])
var = symdiff([1, 2, 3], [3, 2, 0], [7, 2, 6])
print(var)

The value of var turns out to be None. Why is that? I expected it to be [7, 2, 6, 1, 0]. I entered a print(result) just before return result and it printed the correct answer.

Body:
In your else block, you need to return symdiff.

def symdiff(*args):
    dump = [x for x in args[0] if x in args[1]]
    result = [x for x in args[0] + args[1] if x not in dump]
    if len(args) == 2:
        return result
    else:
        return symdiff(result, *args[2:])
var = symdiff([1, 2, 3], [3, 2, 0], [7, 2, 6])
print(var)

The above code should work.


问:
Stripe: attach invoice pdf to email
I'm currently trying to send emails with attached pdf invoices to customers with nodejs but I can't figure out how to get pdf file from invoice_pdf field.

I tried fs, got and request but I am not able to get the file content ever.

for example I tried:

```<code>let file = await got(invoice.invoice_pdf)
let fileContent = Buffer.from(file['body'])
...
// mail conf
attachments: [{
    'type': 'application/pdf',
    'name': invoice.number + '.pdf',
    'content': fileContent.toString('base64'),
}],
</code>```

There is a pdf attached to the received email but it is a blank page with no content.

Any help?

Thanks a lot

EDIT: doc of Mandrill's attachments

答: Did you try using the NPM Package pdfreader or pdf2json these packages will help you read the content firstly then you can store the data into a variable then pass it into the attachments.

Title: Stripe: attach invoice pdf to email

Body:
I'm currently trying to send emails with attached pdf invoices to customers with nodejs but I can't figure out how to get pdf file from invoice_pdf field.

I tried fs, got and request but I am not able to get the file content ever.

for example I tried:

let file = await got(invoice.invoice_pdf)
let fileContent = Buffer.from(file['body'])
...
// mail conf
attachments: [{
    'type': 'application/pdf',
    'name': invoice.number + '.pdf',
    'content': fileContent.toString('base64'),
}],

There is a pdf attached to the received email but it is a blank page with no content.

Any help?

Thanks a lot

EDIT: doc of Mandrill's attachments


问:
How to highlight the differences between two versions of a text in .NET web app?
I have been supporting a web application at work for our Call Center unit for about 2 years now. The app is written in ASP.NET 3.5 with SQL server 2005 database. I’ve been asked to expand the call detail section to allow agents to edit the current call note with the ability to revert back to its previous version. Now, that’s all cool but now the manager wants to be able to click on any particular note and see all edits with changes highlighted in yellow (and if something was deleted, he wants to SEE the deleted text crossed out). Actually, what I need is very similar to how Stackoverflow handles edits on their questions.  I’ve been thinking about how to go about this and after doing research and Google-ing of course, I am still unsure which route to take. I am fairly new to .NET development. Any ideas on the best technique for highlighting the changes in UI? I am afraid I am going to have to store a copy of the entire note each time they make a change because the manager wants to be able to easily review notes and revert back to ANY version (not just the most recent one) before sending the monthly call report off to our VIP customers. Since this department OFTEN changes their mind on things,  I want to make sure the new functionality is scalable and easy to maintain. Any ideas would be greatly appreciated. I am really just looking for someone to point me in the right direction; maybe there are some tools out there that can be useful, recommended keywords in Google lookup, etc. </p>

答:
Some tools for doing the diff for you can be found at Any decent text diff/merge engine for .NET?.

This would entail storing every version like you say. This should allow you to implement it similarly to SO. I seem to recall reading or hearing Jeff mention it, but wasn't able to find it, likely in one of the SO podcasts.

OwnerDisplayName: Dinci

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Dinci Garrone

OwnerDisplayName: Jeremy Wilde


问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
As per the expression, it matches any string with either 6 digits or 4 digits.

However since you are using a (.*) the expression will match any string with a minimum of 4 digits.

To match a number with 6 or 4 digits you can use:

```<code>/^\d{4}(\d{2})?$/
</code>```

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?

Body:
As per the expression, it matches any string with either 6 digits or 4 digits.

However since you are using a (.*) the expression will match any string with a minimum of 4 digits.

To match a number with 6 or 4 digits you can use:

/^\d{4}(\d{2})?$/


问:
I only want Regex to only search spelling mistakes - how to exclude correct spellings?
My goal is to identify a words/phrases which has been misspelt.

I want to exclude correct instances from my search.  The word I want to identify all misspellings of is "Whats'App" (with and without the apostrophe).

I want to identify instances when a letter has been swapped out for a number.

Here is my regex now which works well for all instances including correct spellings. I want the code to exclude the following two words; whatsapp and whats'app.

I am running this in Elastic.

```<code>wh[a4]t[s5]’?[a4]pp
</code>```

答:
Thank you all for your help. The solution to this question was to exclude the correct instances by using @&~(abc.+). I discovered the answer on eslatics site.

Here is the query that now works;

wh[a4]t[s5]’?[a4]p+@&~(whats’?ap+)
```

Unfortunately, I have some unexpected results where some misspellings are not identified.  It must relate to a different problem in this query that I will post as a separate question.

Thanks,
Sean

Body:
My goal is to identify a words/phrases which has been misspelt.

I want to exclude correct instances from my search.  The word I want to identify all misspellings of is "Whats'App" (with and without the apostrophe).

I want to identify instances when a letter has been swapped out for a number.

Here is my regex now which works well for all instances including correct spellings. I want the code to exclude the following two words; whatsapp and whats'app.

I am running this in Elastic.

wh[a4]t[s5]’?[a4]pp

Body:
Thank you all for your help. The solution to this question was to exclude the correct instances by using @&~(abc.+). I discovered the answer on eslatics site.

Here is the query that now works;

wh[a4]t[s5]’?[a4]p+@&~(whats’?ap+)

Unfortunately, I have some unexpected results where some misspellings are not identified.  It must relate to a different problem in this query that I will post as a separate question.

Thanks,
Sean


问:
Explain this snippet which finds the maximum of two integers without using if-else or any other comparison operator?
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

```<code>int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}
</code>```

答:
No logical operators, no libs (JS)

```<code>function (x, y) {
    let z = (x - y) ** 2;
    z = z ** .5;
    return (x + y + z) / 2
}
</code>```

Body:
Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow

EXAMPLE
Input: 5, 10
Output: 10

I found this solution, can someone help me understand these lines of code

int getMax(int a, int b) {
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    return max;
}

Body:
No logical operators, no libs (JS)

function (x, y) {
    let z = (x - y) ** 2;
    z = z ** .5;
    return (x + y + z) / 2
}


问:
Cross-Thread Exception - Environment Only
A control can only be accessed by the thread that created it - this much I know.

I have a DataGridView with a
DataSource based on a BindingList<>.

I have a worker thread (non-GUI)
that runs some fancy
calculations/comparisons/etc and
then adds/edits an object to/in the BindingList<>.

On a timer, the GUI thread refreshes itself against the BindingList<>.

This code works flawlessly - as long as I'm not running in the environment.  In the environment when the .Add() method is called on the BindingList<> I get this handy little error:

```<code>An Exception has occurred
EXCEPTION : Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
IN METHOD : get_Handle
AT LINE   : 0
CLASS     : System.Windows.Forms.Control
</code>```

Notice how the name of the control being violated is blank...  I would think that if the problem was with updating the BindingList<> it wouldn't matter if I was running in the environment or not.  Notwithstanding, that's what I'm seeing.  Moreover, the .Add() completes successfully even though the exception is thrown!!

Obviously, it's not a big deal in my production environment (yet?) since it only happens in Studio; and yes I could Invoke the GUI thread to perform the Add, or store the adds in a place for the GUI thread to retrieve them later...  I'm not looking for a work-around but more so am interested in the answer to this question:

Why does the error only appear in studio?

答:
The error only appears in VS because it's a kind of diagnostic message trying to tell you that you have a bug. And in production those additional checks are disabled by default. So the bug is always there, but you're only notified while debugging.

I'm not too familiar with multithreaded WinForms programming, but I assume that since you call add on that binding list in another thread the change notifications happen in that other thread too, and since you bound a control it will change it's state during such a notification. Which means that the control is accessed from a wrong thread, which is a bug.

Body:
A control can only be accessed by the thread that created it - this much I know.

I have a DataGridView with a
DataSource based on a BindingList<>.

I have a worker thread (non-GUI)
that runs some fancy
calculations/comparisons/etc and
then adds/edits an object to/in the BindingList<>.

On a timer, the GUI thread refreshes itself against the BindingList<>.

This code works flawlessly - as long as I'm not running in the environment.  In the environment when the .Add() method is called on the BindingList<> I get this handy little error:

An Exception has occurred
EXCEPTION : Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
IN METHOD : get_Handle
AT LINE   : 0
CLASS     : System.Windows.Forms.Control

Notice how the name of the control being violated is blank...  I would think that if the problem was with updating the BindingList<> it wouldn't matter if I was running in the environment or not.  Notwithstanding, that's what I'm seeing.  Moreover, the .Add() completes successfully even though the exception is thrown!!

Obviously, it's not a big deal in my production environment (yet?) since it only happens in Studio; and yes I could Invoke the GUI thread to perform the Add, or store the adds in a place for the GUI thread to retrieve them later...  I'm not looking for a work-around but more so am interested in the answer to this question:

Why does the error only appear in studio?


问:
How to calculate confusion matrix for object detection/recognition?
I have solved one image recognition problem of total 32 categories. I got the result and calculated the average precision of it. I need to draw the confusion matrix.</p>

答:
I am working on YOLOv2 and have created a confusion matrix for detection network. Hope this helps  :)

testObjects are true labels, predLabels are predicted labels

TestData is imageDatastore() of imdsTest

```<code>testObjects = testData.UnderlyingDatastores{1, 1}.Files  ; %'C:\Users\admin\Desktop\Img_Data\Flower1\Flower101.jpg'
testObjects = erase(testObjects,fullfile(pwd,imgFolderName)); %'\Flower1\Flower101.jpg'
testObjects = categorical(extractBetween(testObjects, "\","\")); % Flower1 - array

predLabels = zeros(2,1);
predLabels = categorical(predLabels); % Prelocation
for iPred = 1:length(testObjects)
    [~, idxx] = max(cell2mat(detectionResults.Scores(iPred))); % max of all the bounding box scores
    multiLabels = detectionResults.Labels{iPred,1};  % find label of max score
    if isempty(multiLabels) == 1
        predLabels(iPred,1) = {'NaN'};
        predLabels(iPred,1) = standardizeMissing(predLabels(iPred,1),{'NaN'});
    else
       predLabels(iPred,1) = (multiLabels(idxx,1));
    end
end
predLabels = removecats(predLabels);

plotconfusion (testObjects,predLabels) %confusionchart(testAsts,predLabels)
</code>```

Body:
I am working on YOLOv2 and have created a confusion matrix for detection network. Hope this helps  :)

testObjects are true labels, predLabels are predicted labels

TestData is imageDatastore() of imdsTest

testObjects = testData.UnderlyingDatastores{1, 1}.Files  ; %'C:\Users\admin\Desktop\Img_Data\Flower1\Flower101.jpg'
testObjects = erase(testObjects,fullfile(pwd,imgFolderName)); %'\Flower1\Flower101.jpg'
testObjects = categorical(extractBetween(testObjects, "\","\")); % Flower1 - array

predLabels = zeros(2,1);
predLabels = categorical(predLabels); % Prelocation
for iPred = 1:length(testObjects)
    [~, idxx] = max(cell2mat(detectionResults.Scores(iPred))); % max of all the bounding box scores
    multiLabels = detectionResults.Labels{iPred,1};  % find label of max score
    if isempty(multiLabels) == 1
        predLabels(iPred,1) = {'NaN'};
        predLabels(iPred,1) = standardizeMissing(predLabels(iPred,1),{'NaN'});
    else
       predLabels(iPred,1) = (multiLabels(idxx,1));
    end
end
predLabels = removecats(predLabels);

plotconfusion (testObjects,predLabels) %confusionchart(testAsts,predLabels)


问:
React useEffect hook is not working with rails
I am using the react hooks but in that useEffect is not working. As in the console start and end are not printing. Also I am using react in rails project.

```<code>import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const DetailInterview = () => {
  const [participants, setparticipants] = useState([])
  const [interviews, setinterviews] = useState([])

  async function fetchParticipantsList() {
    fetch('/api/v1/participants').
      then((response) => response.json()).
      then((participants) => setparticipants({ participants }));
  };

  async function fetchInterviewsList() {
    const { match: { params: { id } } } = this.props;
    fetch(`/api/v1/interviews/${id}`).
      then((response) => response.json()).
      then((interviews) => setinterviews({ interviews }));

    console.log("sa",interviews)
  };

  useEffect(() => {
    console.log('start')
    fetchParticipantsList();
    fetchInterviewsList();
    console.log('end')
  });

  const interviewslist = JSON.stringify(interviews)

  console.log('interviewlist: ',interviewslist)

  return (
    <div>
      <h3>All participants</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Description</th>
            <th>Is Published</th>
          </tr>
        </thead>
        <tbody>
          {
            interviewslist.map((interview) => {
              return (
                <tr key={interview.id}>
                  <td>{interview.id}</td>
                  <td>{interview.interview_id}</td>
                  <td>
                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}
                  </td>
                  <td>{interview.created_at}</td>
                  <td>'Yes No'</td>
                </tr>
              )
            })
          }
        </tbody>
      </table>
    </div>
  );
}

export default DetailInterview;
</code>```

Can anybody please help me why this is not working. Because of which I think it is showing
this error:

Uncaught TypeError: interviewslist.map is not a function.

Also this console is printing twice: console.log('interviewlist: ',interviewslist)

答:
You are trying map a string, JSON.stringify converts a JavaScript object or value to a JSON string.

Try use JSON.parse in this case.

Body:
I am using the react hooks but in that useEffect is not working. As in the console start and end are not printing. Also I am using react in rails project.

import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';

const DetailInterview = () => {
  const [participants, setparticipants] = useState([])
  const [interviews, setinterviews] = useState([])

  async function fetchParticipantsList() {
    fetch('/api/v1/participants').
      then((response) => response.json()).
      then((participants) => setparticipants({ participants }));
  };

  async function fetchInterviewsList() {
    const { match: { params: { id } } } = this.props;
    fetch(`/api/v1/interviews/${id}`).
      then((response) => response.json()).
      then((interviews) => setinterviews({ interviews }));

    console.log("sa",interviews)
  };

  useEffect(() => {
    console.log('start')
    fetchParticipantsList();
    fetchInterviewsList();
    console.log('end')
  });

  const interviewslist = JSON.stringify(interviews)

  console.log('interviewlist: ',interviewslist)

  return (

All participants

            ID
            Title
            Description
            Is Published

          {
            interviewslist.map((interview) => {
              return (

                  {interview.id}
                  {interview.interview_id}

                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}

                  {interview.created_at}
                  'Yes No'

              )
            })
          }

  );
}

export default DetailInterview;

Can anybody please help me why this is not working. Because of which I think it is showing
this error:

Uncaught TypeError: interviewslist.map is not a function.

Also this console is printing twice: console.log('interviewlist: ',interviewslist)