问:
Moving labels in ggplot graph so that they match the x-axis tick marks
I am working with a bar graph, and am trying to adjust the labels (location, in my dataset) so that they line up with the x-axis tick marks. The data is below:

```<code>data <- data.frame(location=c('Allen',
                              'Allen',
                              'Anderson',
                              'Atchison',
                              'Barber',
                              'Barber',
                              'Bourbon',
                              'Brown',
                              'Brown',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Cherokee',
                              'Cherokee',
                              'Cheyenne',
                              'Comanche',
                              'Cowley',
                              'Crawford',
                              'Crawford',
                              'Crawford',
                              'Decatur',
                              'Dickinson',
                              'Dickinson',
                              'Dickinson',
                              'Doniphan',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Edwards',
                              'Edwards',
                              'Ellis',
                              'Ellis',
                              'Finney',
                              'Finney',
                              'Finney',
                              'Ford',
                              'Geary',
                              'Gove',
                              'Graham',
                              'Grant',
                              'Gray',
                              'Harper',
                              'Harper',
                              'Harvey',
                              'Harvey',
                              'Harvey',
                              'Jackson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jewell',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Labette',
                              'Labette',
                              'Labette',
                              'Lane',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Linn',
                              'Lyon',
                              'Marion',
                              'Marion',
                              'Marshall',
                              'Marshall',
                              'Meade',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Morris',
                              'Nemaha',
                              'Neosho',
                              'Ness',
                              'Osage',
                              'Osage',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Republic',
                              'Rice',
                              'Riley',
                              'Riley',
                              'Riley',
                              'Rooks',
                              'Rush',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Sheridan',
                              'Smith',
                              'Stanton',
                              'Sumner',
                              'Sumner',
                              'Trego',
                              'Wabaunsee',
                              'Wilson',
                              'Wilson',
                              'Woodson',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte'),
                   vehicles = c(43472,
                                51429,
                                53577,
                                54936,
                                56705,
                                63875,
                                46172,
                                54135,
                                53690,
                                72173,
                                93634,
                                83378,
                                72500,
                                46458,
                                53843,
                                55352,
                                58173,
                                78182,
                                56406,
                                45114,
                                74543,
                                43646,
                                68798,
                                57917,
                                46219,
                                62188,
                                53445,
                                79500,
                                86150,
                                63523,
                                55598,
                                58438,
                                65673,
                                71417,
                                73958,
                                117703,
                                36750,
                                52349,
                                50906,
                                56667,
                                67292,
                                65000,
                                67381,
                                54044,
                                49648,
                                55774,
                                78272,
                                67056,
                                69962,
                                73036,
                                74688,
                                63177,
                                66189,
                                51932,
                                67266,
                                27860,
                                72358,
                                106582,
                                72923,
                                71667,
                                115741,
                                97734,
                                113750,
                                98359,
                                0,
                                49193,
                                48553,
                                45313,
                                64805,
                                76667,
                                90597,
                                95944,
                                88431,
                                74613,
                                75625,
                                54848,
                                74750,
                                65057,
                                63824,
                                54250,
                                55651,
                                61797,
                                90083,
                                96450,
                                91549,
                                79722,
                                74543,
                                66111,
                                55865,
                                43750,
                                46310,
                                62411,
                                58750,
                                52838,
                                62813,
                                60972,
                                63125,
                                64495,
                                54492,
                                82574,
                                68850,
                                57557,
                                41100,
                                70313,
                                43152,
                                62482,
                                59155,
                                47713,
                                46613,
                                66583,
                                42853,
                                65773,
                                0,
                                54531,
                                52750,
                                25455,
                                28889,
                                55682,
                                52926,
                                43646,
                                26857,
                                34224,
                                81167,
                                81917,
                                79556,
                                86826,
                                80326,
                                43333,
                                84325,
                                103333,
                                78279,
                                97940,
                                71085,
                                91146,
                                98008,
                                83750,
                                44554,
                                78065,
                                75500,
                                84615,
                                76004,
                                88480,
                                80392,
                                65472,
                                77957,
                                90848,
                                59342,
                                49821,
                                50703,
                                60147,
                                73897,
                                57017,
                                68966,
                                48750,
                                45924,
                                50568,
                                0,
                                22399,
                                30625,
                                29676,
                                36250,
                                0,
                                0,
                                66806,
                                41714,
                                0,
                                0,
                                106574,
                                110909,
                                73487,
                                97083))
</code>```

Here is the code that I am using to generate my graph:

```<code>library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  theme(axis.text.x = element_text(angle = 90)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")
</code>```

As can be seen below, the labels do not match up with the tick marks. I need to shift them slightly to the left. How can I fix this?

答:
If you set hjust and vjust inside theme(axis.text.x = element_text(...)) you can tweak the positions however you like:

library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.3, hjust = 1)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")
```

Body:
I am working with a bar graph, and am trying to adjust the labels (location, in my dataset) so that they line up with the x-axis tick marks. The data is below:

data <- data.frame(location=c('Allen',
                              'Allen',
                              'Anderson',
                              'Atchison',
                              'Barber',
                              'Barber',
                              'Bourbon',
                              'Brown',
                              'Brown',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Butler',
                              'Cherokee',
                              'Cherokee',
                              'Cheyenne',
                              'Comanche',
                              'Cowley',
                              'Crawford',
                              'Crawford',
                              'Crawford',
                              'Decatur',
                              'Dickinson',
                              'Dickinson',
                              'Dickinson',
                              'Doniphan',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Douglas',
                              'Edwards',
                              'Edwards',
                              'Ellis',
                              'Ellis',
                              'Finney',
                              'Finney',
                              'Finney',
                              'Ford',
                              'Geary',
                              'Gove',
                              'Graham',
                              'Grant',
                              'Gray',
                              'Harper',
                              'Harper',
                              'Harvey',
                              'Harvey',
                              'Harvey',
                              'Jackson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jefferson',
                              'Jewell',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Johnson',
                              'Labette',
                              'Labette',
                              'Labette',
                              'Lane',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Leavenworth',
                              'Linn',
                              'Lyon',
                              'Marion',
                              'Marion',
                              'Marshall',
                              'Marshall',
                              'Meade',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Miami',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Montgomery',
                              'Morris',
                              'Nemaha',
                              'Neosho',
                              'Ness',
                              'Osage',
                              'Osage',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Pottawatomie',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Reno',
                              'Republic',
                              'Rice',
                              'Riley',
                              'Riley',
                              'Riley',
                              'Rooks',
                              'Rush',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Sedgwick',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Shawnee',
                              'Sheridan',
                              'Smith',
                              'Stanton',
                              'Sumner',
                              'Sumner',
                              'Trego',
                              'Wabaunsee',
                              'Wilson',
                              'Wilson',
                              'Woodson',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte',
                              'Wyandotte'),
                   vehicles = c(43472,
                                51429,
                                53577,
                                54936,
                                56705,
                                63875,
                                46172,
                                54135,
                                53690,
                                72173,
                                93634,
                                83378,
                                72500,
                                46458,
                                53843,
                                55352,
                                58173,
                                78182,
                                56406,
                                45114,
                                74543,
                                43646,
                                68798,
                                57917,
                                46219,
                                62188,
                                53445,
                                79500,
                                86150,
                                63523,
                                55598,
                                58438,
                                65673,
                                71417,
                                73958,
                                117703,
                                36750,
                                52349,
                                50906,
                                56667,
                                67292,
                                65000,
                                67381,
                                54044,
                                49648,
                                55774,
                                78272,
                                67056,
                                69962,
                                73036,
                                74688,
                                63177,
                                66189,
                                51932,
                                67266,
                                27860,
                                72358,
                                106582,
                                72923,
                                71667,
                                115741,
                                97734,
                                113750,
                                98359,
                                0,
                                49193,
                                48553,
                                45313,
                                64805,
                                76667,
                                90597,
                                95944,
                                88431,
                                74613,
                                75625,
                                54848,
                                74750,
                                65057,
                                63824,
                                54250,
                                55651,
                                61797,
                                90083,
                                96450,
                                91549,
                                79722,
                                74543,
                                66111,
                                55865,
                                43750,
                                46310,
                                62411,
                                58750,
                                52838,
                                62813,
                                60972,
                                63125,
                                64495,
                                54492,
                                82574,
                                68850,
                                57557,
                                41100,
                                70313,
                                43152,
                                62482,
                                59155,
                                47713,
                                46613,
                                66583,
                                42853,
                                65773,
                                0,
                                54531,
                                52750,
                                25455,
                                28889,
                                55682,
                                52926,
                                43646,
                                26857,
                                34224,
                                81167,
                                81917,
                                79556,
                                86826,
                                80326,
                                43333,
                                84325,
                                103333,
                                78279,
                                97940,
                                71085,
                                91146,
                                98008,
                                83750,
                                44554,
                                78065,
                                75500,
                                84615,
                                76004,
                                88480,
                                80392,
                                65472,
                                77957,
                                90848,
                                59342,
                                49821,
                                50703,
                                60147,
                                73897,
                                57017,
                                68966,
                                48750,
                                45924,
                                50568,
                                0,
                                22399,
                                30625,
                                29676,
                                36250,
                                0,
                                0,
                                66806,
                                41714,
                                0,
                                0,
                                106574,
                                110909,
                                73487,
                                97083))

Here is the code that I am using to generate my graph:

library(ggplot2)

ggplot(data = data, aes(x = location, y = vehicles)) +
  geom_bar(stat = 'identity', fill = 'steelblue') +
  theme(axis.text.x = element_text(angle = 90)) +
  xlab("Location") +
  ylab("Vehicles")+
  ggtitle("Vehicles per location")

As can be seen below, the labels do not match up with the tick marks. I need to shift them slightly to the left. How can I fix this?


来源: stackexchange

问:
Button Opens All Buttons
I created a dropdown button but when I replicate this and use it multiple times it opens all of the buttons on the page. I thought wrapping the button in class="dropdown" was the way to make sure this doesn't happen.

Can someone please tell me what is wrong with this?

```<code>    <li class="text-middle">
          <div id="dropdown_m" class="dropdown">
            <button class="button button-sm button-secondary button-nina dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown Items </button>
           <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
    <a class="dropdown-item" href="#">Option 1</a>
    <a class="dropdown-item" href="#">Option 2</a>
    <a class="dropdown-item" href="#">Option 3</a>
    <a class="dropdown-item" href="#">Option 4</a>
    <a class="dropdown-item" href="#">Option 5</a>
                     </div>
                    </div>
                  </li>
</code>```

答:
Each
 has to contain only one Dropdown. If you put them in one single
 browsers will execute them all in that div. Try to create a div for each Dropdown.

ContentLicense: CC BY-SA 4.0

Title: Button Opens All Buttons

Body:
I created a dropdown button but when I replicate this and use it multiple times it opens all of the buttons on the page. I thought wrapping the button in class="dropdown" was the way to make sure this doesn't happen.

Can someone please tell me what is wrong with this?

            <button class="button button-sm button-secondary button-nina dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown Items </button>

    Option 1
    Option 2
    Option 3
    Option 4
    Option 5

Body: Each <div> has to contain only one Dropdown. If you put them in one single <div> browsers will execute them all in that div. Try to create a div for each Dropdown.


问:
How to fix memory leak in Next JS?
I encountered an error while fetching the API that says:

```<code>Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it
indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous
tasks in a useEffect cleanup function.
</code>```

How can I cancel all subscriptions and asynchronous tasks in a useEffect function?

My Header.js file

```<code>const getData = async () => {
try {
  const res = await fetch(
    `https://ip-geolocation-ipwhois-io.p.rapidapi.com/json/?ip=${ipAddress}`,
    {
      method: "GET",
      headers: {
        "x-rapidapi-host": "ip-geolocation-ipwhois-io.p.rapidapi.com",
      },
    }
  );
  const data = await res.json();
  setResults(data);
  return results;
} catch (error) {
  console.log("Error");
   }
};

useEffect(() => {
let abortController = new AbortController();
getData();
return () => {
  abortController.abort();
     };
   // eslint-disable-next-line react-hooks/exhaustive-deps
 }, [results]);
</code>```

答:
You need to provide abort controller signal to fetcher function so that cleanup function in your hooks now which call to cancel.

Please refer to example in MDN

https://developer.mozilla.org/en-US/docs/Web/API/AbortController#examples

Title: How to fix memory leak in Next JS?

Body:
I encountered an error while fetching the API that says:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it
indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous
tasks in a useEffect cleanup function.

How can I cancel all subscriptions and asynchronous tasks in a useEffect function?

My Header.js file

const getData = async () => {
try {
  const res = await fetch(
    `https://ip-geolocation-ipwhois-io.p.rapidapi.com/json/?ip=${ipAddress}`,
    {
      method: "GET",
      headers: {
        "x-rapidapi-host": "ip-geolocation-ipwhois-io.p.rapidapi.com",
      },
    }
  );
  const data = await res.json();
  setResults(data);
  return results;
} catch (error) {
  console.log("Error");
   }
};

useEffect(() => {
let abortController = new AbortController();
getData();
return () => {
  abortController.abort();
     };
   // eslint-disable-next-line react-hooks/exhaustive-deps
 }, [results]);


问:
How to return the appropriate results with JSON in order to populate cascading drop down lists?
I'm trying to populate a second drop down list (which contains counties) depending on what is selected on the first drop down list (which contains countries).

I have a controller action called GetCounties:

```<code>  public JsonResult GetCounties(string id)
    {
        DBEntities dc = new DBEntities();
        JsonResult result = new JsonResult();
        var filteredDivisions = from div in dc.Divisions
                                where div.CountryID == 1 //id
                                select div;
        result.Data = filteredDivisions.ToList();
        return Json(result.Data, JsonRequestBehavior.AllowGet);

        //         return Json(new[] {
        //    new { Id = filteredDivisions.ToArray()[0].DivisionID, Value = filteredDivisions.ToArray()[0].DivisionName },
        //    new { Id = 2, Value = "value 2" },
        //    new { Id = 3, Value = "value 3" },
        //}, JsonRequestBehavior.AllowGet);
    }
</code>```

Notice the section that is commented out. That works fine for me, (I get the first value from the divisions list, and the other two called "value 2" and "value 3". I used that there to test the callback, but it was the only thing that gave me results. Using:

```<code> return Json(result.Data, JsonRequestBehavior.AllowGet);
</code>```

doesn't achieve anything on the view side. When debugging, all the right values are there, but they don't come up on the view side's drop down list. As I said, the only results I get is by using the code that is commented out (the hardcoded values, which of course are not good enough). I tried to use for loops to iterate through the list in order to populate the array, but nothing works, I get errors like anonymous type is read only so I cannot set it again.

This is my jquery code:

```<code>  $(function () {
            $.getJSON('/Entity/GetCounties', function (result) {
                var ddl = $('#DivisionsList');
                ddl.empty();
                $(result).each(function () {
                    $(document.createElement('option'))
            .attr('value', this.Id)
            .text(this.Value)
            .appendTo(ddl);
                });
            });
        });
</code>```

The divisionslist is of course the dropdown with all the counties, which by using the non-commented return statement above, just returns unchanged, i.e. containing ALL of its values, and not just the ones that should come up depending on the selected country.
so please HOW CAN I POPULATE AN ARRAY WITH THE FILTERED RESULTS SO THAT I CAN RETURN IT TO THE VIEW USING JSON? I want to use THIS code that I have posted, as it was THE ONLY ONE that ever worked. I just need to swap the hardcoded values with the right ones. that's where i'm having trouble.

please help me.

答:
I solved it myself. What i did is this:

```<code>   public JsonResult GetDivisions(int id)
    {
        ASNEntities dc = new ASNEntities();
        JsonResult result = new JsonResult();
        var filteredDivisions = from div in dc.Divisions
                                where div.CountryID == id
                                select div;

        List<object> listToReturn = new List<object>();

        for (int i = 0; i < filteredDivisions.Count(); i++)
        {
            Object[] obj = new[]{
             new { Id = filteredDivisions.ToArray()[i].DivisionID, Value = filteredDivisions.ToArray()[i].DivisionName },
        };

           listToReturn.Add(obj[0]);
        }

        return Json(listToReturn.ToArray(), JsonRequestBehavior.AllowGet);

        //return Json(new[] {
        //    new { Id = filteredDivisions.ToArray()[0].DivisionID, Value = filteredDivisions.ToArray()[0].DivisionName },
        //    new { Id = 2, Value = "value 2" },
        //    new { Id = 3, Value = "value 3" },
        //}, JsonRequestBehavior.AllowGet);

    }
</code>```

and it works great.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to populate a second drop down list (which contains counties) depending on what is selected on the first drop down list (which contains countries).

I have a controller action called GetCounties:

  public JsonResult GetCounties(string id)
    {
        DBEntities dc = new DBEntities();
        JsonResult result = new JsonResult();
        var filteredDivisions = from div in dc.Divisions
                                where div.CountryID == 1 //id
                                select div;
        result.Data = filteredDivisions.ToList();
        return Json(result.Data, JsonRequestBehavior.AllowGet);

        //         return Json(new[] {
        //    new { Id = filteredDivisions.ToArray()[0].DivisionID, Value = filteredDivisions.ToArray()[0].DivisionName },
        //    new { Id = 2, Value = "value 2" },
        //    new { Id = 3, Value = "value 3" },
        //}, JsonRequestBehavior.AllowGet);
    }

Notice the section that is commented out. That works fine for me, (I get the first value from the divisions list, and the other two called "value 2" and "value 3". I used that there to test the callback, but it was the only thing that gave me results. Using:

 return Json(result.Data, JsonRequestBehavior.AllowGet);

doesn't achieve anything on the view side. When debugging, all the right values are there, but they don't come up on the view side's drop down list. As I said, the only results I get is by using the code that is commented out (the hardcoded values, which of course are not good enough). I tried to use for loops to iterate through the list in order to populate the array, but nothing works, I get errors like anonymous type is read only so I cannot set it again.

This is my jquery code:

  $(function () {
            $.getJSON('/Entity/GetCounties', function (result) {
                var ddl = $('#DivisionsList');
                ddl.empty();
                $(result).each(function () {
                    $(document.createElement('option'))
            .attr('value', this.Id)
            .text(this.Value)
            .appendTo(ddl);
                });
            });
        });

The divisionslist is of course the dropdown with all the counties, which by using the non-commented return statement above, just returns unchanged, i.e. containing ALL of its values, and not just the ones that should come up depending on the selected country.
so please HOW CAN I POPULATE AN ARRAY WITH THE FILTERED RESULTS SO THAT I CAN RETURN IT TO THE VIEW USING JSON? I want to use THIS code that I have posted, as it was THE ONLY ONE that ever worked. I just need to swap the hardcoded values with the right ones. that's where i'm having trouble.

please help me.

Body:
I solved it myself. What i did is this:

   public JsonResult GetDivisions(int id)
    {
        ASNEntities dc = new ASNEntities();
        JsonResult result = new JsonResult();
        var filteredDivisions = from div in dc.Divisions
                                where div.CountryID == id
                                select div;

        List<object> listToReturn = new List<object>();

        for (int i = 0; i < filteredDivisions.Count(); i++)
        {
            Object[] obj = new[]{
             new { Id = filteredDivisions.ToArray()[i].DivisionID, Value = filteredDivisions.ToArray()[i].DivisionName },
        };

           listToReturn.Add(obj[0]);
        }

        return Json(listToReturn.ToArray(), JsonRequestBehavior.AllowGet);

        //return Json(new[] {
        //    new { Id = filteredDivisions.ToArray()[0].DivisionID, Value = filteredDivisions.ToArray()[0].DivisionName },
        //    new { Id = 2, Value = "value 2" },
        //    new { Id = 3, Value = "value 3" },
        //}, JsonRequestBehavior.AllowGet);

    }

and it works great.


问:
SwuiftUI Custom Sorting
I'm just starting out in SwuiftUI so bear with me.
I have a Game stuct that has a field lastUpdated and title. I want to have the choice to sort by my list by lastUpdated or title. But I'm not sure how this works. I've looked into sorted(by:) but I can't really get anything to work. Suggestions?

```<code>struct Game: Identifiable, Codable {
let id: UUID
var title: String
var players: [Player]
var lastUsed: Date }
</code>```

GameView

```<code>struct GameListView: View {
@Binding var games: [Game]

var body: some View {

    List {
        ForEach($games) { $game in
            NavigationLink(destination: GameView(game: $game)) {
                Text(game.title)}
            }
        }
</code>```

答:
The scenario is slightly complicated by the Binding form of ForEach, but you should still be able to return a sorted collection. It might look like this:

```<code>struct GameListView: View {
    @Binding var games: [Game]
    @State var sortType : SortType = .lastUsed

    enum SortType {
        case lastUsed, title
    }

    var sortedGames : [Binding<Game>] {
        $games.sorted(by: { a, b in
            switch sortType {
            case .lastUsed:
                return a.wrappedValue.lastUsed < b.wrappedValue.lastUsed
            case .title:
                return a.wrappedValue.title < b.wrappedValue.title
            }
        })
    }

    var body: some View {
        List {
            ForEach(sortedGames) { $game in
                NavigationLink(destination: GameView(game: $game)) {
                    Text(game.title)}
            }
        }
    }
}
</code>```

Title: SwuiftUI Custom Sorting

Body:
I'm just starting out in SwuiftUI so bear with me.
I have a Game stuct that has a field lastUpdated and title. I want to have the choice to sort by my list by lastUpdated or title. But I'm not sure how this works. I've looked into sorted(by:) but I can't really get anything to work. Suggestions?

struct Game: Identifiable, Codable {
let id: UUID
var title: String
var players: [Player]
var lastUsed: Date }

GameView

struct GameListView: View {
@Binding var games: [Game]

var body: some View {

    List {
        ForEach($games) { $game in
            NavigationLink(destination: GameView(game: $game)) {
                Text(game.title)}
            }
        }

Body:
The scenario is slightly complicated by the Binding form of ForEach, but you should still be able to return a sorted collection. It might look like this:

struct GameListView: View {
    @Binding var games: [Game]
    @State var sortType : SortType = .lastUsed

    enum SortType {
        case lastUsed, title
    }

    var sortedGames : [Binding<Game>] {
        $games.sorted(by: { a, b in
            switch sortType {
            case .lastUsed:
                return a.wrappedValue.lastUsed < b.wrappedValue.lastUsed
            case .title:
                return a.wrappedValue.title < b.wrappedValue.title
            }
        })
    }

    var body: some View {
        List {
            ForEach(sortedGames) { $game in
                NavigationLink(destination: GameView(game: $game)) {
                    Text(game.title)}
            }
        }
    }
}


问:
JSON Schema validate if a number is either zero or more than 1000
How could I write a schema to validate that an integer field is either 0 or more than 100?

答:
You can check equality with the const keyword: https://json-schema.org/understanding-json-schema/reference/generic.html#constant-values

You can check numerical ranges with the maximum, minimum, exclusiveMaximum and exclusiveMinimum keywords: https://json-schema.org/understanding-json-schema/reference/numeric.html

You can combine schemas with a number of keywords: anyOf, allOf, oneOf, not, and if/then/else: https://json-schema.org/understanding-json-schema/reference/combining.html


问:
How to iterate through the infinite Cartesian product of infinite generator functions in python?
I want a generator function product that generates the Cartesian product of any two given generator functions f and g (i.e. if x can found in f() in finite time and y can be found in g() in finite time, then (x,y) should be produced from product(f, g) in finite time).

For example, I might want a generator function to iterate through (x,y) satisfying x in itertools.count() and y in itertools.count(-1, -1).

What is a good way to do this? Any order is fine.

答:
Here is a way to do it:</p>
```<code>import itertools

def product(fn1, fn2):
    def product_part(fnx, fny):
      for i, x in enumerate(fnx()):
          for y in itertools.islice(fny(), i):
              yield x, y
    prod_a = zip(fn1(), fn2())
    prod_b = product_part(fn1, fn2)
    prod_c = ((x, y) for y, x in product_part(fn2, fn1))
    return itertools.chain.from_iterable(zip(prod_a, prod_b, prod_c))
</code>```

Body:
Here is a way to do it:

import itertools

def product(fn1, fn2):
    def product_part(fnx, fny):
      for i, x in enumerate(fnx()):
          for y in itertools.islice(fny(), i):
              yield x, y
    prod_a = zip(fn1(), fn2())
    prod_b = product_part(fn1, fn2)
    prod_c = ((x, y) for y, x in product_part(fn2, fn1))
    return itertools.chain.from_iterable(zip(prod_a, prod_b, prod_c))


问:
"Docker Desktop stopped..." message after installation
Installed docker desktop for windows, after having installed the linux kernel update package and changing to wsl 2 version (virtualization is enabled) but i get the message "Docker Desktop stopped..." as shown below.

Tried:

uninstalling and reinstalling again

run application as administrator

答:
From https://github.com/docker/for-win/issues/12545#issuecomment-1037225140

Just go to the config file at C:\Users\<username>\AppData\Roaming\Docker\settings.json, and set "wslEngineEnabled": true

I had to restart after saving.


问:
Python variable manipulated indirectly without being mentioned in function
I'm a coding beginner that's putting a project together for a game. To update the game board, I use this function:

```<code>Board = [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def boardupdate(self, move):
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: self[move[0]] = 1
    except Exception: None
    try: self[move[1]] = 0
    except Exception: None
    try: self[move[2]] = 0
    except Exception: None
    return self
</code>```

Where the first item of the list move represents the location where a piece is being placed in a turn, the second item representing where the piece is being taken from (in this game, you can either place a new piece on the board or move a piece), and the third item represents where a piece is being completely removed from the game. A certain turn can involve any of or none of these actions, hence the try and except blocks (which I learned just today, so if I am using them incorrectly, help would be much appreciated).

The code works as intended inside the function, but for some reason after this function is called, Board gets changed as if it was run through the function.

```<code>print(Board)
print(boardupdate(Board, [0, None]))
print(Board)
</code>```

returns:

```<code>[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

I've tried to solve this by copying Board to a temporary variable like so:

```<code>def boardupdate(self, move):
    tempboard = self
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: tempboard[move[0]] = 1
    except Exception: None
    try: tempboard[move[1]] = 0
    except Exception: None
    try: tempboard[move[2]] = 0
    except Exception: None
    return tempboard
</code>```

Returns the same output as before. How can I change the output of this function without messing around with the initial conditions of Board? This is necessary in order for the rest of my code to run. Thanks!

答:
tempboard = board doesn't copy board, it just binds tempboard to the same value as board.  If you do:

```<code>tempboard = board.copy()
</code>```

it will actually copy board.

Some other miscellaneous advice on this function:

Don't call the board parameter self, since this isn't an instance method on the board itself.  Just call it something like board.

Don't catch all exceptions blindly; it makes errors very difficult to debug.  If you have an error in your code, you want it to raise an exception so you can see exactly what went wrong right away, rather than spending hours trying to figure out why it's just not doing anything!  I'd suggest adopting a convention that a move you aren't making is None, and then checking for None specifically, rather than just ignoring any attempted move that raises an exception.

Use named variables and/or comments to keep track of what the different move items represent.

```<code>def boardupdate(board, move):
    board = board.copy()
    # Subtract 3 from any move positions >= 15.
    move = [p if p is None or p < 15 else p - 3 for p in move]

    [moved_to, moved_from, removed] = move
    if moved_to is not None:
        board[moved_to] = 1
    if moved_from is not None:
        board[moved_from] = 0
    if removed is not None:
        board[removed] = 0

    return board
</code>```

Body:
I'm a coding beginner that's putting a project together for a game. To update the game board, I use this function:

Board = [0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def boardupdate(self, move):
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: self[move[0]] = 1
    except Exception: None
    try: self[move[1]] = 0
    except Exception: None
    try: self[move[2]] = 0
    except Exception: None
    return self

Where the first item of the list move represents the location where a piece is being placed in a turn, the second item representing where the piece is being taken from (in this game, you can either place a new piece on the board or move a piece), and the third item represents where a piece is being completely removed from the game. A certain turn can involve any of or none of these actions, hence the try and except blocks (which I learned just today, so if I am using them incorrectly, help would be much appreciated).

The code works as intended inside the function, but for some reason after this function is called, Board gets changed as if it was run through the function.

print(Board)
print(boardupdate(Board, [0, None]))
print(Board)

returns:

[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I've tried to solve this by copying Board to a temporary variable like so:

def boardupdate(self, move):
    tempboard = self
    for index, val in enumerate(move):
        try:
            if val >= 15:
                val -= 3
                move[index] = val
        except TypeError:
            pass
    try: tempboard[move[0]] = 1
    except Exception: None
    try: tempboard[move[1]] = 0
    except Exception: None
    try: tempboard[move[2]] = 0
    except Exception: None
    return tempboard

Returns the same output as before. How can I change the output of this function without messing around with the initial conditions of Board? This is necessary in order for the rest of my code to run. Thanks!

Body:
tempboard = board doesn't copy board, it just binds tempboard to the same value as board.  If you do:

tempboard = board.copy()

it will actually copy board.

Some other miscellaneous advice on this function:

Don't call the board parameter self, since this isn't an instance method on the board itself.  Just call it something like board.

Don't catch all exceptions blindly; it makes errors very difficult to debug.  If you have an error in your code, you want it to raise an exception so you can see exactly what went wrong right away, rather than spending hours trying to figure out why it's just not doing anything!  I'd suggest adopting a convention that a move you aren't making is None, and then checking for None specifically, rather than just ignoring any attempted move that raises an exception.

Use named variables and/or comments to keep track of what the different move items represent.

def boardupdate(board, move):
    board = board.copy()
    # Subtract 3 from any move positions >= 15.
    move = [p if p is None or p < 15 else p - 3 for p in move]

    [moved_to, moved_from, removed] = move
    if moved_to is not None:
        board[moved_to] = 1
    if moved_from is not None:
        board[moved_from] = 0
    if removed is not None:
        board[removed] = 0

    return board


问:
Filter R dataframe to n most frequent cases and order by frequency
In a dataframe with repeat values, I want the rows for the most frequent n cases, say the two most frequently occurring. The code below does this, selecting rows where x==3 or x==4 and return the rows in that order.

I don't want to have to use the value 5; however, I want some way of programmatically stating the top 2 most frequent x values, without knowing a threshold (5 in this example) apriori. In addition, I would like to order the resulting dataframe by frequency of occurrence, so x==4 rows come before x==3 rows.

I am presuming it is related to count, top_n or slice_max and arrange but maybe not!

Any hints on how to do this with dplyr would be greatly appreciated.

```<code>require(tidyverse)
adf <- data.frame(x=c(rep(2,5),rep(3,7), rep(4,9), 1), y=1:22)
adf %>% group_by(x) %>% filter(n() > 5)
</code>```

答:
We can do this by calculating the size of each group using n() and then filtering on that. If you want them in order, can also use dplyr::arrange().

library(dplyr)

adf %>%
  group_by(x) %>%
  mutate(size = n()) %>%
  ungroup() %>%
  filter(size >= sort(unique(size), TRUE)[2]) %>%
  arrange(desc(size))
#> # A tibble: 16 × 3
#>        x     y  size
#>    <dbl> <int> <int>
#>  1     4    13     9
#>  2     4    14     9
#>  3     4    15     9
#>  4     4    16     9
#>  5     4    17     9
#>  6     4    18     9
#>  7     4    19     9
#>  8     4    20     9
#>  9     4    21     9
#> 10     3     6     7
#> 11     3     7     7
#> 12     3     8     7
#> 13     3     9     7
#> 14     3    10     7
#> 15     3    11     7
#> 16     3    12     7
```

Body:
In a dataframe with repeat values, I want the rows for the most frequent n cases, say the two most frequently occurring. The code below does this, selecting rows where x==3 or x==4 and return the rows in that order.

I don't want to have to use the value 5; however, I want some way of programmatically stating the top 2 most frequent x values, without knowing a threshold (5 in this example) apriori. In addition, I would like to order the resulting dataframe by frequency of occurrence, so x==4 rows come before x==3 rows.

I am presuming it is related to count, top_n or slice_max and arrange but maybe not!

Any hints on how to do this with dplyr would be greatly appreciated.

require(tidyverse)
adf <- data.frame(x=c(rep(2,5),rep(3,7), rep(4,9), 1), y=1:22)
adf %>% group_by(x) %>% filter(n() > 5)


问:
Docker desktop - kubernetes failed to start
I have installed Docker Desktop (version : 2.3.0.4) and enabled Kubernetes.
I deployed couple of PODS and everything was working fine, Since yesterday I am facing a weird issue mentioned below:

```<code>Unable to connect to the server: dial tcp 127.0.0.1:6443: connectex: No
connection could be made because the target machine actively refused it.
</code>```

As such, no changes were made on my system. I am using Linux Containers on Windows 10 machine.

Following steps I have tried:

Restarted the Docker Desktop

Tried the same with minikube and Docker Desktop both

Tried to disable the firewall but due to some permissions, I am not able to turn it off.

I have reset the kubernetes cluster as well.

答:
For me, just "Clean and Purge" wasn't enough. Here is what I did.

Log off VPN

Go to bug and "Clean and Purge Data"

Also choose "Reset to Factory Defaults"

Restart Docker Desktop

Choose "Enable Kubernetes"

At this point, the "Starting" took a while for Kubernetes to be enabled. Now's it all good.

```<code>$ kubectl get namespace
NAME              STATUS   AGE
default           Active   80s
kube-node-lease   Active   82s
kube-public       Active   82s
kube-system       Active   82s
</code>```

Body:
I have installed Docker Desktop (version : 2.3.0.4) and enabled Kubernetes.
I deployed couple of PODS and everything was working fine, Since yesterday I am facing a weird issue mentioned below:

Unable to connect to the server: dial tcp 127.0.0.1:6443: connectex: No
connection could be made because the target machine actively refused it.

As such, no changes were made on my system. I am using Linux Containers on Windows 10 machine.

Following steps I have tried:

Restarted the Docker Desktop

Tried the same with minikube and Docker Desktop both

Tried to disable the firewall but due to some permissions, I am not able to turn it off.

I have reset the kubernetes cluster as well.

Body:
For me, just "Clean and Purge" wasn't enough. Here is what I did.

Log off VPN

Go to bug and "Clean and Purge Data"

Also choose "Reset to Factory Defaults"

Restart Docker Desktop

Choose "Enable Kubernetes"

At this point, the "Starting" took a while for Kubernetes to be enabled. Now's it all good.

$ kubectl get namespace
NAME              STATUS   AGE
default           Active   80s
kube-node-lease   Active   82s
kube-public       Active   82s
kube-system       Active   82s


问:
Plotting bar chart of categorical values for each group
I have a dataframe that I want to group and then to plot (barplot) based on value_counts.

```<code>import pandas as pd

df = pd.DataFrame({'date': ['jan', 'jan', 'jan', 'jan', 'feb', 'feb', 'feb', 'feb'],
                  'value': ['low', 'low', 'high', 'medium', 'medium', 'high', 'high', 'medium']})

print(df)
</code>```

I want to have months on the X-axis (in this case only jan and feb) and bars of values for each month on Y-axis. Hight of the bars should depend of count of specific category.
For example, for 'jan' low=2, high=1, medium=1

I have tried:

```<code>sns.countplot(x = 'date', hue = 'value', data = df.melt())
</code>```

But this is my error:

```<code>ValueError: Could not interpret input 'date'
</code>```

This can be done with matplotlib or seaborn

答:
You can use sns.countplot to count items from the original dataframe. You can use hue= to separate out the value column. order= can fix an order on the x-values. Similarly, hue_order= can set an order for the hue categories. (Default, the order of appearance in the dataframe is used.) palette= can among others be a dictionary to assign a specific color to a specific category.

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'date': ['jan', 'jan', 'jan', 'jan', 'feb', 'feb', 'feb', 'feb'],
                   'value': ['low', 'low', 'high', 'medium', 'medium', 'high', 'high', 'medium']})

sns.set()
ax = sns.countplot(data=df, x='date', hue='value',
                   # order=['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
                   order=['jan', 'feb'], hue_order=['low', 'medium', 'high'],
                   palette={'low': 'limegreen', 'medium': 'gold', 'high': 'crimson'})
ax.set_xlabel('')  # optionally remove 'date' label, as it is clear from the ticklabels
plt.tight_layout()
plt.show()
```

Body:
I have a dataframe that I want to group and then to plot (barplot) based on value_counts.

import pandas as pd

df = pd.DataFrame({'date': ['jan', 'jan', 'jan', 'jan', 'feb', 'feb', 'feb', 'feb'],
                  'value': ['low', 'low', 'high', 'medium', 'medium', 'high', 'high', 'medium']})

print(df)

I want to have months on the X-axis (in this case only jan and feb) and bars of values for each month on Y-axis. Hight of the bars should depend of count of specific category.
For example, for 'jan' low=2, high=1, medium=1

I have tried:

sns.countplot(x = 'date', hue = 'value', data = df.melt())

But this is my error:

ValueError: Could not interpret input 'date'

This can be done with matplotlib or seaborn


问:
C switch case using char[2]
I'm trying to use switch case with char[2] in C, but it only supports integers.

int main() {
        char c[2] = "h";
        switch (c) {
                case "h":
                        printf("done!");
        }
        return 1;
}
```
<p>For better understanding, what I'm trying to do is:</p>
<pre class="lang-py prettyprint-override"><code>if "h" in ")($+#&@+)#"
</code>```

Basically I want to make a condition that matches a character with a group of characters, but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use (int)c which is recommended in other stackoverflow answers, it doesn't return the ascii value.

答:
You can't compare arrays of characters (strings) using a switch statement directly, because switch statements only work with fundamental types; not arrays of fundamental types.

The reason using (int)c isn't returning the ASCII value is because you're casting char[]->int instead of char->int.

The difference between single and double quotes is an important one in C:

'h' is of type char, and is equal to 104 (Lowercase 'h' in ASCII)

"h" is of type const char*, and points to 2 characters: h, & the null terminating character \0

To check if a character is present in a string, you can use the strchr function as mentioned in Vlad from Moscow's answer, or if you want to do it yourself using switch statements you could try this:

```<code>int main()
{
    char c[2] = "h";
    bool found = false;
    for (int i = 0; i < 2; ++i) {
        switch (c[i]) {
        case 'h': // compare c[i] == 'h'
            found = true;
            break;
        default:
            break;
        }
    }
    if (found)
        printf("Done!");
    return 0;
}
</code>```

Title: C switch case using char[2]

Body:
I'm trying to use switch case with char[2] in C, but it only supports integers.

int main() {
        char c[2] = "h";
        switch (c) {
                case "h":
                        printf("done!");
        }
        return 1;
}

For better understanding, what I'm trying to do is:

if "h" in ")($+#&@+)#"

Basically I want to make a condition that matches a character with a group of characters, but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use (int)c which is recommended in other stackoverflow answers, it doesn't return the ascii value.

Body:
You can't compare arrays of characters (strings) using a switch statement directly, because switch statements only work with fundamental types; not arrays of fundamental types.

The reason using (int)c isn't returning the ASCII value is because you're casting char[]->int instead of char->int.

The difference between single and double quotes is an important one in C:

'h' is of type char, and is equal to 104 (Lowercase 'h' in ASCII)

"h" is of type const char*, and points to 2 characters: h, & the null terminating character \0

To check if a character is present in a string, you can use the strchr function as mentioned in Vlad from Moscow's answer, or if you want to do it yourself using switch statements you could try this:

int main()
{
    char c[2] = "h";
    bool found = false;
    for (int i = 0; i < 2; ++i) {
        switch (c[i]) {
        case 'h': // compare c[i] == 'h'
            found = true;
            break;
        default:
            break;
        }
    }
    if (found)
        printf("Done!");
    return 0;
}


问:
remove elementor html tags but leave the text inside the tags
I try to remove all html tags that Elementor creates but leave the text inside.

It works, but I'm very sure the RegEx can be simplified so I need only one replace. My code looks like this

I think the easiest way would be to create an array with class names and all tags that include one of these class names will then be removed. But I'm really struggeling with RegEX

```<code>if( !is_admin() ) // not admin side
    add_filter( 'the_content', 'remove_all_elementor_tags' );

function remove_all_elementor_tags( $content )
{

// remove <div class="elementor-widget-container"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-widget-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-element"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-element\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-container"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor-section-wrap"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-section-wrap\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove <section class="elementor-section"></div>
$re = "/ ?<section[^<]*?class=[\"'][^\"']*\\belementor-section\\b[^\"']*[\"'][^<]*?>| ?<\\/section>/s";

$content = preg_replace($re, "", $content);

// remove <div class="elementor"></div>
$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor\\b[^\"']*[\"'][^<]*?>| ?<\\/div/s";

$content = preg_replace($re, "", $content);

    return $content;

}
</code>```

the html content before removing looks like this

```<code><div class="page-content">
    <div data-elementor-type="wp-page" data-elementor-id="257" data-post-id="257" data-obj-id="257" class="elementor elementor-257 dce-elementor-post-257" data-elementor-settings="[]">
        <div class="elementor-section-wrap">
            <section class="elementor-section elementor-top-section elementor-element elementor-element-2e18164 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="2e18164" data-element_type="section">
                <div class="elementor-container elementor-column-gap-default">
                    <div class="elementor-element elementor-element-1aa904f elementor-widget elementor-widget-dce-rawphp" data-id="1aa904f" data-element_type="widget" data-widget_type="dce-rawphp.default">
                        <div class="elementor-widget-container">
                            <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <div class="post-tags">
    </div>
</div>
</code>```

the html content after my code looks like this

```<code><div class="page-content">
    <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
    <div class="post-tags">
    </div>
</div>
</code>```

thank you

答:
Depending on your actual input snippets, better use DOM function instead, e.g.:</p>
```<code><?php

$snippet = <<<DATA
<div class="page-content">
    <div data-elementor-type="wp-page" data-elementor-id="257" data-post-id="257" data-obj-id="257" class="elementor elementor-257 dce-elementor-post-257" data-elementor-settings="[]">
        <div class="elementor-section-wrap">
            <section class="elementor-section elementor-top-section elementor-element elementor-element-2e18164 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="2e18164" data-element_type="section">
                <div class="elementor-container elementor-column-gap-default">
                    <div class="elementor-element elementor-element-1aa904f elementor-widget elementor-widget-dce-rawphp" data-id="1aa904f" data-element_type="widget" data-widget_type="dce-rawphp.default">
                        <div class="elementor-widget-container">
                            <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <div class="post-tags">
    </div>
</div>
DATA;

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($snippet);//, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOWARNING);
libxml_clear_errors();

$xpath = new DOMXPath($dom,);

$widgets = $xpath->query("//div[@class='elementor-widget-container']");
foreach ($widgets as $widget) {
    echo $widget->nodeValue;
}
?>
</code>```

Body:
I try to remove all html tags that Elementor creates but leave the text inside.

It works, but I'm very sure the RegEx can be simplified so I need only one replace. My code looks like this

I think the easiest way would be to create an array with class names and all tags that include one of these class names will then be removed. But I'm really struggeling with RegEX

if( !is_admin() ) // not admin side
    add_filter( 'the_content', 'remove_all_elementor_tags' );

function remove_all_elementor_tags( $content )
{

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-widget-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-element\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-container\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor-section-wrap\\b[^\"']*[\"'][^<]*?>| ?<\\/div>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<section[^<]*?class=[\"'][^\"']*\\belementor-section\\b[^\"']*[\"'][^<]*?>| ?<\\/section>/s";

$content = preg_replace($re, "", $content);

// remove

$re = "/ ?<div[^<]*?class=[\"'][^\"']*\\belementor\\b[^\"']*[\"'][^<]*?>| ?<\\/div/s";

$content = preg_replace($re, "", $content);

    return $content;

}

the html content before removing looks like this

                            dies ist der normale Inhalt

the html content after my code looks like this

    dies ist der normale Inhalt

thank you

Body:
Depending on your actual input snippets, better use DOM function instead, e.g.:

<?php

$snippet = <<<DATA
<div class="page-content">
    <div data-elementor-type="wp-page" data-elementor-id="257" data-post-id="257" data-obj-id="257" class="elementor elementor-257 dce-elementor-post-257" data-elementor-settings="[]">
        <div class="elementor-section-wrap">
            <section class="elementor-section elementor-top-section elementor-element elementor-element-2e18164 elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-id="2e18164" data-element_type="section">
                <div class="elementor-container elementor-column-gap-default">
                    <div class="elementor-element elementor-element-1aa904f elementor-widget elementor-widget-dce-rawphp" data-id="1aa904f" data-element_type="widget" data-widget_type="dce-rawphp.default">
                        <div class="elementor-widget-container">
                            <!-- Dynamic PHP Raw -->dies ist der normale Inhalt
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <div class="post-tags">
    </div>
</div>
DATA;

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($snippet);//, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOWARNING);
libxml_clear_errors();

$xpath = new DOMXPath($dom,);

$widgets = $xpath->query("//div[@class='elementor-widget-container']");
foreach ($widgets as $widget) {
    echo $widget->nodeValue;
}
?>


问:
How could i skip a row if a csv field is empty
I have a csv file where I have some names and the date from when students have passed the exam. if they did not pass the exam the date will be empty. how could I filter out the empty field so I only have a list with people that have passed the test?

Here is the code that I have. the row[0] is the names of the student and row[12] is the date they have passed it.

```<code>with open("MYCSV_FILE", 'r') as read_obj:
       csv_dict_reader = csv.reader(read_obj, delimiter=';')
for row in csv_dict_reader:
    if row[12]:
        with open('fed_results\Behaalde_studenten.csv', 'a') as f_object:
            # Pass the CSV  file object to the writer() function
            writer_object = csv.writer(f_object)
            # Result - a writer object
            # Pass the data in the list as an argument into the writerow() function
            writer_object.writerow(row[0])
            # Close the file object
            f_object.close()

</code>```

答:
row[12] can be checked for an empty result like this:

```<code>if row[12]:
    # do something #
</code>```

So your code can check for non-empty rows by:

```<code>with open("MYCSV_FILE", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            print(row[0], row[12])
</code>```

Or you can consider an if/else statement:

```<code>with open("MYCSV_FILE", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            print(row[0], row[12])
        else:
            # what to do if it isn't there #
</code>```

This all assumes that each row is delimited by a semicolon even when empty values are given, such that:

```<code>a;b;c;d;e;f;g;h;i;j;k;l
1;2;3;4;5;6;7;8;9;10;11;
</code>```

Body:
I have a csv file where I have some names and the date from when students have passed the exam. if they did not pass the exam the date will be empty. how could I filter out the empty field so I only have a list with people that have passed the test?

Here is the code that I have. the row[0] is the names of the student and row[12] is the date they have passed it.

with open("MYCSV_FILE", 'r') as read_obj:
       csv_dict_reader = csv.reader(read_obj, delimiter=';')
for row in csv_dict_reader:
    if row[12]:
        with open('fed_results\Behaalde_studenten.csv', 'a') as f_object:
            # Pass the CSV  file object to the writer() function
            writer_object = csv.writer(f_object)
            # Result - a writer object
            # Pass the data in the list as an argument into the writerow() function
            writer_object.writerow(row[0])
            # Close the file object
            f_object.close()

Body:
row[12] can be checked for an empty result like this:

if row[12]:
    # do something #

So your code can check for non-empty rows by:

with open("MYCSV_FILE", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            print(row[0], row[12])

Or you can consider an if/else statement:

with open("MYCSV_FILE", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            print(row[0], row[12])
        else:
            # what to do if it isn't there #

This all assumes that each row is delimited by a semicolon even when empty values are given, such that:

a;b;c;d;e;f;g;h;i;j;k;l
1;2;3;4;5;6;7;8;9;10;11;


问:
Move text next to logo; get rid of a hard rule
Here's the site:  www.red-tuxedo.com

I want the "Red Tuxedo" text to sit next to the logo, not below, and I want to get rid of that hard rule that runs through the logo.  My CSS / HTML skills aren't up to it.  I completely destroy the column layout when I change the text and I can't find the hard rule in the code.  Tried adjusting the gif (cut off the bottom in Photoshop) and that didn't help.

I did write to the person who created the template; haven't heard back after several days.  Would like to get this fixed before I start adding more pages.

thx

答:
Try changing the div (id=logo) so that it includes the logo image and the text and add align='absmiddle' to the image.  I'd suggest CSS but it looks like it has fixed attributes on it anyway.  The "rule" looks like it is coming from the background image for the body element.  You'd need to update the file bg.gif to modify it, I think.

```<code><div id="logo">
    <img id="logo_red_tuxedo" src="logo_red_tuxedo.gif"
         alt="Red Tuxedo Logo" align="absmiddle" height="60" width="60">
    <span class="red">Red</span>Tuxedo
</div>
</code>```

OwnerDisplayName: Karen

ContentLicense: CC BY-SA 2.5

Body:
Try changing the div (id=logo) so that it includes the logo image and the text and add align='absmiddle' to the image.  I'd suggest CSS but it looks like it has fixed attributes on it anyway.  The "rule" looks like it is coming from the background image for the body element.  You'd need to update the file bg.gif to modify it, I think.

<div id="logo">
    <img id="logo_red_tuxedo" src="logo_red_tuxedo.gif"
         alt="Red Tuxedo Logo" align="absmiddle" height="60" width="60">
    <span class="red">Red</span>Tuxedo
</div>

OwnerDisplayName: tvanfosson


问:
Adding Guidelines in Plot in Netlogo
I have a plot in Netlogo that shows the average heading of all turtles. Even when the scale is set from 0 to 360 it is a little hard to read, so I wanted to add horizontal guidelines at 90, 180, and 270. I can't find anything in the manual or web on how to do this. Thanks in advance for any help.</p>

答:
You can use plotxy to 'draw' well-enough for most purposes like this. For example, I've created a new plot and added this code to the "Plot update commands" field:

```<code>create-temporary-plot-pen "temp"
set-plot-pen-color 7
foreach [ 90 180 270 ] [ h ->
plot-pen-up
plotxy 0 h
plot-pen-down
plotxy plot-x-max h
]
</code>```

On each update (to maintain the lines as the scale of the x axis changes, in this example), this code iterates over the y values of interest, turns the pen off temporarily, moves the pen to x = 0 and y = h, then draws a horizontal line to whatever x is the current maximum x value for the plot. Output should look something like:

Title: Adding Guidelines in Plot in Netlogo

Body:
You can use plotxy to 'draw' well-enough for most purposes like this. For example, I've created a new plot and added this code to the "Plot update commands" field:

create-temporary-plot-pen "temp"
set-plot-pen-color 7
foreach [ 90 180 270 ] [ h ->
plot-pen-up
plotxy 0 h
plot-pen-down
plotxy plot-x-max h
]

On each update (to maintain the lines as the scale of the x axis changes, in this example), this code iterates over the y values of interest, turns the pen off temporarily, moves the pen to x = 0 and y = h, then draws a horizontal line to whatever x is the current maximum x value for the plot. Output should look something like:


问:
Problem with System.out.printf command in Java
I am new to programming so I apologize beforehand.  I am running a program and am having a problem with the System.out.printf method in Java. I know everything else in the program is working correctly (tested it). However this does not seem to work.

The error is:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double

      at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)

      at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)

      at java.util.Formatter$FormatSpecifier.print(Unknown Source)

      at java.util.Formatter.format(Unknown Source)

      at java.io.PrintStream.format(Unknown Source)

      at java.io.PrintStream.printf(Unknown Source)

      at Advisor_Score.main(Advisor_Score.java:17)

My code is:

```<code>import java.lang.Math;
public class Advisor_Score {
    public static void main(String[] args){
        double l[] = {101,1,1,1};
        double k[] = {102,2,2,4};
        double m[] = {103,5,5,5,5,5,5,5};
        double All_users[][]={l,k,m};
        double sum[]=new double [All_users.length];
        double [] raw_advisor=new double [All_users.length];
        double []advisor_score= new double [All_users.length];
        for (int i=0;i<All_users.length;i++){
                for(int j=1;j<All_users[i].length;j++){
                        sum[i]+=All_users[i][j];
                }
                raw_advisor[i]=((sum[i]-(3*(All_users[i].length-1)))/4);
                advisor_score[i]= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor[i])));
                System.out.printf("%d: %d\n", All_users[i][0], advisor_score[i]);
                }
    }
}
</code>```

Not really sure why it's not working.

答: if your dataType is bigDecimal then have to use : %g

Body:
I am new to programming so I apologize beforehand.  I am running a program and am having a problem with the System.out.printf method in Java. I know everything else in the program is working correctly (tested it). However this does not seem to work.

The error is:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double

      at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)

      at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)

      at java.util.Formatter$FormatSpecifier.print(Unknown Source)

      at java.util.Formatter.format(Unknown Source)

      at java.io.PrintStream.format(Unknown Source)

      at java.io.PrintStream.printf(Unknown Source)

      at Advisor_Score.main(Advisor_Score.java:17)

My code is:

import java.lang.Math;
public class Advisor_Score {
    public static void main(String[] args){
        double l[] = {101,1,1,1};
        double k[] = {102,2,2,4};
        double m[] = {103,5,5,5,5,5,5,5};
        double All_users[][]={l,k,m};
        double sum[]=new double [All_users.length];
        double [] raw_advisor=new double [All_users.length];
        double []advisor_score= new double [All_users.length];
        for (int i=0;i<All_users.length;i++){
                for(int j=1;j<All_users[i].length;j++){
                        sum[i]+=All_users[i][j];
                }
                raw_advisor[i]=((sum[i]-(3*(All_users[i].length-1)))/4);
                advisor_score[i]= 2.5+(2.5*(1-Math.pow(Math.E, -.5*raw_advisor[i])));
                System.out.printf("%d: %d\n", All_users[i][0], advisor_score[i]);
                }
    }
}

Not really sure why it's not working.


问:
NjsonSchema Validation If Property1 is equal to Something then require Property2
I seem to not be able to get const or enum working as part of an if-then-else JSON schema validation.

They seem to be interchangeable when 1 validation value is concerned. (Reference)

Here is my JSON schema

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Test_Schema",
      "description": "A schema for validating a test object",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "GeneralData": {
          "type": "object",
          "description": "Advsor and admin customer information",
          "properties": {
            "Name": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor name"
            },
            "Age": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor email"
            },
            "Location": {
              "type": [ "string", "null" ],
              "description": "The advisor's manager email'"
            }
          },
          "required": [ "Name", "Location", "Age" ]
        },
        "ClientData": {
          "type": "object",
          "description": "Customer's information",
          "additionalProperties": false,
          "properties": {
            "Title": {
              "type": [ "string", "null" ]
            },
            "Forename": {
              "type": [ "string", "null" ]
            },
            "Surname": {
              "type": [ "string" ]
            }
          },
          "required": [ "Title" ],
          "if": {
            "properties": {
              "Forename": { "enum": [ "Soameonea" ] }
            },
            "required": [ "Forename" ]
          },
          "then": { "required": [ "Surname" ] },
          "else": false
        }
      }
    }
```
<p>If Forename = "Someone" I want Surname to be required.</p>
<p>Here is my jsonObject after serialization:</p>
```     {
        "GeneralData": {
            "Name": "Not Relevant",
            "Age": "Not Relevant",
            "Location": "Not Relevant"
        },
        "ClientData": {
            "Title": "SomeTitle",
            "Forename": "Someone",
            "Surname": null
        }
    }
```
<p>Validation code:</p>
```     internal void ValidateDataObjectOnSchema()
            {
                var dataObject = PopulateDataObject();
                var json = JsonConvert.SerializeObject(dataObject);
                var result = GetSchema().Validate(json);
                var errors = result.Select(x =>
                {
                    return new Errors() { Title = x.Property, Description = x.Schema.Description };
                });
                var i = errors;

            }

      internal JsonSchema GetSchema()
            {
                return JsonSchema.FromFileAsync("Test/testSchema.json").Result;
            }
```

Right now it still requires Surname, even though the enum Soameonea != Someone and I only require Title. <== Issue1

In the JSON schema if I set "Surname":{"type":["string","null]} then the error disappears and still I don't get the error if I then change the if condition for the Forename enum to "Someone". <== Issue 2

I cannot get a different validation output if I replace Enum with Const, So if I can get one to work I'm sure the other will follow.

I've found several answers to this question (Answer 1), I try to implement the same thing and for some reason, it fails in my case.

What am I missing?

答:
In the JSON schema if I set "Surname":{"type":["string","null]} then the error disappears

A property with a null value still has a value. If you want to say that the property value must not only exist, but not be null, then add "type": "string" to your then condition.

Body:
I seem to not be able to get const or enum working as part of an if-then-else JSON schema validation.

They seem to be interchangeable when 1 validation value is concerned. (Reference)

Here is my JSON schema

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Test_Schema",
      "description": "A schema for validating a test object",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "GeneralData": {
          "type": "object",
          "description": "Advsor and admin customer information",
          "properties": {
            "Name": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor name"
            },
            "Age": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor email"
            },
            "Location": {
              "type": [ "string", "null" ],
              "description": "The advisor's manager email'"
            }
          },
          "required": [ "Name", "Location", "Age" ]
        },
        "ClientData": {
          "type": "object",
          "description": "Customer's information",
          "additionalProperties": false,
          "properties": {
            "Title": {
              "type": [ "string", "null" ]
            },
            "Forename": {
              "type": [ "string", "null" ]
            },
            "Surname": {
              "type": [ "string" ]
            }
          },
          "required": [ "Title" ],
          "if": {
            "properties": {
              "Forename": { "enum": [ "Soameonea" ] }
            },
            "required": [ "Forename" ]
          },
          "then": { "required": [ "Surname" ] },
          "else": false
        }
      }
    }

If Forename = "Someone" I want Surname to be required.

Here is my jsonObject after serialization:

     {
        "GeneralData": {
            "Name": "Not Relevant",
            "Age": "Not Relevant",
            "Location": "Not Relevant"
        },
        "ClientData": {
            "Title": "SomeTitle",
            "Forename": "Someone",
            "Surname": null
        }
    }

Validation code:

     internal void ValidateDataObjectOnSchema()
            {
                var dataObject = PopulateDataObject();
                var json = JsonConvert.SerializeObject(dataObject);
                var result = GetSchema().Validate(json);
                var errors = result.Select(x =>
                {
                    return new Errors() { Title = x.Property, Description = x.Schema.Description };
                });
                var i = errors;

            }

      internal JsonSchema GetSchema()
            {
                return JsonSchema.FromFileAsync("Test/testSchema.json").Result;
            }

Right now it still requires Surname, even though the enum Soameonea != Someone and I only require Title. <== Issue1

In the JSON schema if I set "Surname":{"type":["string","null]} then the error disappears and still I don't get the error if I then change the if condition for the Forename enum to "Someone". <== Issue 2

I cannot get a different validation output if I replace Enum with Const, So if I can get one to work I'm sure the other will follow.

I've found several answers to this question (Answer 1), I try to implement the same thing and for some reason, it fails in my case.

What am I missing?


问:
Potsgres SQL: select timestamp prior to max timestamp
I have a table in Postgres with timestamps:

```<code>timestamp
2022-01-01 00:52:53
2022-01-01 00:57:12
...
2022-02-13 11:00:31
2022-02-13 16:45:10
</code>```

How can I select the timestamp closest to max timestamp? Meaning, I want the timestamp 2022-02-13 11:00:31.

I am looking for something like max(timestamp)-1 so I can do on a recurring basis. Thank you

答:
You can do:

```<code>select *
from (
  select *,
    rank() over(order by timestamp desc) as rk
  from t
) x
where rk = 2
</code>```

See running example at DB Fiddle.

Body:
I have a table in Postgres with timestamps:

timestamp
2022-01-01 00:52:53
2022-01-01 00:57:12
...
2022-02-13 11:00:31
2022-02-13 16:45:10

How can I select the timestamp closest to max timestamp? Meaning, I want the timestamp 2022-02-13 11:00:31.

I am looking for something like max(timestamp)-1 so I can do on a recurring basis. Thank you

Body:
You can do:

select *
from (
  select *,
    rank() over(order by timestamp desc) as rk
  from t
) x
where rk = 2

See running example at DB Fiddle.


问:
uploading images in winforms application
Does anyone know if a there is a control to allow the user to upload a image to a windows form?  Or any example code to accomplish this.

I am using win-form applications

Thanks,

答: It's note clear where you are going to upload your image. If you just want to use an image in a simple desktop application you can use OpenFileDialog to allow a user to select an image file. And then you can use this image path in you application. If you you want to upload this image to database you can read this image into memory using something like FileStream class.</p>