问:
Scrapy API request 403 error issue. Works with requests, but not scrapy
I've having a weird issue where my API request call works perfectly with standard request library, but it throws a 403 using scrapy only. The error message does not give me anything useful, except the "403 error" message. I have dropped my API key from this post, but you can easily obtain your own. Let me know if you need help getting an API key.

Working python code (no scrapy)

```<code>import requests

url = "https://www.airbnb.ca/api/v3/ExploreSections"

querystring = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}

headers = {
    "x-airbnb-api-key": "YOUR_KEY",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
    "content-type": "application/json",
    "accept-language": "en-US,en;q=0.9"
}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
</code>```

Scrapy spider code:

```<code>import scrapy
import json
from urllib.parse import urlencode

class ListingsSpider(scrapy.Spider):
    name = 'listings'
    allowed_domains = ['airbnb.ca']

    def start_requests(self):
        params = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}
        url = f"https://www.airbnb.ca/api/v3/ExploreSections?{urlencode(params)}"
        headers = {
            "x-airbnb-api-key": "YOUR_KEY",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
            "content-type": "application/json",
            "accept-language": "en-US,en;q=0.9"
        }
        yield scrapy.Request(
            url=url,
            method='GET',
            headers=headers,
            callback=self.parse_listings,
        )

    def parse_listings(self, response):
        resp_dict = json.loads(response.body)
        yield resp_dict
</code>```

答:
The problem is with the headers, copy them from the browser and remove cookie and content-length if they are present.

import scrapy
import json
from urllib.parse import urlencode

class ListingsSpider(scrapy.Spider):
    name = 'listings'
    allowed_domains = ['airbnb.ca']

    custom_settings = {
        'DOWNLOAD_DELAY': 0.5
    }
    def start_requests(self):
        params = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}
        url = f"https://www.airbnb.ca/api/v3/ExploreSections?{urlencode(params)}"

        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.5",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "DNT": "1",
            "Host": "www.airbnb.ca",
            "Pragma": "no-cache",
            "Referer": "https://www.airbnb.ca/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "Sec-GPC": "1",
            "TE": "trailers",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
            "X-Airbnb-API-Key": "API_KEY",
            "X-Airbnb-GraphQL-Platform": "web",
            "X-Airbnb-GraphQL-Platform-Client": "minimalist-niobe",
            "X-Airbnb-Supports-Airlock-V2": "true",
            "X-CSRF-Token": "null",
            "X-CSRF-Without-Token": "1",
            "X-KL-Ajax-Request": "Ajax_Request",
            "X-Niobe-Short-Circuited": "true"
        }
        yield scrapy.Request(
            url=url,
            method='GET',
            headers=headers,
            callback=self.parse_listings,
        )

    def parse_listings(self, response):
        resp_dict = response.json()
        yield resp_dict
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>{'data': {'presentation': {'__typename': 'RootPresentationContainer', 'explore': {'__typename': 'ExplorePresentation', 'sections': {'__typename': 'ExploreSections', 'sections': [{'__typename': 'SectionContainer', 'id':
...
...
...
</code>```

Getting the request headers, example with chrome:

Body:
I've having a weird issue where my API request call works perfectly with standard request library, but it throws a 403 using scrapy only. The error message does not give me anything useful, except the "403 error" message. I have dropped my API key from this post, but you can easily obtain your own. Let me know if you need help getting an API key.

Working python code (no scrapy)

import requests

url = "https://www.airbnb.ca/api/v3/ExploreSections"

querystring = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}

headers = {
    "x-airbnb-api-key": "YOUR_KEY",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
    "content-type": "application/json",
    "accept-language": "en-US,en;q=0.9"
}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

Scrapy spider code:

import scrapy
import json
from urllib.parse import urlencode

class ListingsSpider(scrapy.Spider):
    name = 'listings'
    allowed_domains = ['airbnb.ca']

    def start_requests(self):
        params = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}
        url = f"https://www.airbnb.ca/api/v3/ExploreSections?{urlencode(params)}"
        headers = {
            "x-airbnb-api-key": "YOUR_KEY",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
            "content-type": "application/json",
            "accept-language": "en-US,en;q=0.9"
        }
        yield scrapy.Request(
            url=url,
            method='GET',
            headers=headers,
            callback=self.parse_listings,
        )

    def parse_listings(self, response):
        resp_dict = json.loads(response.body)
        yield resp_dict

Body:
The problem is with the headers, copy them from the browser and remove cookie and content-length if they are present.

import scrapy
import json
from urllib.parse import urlencode

class ListingsSpider(scrapy.Spider):
    name = 'listings'
    allowed_domains = ['airbnb.ca']

    custom_settings = {
        'DOWNLOAD_DELAY': 0.5
    }
    def start_requests(self):
        params = {"operationName":"ExploreSections","locale":"en-CA","currency":"CAD","_cb":"1db02z70xkcr690n1h3gp0py4nmy","variables":"{\"isInitialLoad\":true,\"hasLoggedIn\":false,\"cdnCacheSafe\":false,\"source\":\"EXPLORE\",\"exploreRequest\":{\"metadataOnly\":false,\"version\":\"1.8.3\",\"itemsPerGrid\":20,\"tabId\":\"home_tab\",\"refinementPaths\":[\"/homes\"],\"flexibleTripDates\":[\"february\",\"march\"],\"flexibleTripLengths\":[\"weekend_trip\"],\"datePickerType\":\"calendar\",\"placeId\":\"ChIJpTvG15DL1IkRd8S0KlBVNTI\",\"checkin\":\"2022-03-15\",\"checkout\":\"2022-03-16\",\"adults\":2,\"source\":\"structured_search_input_header\",\"searchType\":\"autocomplete_click\",\"query\":\"Toronto, ON\",\"cdnCacheSafe\":false,\"treatmentFlags\":[\"flex_destinations_june_2021_launch_web_treatment\",\"new_filter_bar_v2_fm_header\",\"merch_header_breakpoint_expansion_web\",\"flexible_dates_12_month_lead_time\",\"storefronts_nov23_2021_homepage_web_treatment\",\"flexible_dates_options_extend_one_three_seven_days\",\"super_date_flexibility\",\"micro_flex_improvements\",\"micro_flex_show_by_default\",\"search_input_placeholder_phrases\",\"pets_fee_treatment\"],\"screenSize\":\"large\",\"isInitialLoad\":true,\"hasLoggedIn\":false},\"removeDuplicatedParams\":false}","extensions":"{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"0d0a5c3b44e87ccaecf084cfc3027a175af11955cffa04bb986406e9b4bdfe6e\"}}"}
        url = f"https://www.airbnb.ca/api/v3/ExploreSections?{urlencode(params)}"

        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.5",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "DNT": "1",
            "Host": "www.airbnb.ca",
            "Pragma": "no-cache",
            "Referer": "https://www.airbnb.ca/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "Sec-GPC": "1",
            "TE": "trailers",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
            "X-Airbnb-API-Key": "API_KEY",
            "X-Airbnb-GraphQL-Platform": "web",
            "X-Airbnb-GraphQL-Platform-Client": "minimalist-niobe",
            "X-Airbnb-Supports-Airlock-V2": "true",
            "X-CSRF-Token": "null",
            "X-CSRF-Without-Token": "1",
            "X-KL-Ajax-Request": "Ajax_Request",
            "X-Niobe-Short-Circuited": "true"
        }
        yield scrapy.Request(
            url=url,
            method='GET',
            headers=headers,
            callback=self.parse_listings,
        )

    def parse_listings(self, response):
        resp_dict = response.json()
        yield resp_dict

Output:

{'data': {'presentation': {'__typename': 'RootPresentationContainer', 'explore': {'__typename': 'ExplorePresentation', 'sections': {'__typename': 'ExploreSections', 'sections': [{'__typename': 'SectionContainer', 'id':
...
...
...

Getting the request headers, example with chrome:


来源: stackexchange

问:
Batch index updates?
I'm writing several hundred or potentially several thousand rows into a set of tables at a time, each of which is heavily indexed both internally and via indexed views.

Generally, the inserts are occurring where the rows inserted will be adjacent in the index.

I expect these inserts to be expensive, but they are really slow. I think part of the performance issue is that the indexes are being updated with each individual INSERT.

Is there a way to tell SQL Server to hold off on updating the indexes until I am finished with my batch of inserts so the index trees will only need to be updated once?

These are executed as separate statements due to needing to show the user a progress bar during save and log any individual issues, but are all coming from the same connection in C#. I can place them in a transaction if needed, though I'd prefer not to.

答:
You are paying the cost of adding those rows to the index one way or another.  Not updating the index during the insert would cause an issue with accuracy of concurrent statements - any query on that table that used any of the indexes would not "see" the new rows!

If speed is of the essence, and downtime after the insert isn't a major concern, you can:

Disable non-clustered indexes on the target table

Inert

Rebuild non-clustered indexes

You probably should clarify some more about your table:

How wide is the table?

How many indexes?

How wide are the indexes?

If you have 20 indexes and each index has 5 fields, you are really updating 100 extra fields per row which can get expensive quickly.

ContentLicense: CC BY-SA 3.0

Title: Batch index updates?


问:
How can i make these shapes different in loop with python?
So I have this code here, everything is good but it has to make 20 different shapes, at the moment it makes 20 same shapes. Can somebody help me plz?

import random
from turtle import*

def func(lenght, nr_of_sides):
    i = 0
    while i in range(20):
        i += 1
        for element in range(nr_of_sides):
            forward(lenght)
            angle = 360/nr_of_sides
            left(angle)

a = random.randint(1, 100)
b = random.randint(3, 10)
func(a, b)

exitonclick()
```

答:
I added the for loop out of the function so every time it starts a new iteration the a and b values are random.

```<code>import random
from turtle import*

def func(lenght, nr_of_sides):
    for element in range(nr_of_sides):
        forward(lenght)
        angle = 360/nr_of_sides
        left(angle)

for i in range(0, 20):
    a = random.randint(1, 100)
    b = random.randint(3, 10)
    func(a, b)

exitonclick()
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
I added the for loop out of the function so every time it starts a new iteration the a and b values are random.

import random
from turtle import*

def func(lenght, nr_of_sides):
    for element in range(nr_of_sides):
        forward(lenght)
        angle = 360/nr_of_sides
        left(angle)

for i in range(0, 20):
    a = random.randint(1, 100)
    b = random.randint(3, 10)
    func(a, b)

exitonclick()

Result:


问:
How to update the entire div after deleting each row?
I wrote a simple table, and in each row I'll update the div tag.

As you can see, each row contains two parts that are separated by :, and each part in my array separated by |.

so the output is something like this :

|3:Apple|5:Orange|1:Lemon

I'm very rookie in JS,So if you answer these two questions, I will be grateful.

How can I update the entire div after deleting each row?

According to the code I wrote(Just JS), do you suggest a shorter and cleaner way to update the div?
I feel that the code I wrote is very spaghetti.

$('.add-row').click(function() {
  row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
});
$(document).on('change', 'input[name="prodKind"]', function() {
  mainArr = [];
  var mainTable = $(this).closest('table');
  var tr = mainTable.find('tr');
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      tmpArr.push(values);
    });
    mainArr.push(tmpArr.join(":"));
  });
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').html(mainArr.join("|"));
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').trigger('blur');

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tr>
  <td>
<table>
  <tr>
<td>
  <table class='table tablemain' border=1>
    <tr>
      <td>number</td>
      <td>item</td>
      <td><span class="add-row font-icon-plus-sign">add</span></td>
    </tr>
  </table>
  <div class='kind-out'></div>
</td>
  </tr>
</table>
  </td>
</tr>
</table></code>```

答:
I have added a render function which basically gets called from the delete button click and the input change

$('.add-row').click(function() {
  row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
  render();
});

//Render function called from onchange as well as delete click
function render(){
 mainArr = [];
  var mainTable = $('.tablemain');
  var tr = mainTable.find('tr');
  $('.kind-out').html("");
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      if(values.trim() != ''){
      tmpArr.push(values);
      }
    });
    if(tmpArr.length > 0)
    mainArr.push(tmpArr.join(":"));
  });
  $('.kind-out').html(mainArr.join("|"));
  $('.kind-out').trigger('blur');
}

$(document).on('change', 'input[name="prodKind"]', render);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tr>
  <td>
<table>
  <tr>
<td>
  <table class='table tablemain' border=1>
    <tr>
      <td>number</td>
      <td>item</td>
      <td><span class="add-row font-icon-plus-sign">add</span></td>
    </tr>
  </table>
  <div class='kind-out'></div>
</td>
  </tr>
</table>
  </td>
</tr>
</table></code>```

Body:
I wrote a simple table, and in each row I'll update the div tag.

As you can see, each row contains two parts that are separated by :, and each part in my array separated by |.

so the output is something like this :

|3:Apple|5:Orange|1:Lemon

I'm very rookie in JS,So if you answer these two questions, I will be grateful.

How can I update the entire div after deleting each row?

According to the code I wrote(Just JS), do you suggest a shorter and cleaner way to update the div?
I feel that the code I wrote is very spaghetti.

$('.add-row').click(function() {
  row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
});
$(document).on('change', 'input[name="prodKind"]', function() {
  mainArr = [];
  var mainTable = $(this).closest('table');
  var tr = mainTable.find('tr');
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      tmpArr.push(values);
    });
    mainArr.push(tmpArr.join(":"));
  });
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').html(mainArr.join("|"));
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').trigger('blur');

});

      number
      item
      add

Body:
I have added a render function which basically gets called from the delete button click and the input change

$('.add-row').click(function() {
  row = "<tr class='prod-row'><td class='product_kind'><input type='number' name='prodKind' placeholder='number' /></td><td class='product_kind'><input dir='rtl' type='text' name='prodKind' placeholder='item' /></td><td><span class='del-row font-icon-minus-sign'>del</span></td></tr>";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
  render();
});

//Render function called from onchange as well as delete click
function render(){
 mainArr = [];
  var mainTable = $('.tablemain');
  var tr = mainTable.find('tr');
  $('.kind-out').html("");
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      if(values.trim() != ''){
      tmpArr.push(values);
      }
    });
    if(tmpArr.length > 0)
    mainArr.push(tmpArr.join(":"));
  });
  $('.kind-out').html(mainArr.join("|"));
  $('.kind-out').trigger('blur');
}

$(document).on('change', 'input[name="prodKind"]', render);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tr>
  <td>
<table>
  <tr>
<td>
  <table class='table tablemain' border=1>
    <tr>
      <td>number</td>
      <td>item</td>
      <td><span class="add-row font-icon-plus-sign">add</span></td>
    </tr>
  </table>
  <div class='kind-out'></div>
</td>
  </tr>
</table>
  </td>
</tr>
</table>


问:
Should a key be directly on your component or on the container element within your component?
If I want to return one of my components from a map, can I just do this?

```<code><Component data={data} key={`component-${data.id}`} />
</code>```

or, are you supposed to do something like this, within the component itself?

```<code>const Component = ({data}) => {
  return (
     <div key={`component-${data.id}`}>
     // Rest of component
     </div>
  )
}
</code>```

答:
Both approaches are fine they work both its your own personal preference honestly I think if you do it like the first example you won't get warnings  I assume you're trying something like this hope this clears it up if not let me know

```<code>return (
    <>
      {Dataa.map((data) =>
        <Component data={data} key=
        {`component-${data.id}`} />
      )}
    </>
  );
</code>```

Refer docs for further clarification:
https://reactjs.org/docs/lists-and-keys.html

Body:
If I want to return one of my components from a map, can I just do this?

<Component data={data} key={`component-${data.id}`} />

or, are you supposed to do something like this, within the component itself?

const Component = ({data}) => {
  return (
     <div key={`component-${data.id}`}>
     // Rest of component

  )
}

Body:
Both approaches are fine they work both its your own personal preference honestly I think if you do it like the first example you won't get warnings  I assume you're trying something like this hope this clears it up if not let me know

return (
    <>
      {Dataa.map((data) =>
        <Component data={data} key=
        {`component-${data.id}`} />
      )}
    </>
  );

Refer docs for further clarification:
https://reactjs.org/docs/lists-and-keys.html


问:
Watch change in nested property in Vue 3
I have created a Simple State Management with Reactivity API

My Store file looks like the following:

```<code>import { reactive, watch  } from "vue";

const state = reactive({
   form : {
    service_id : null
   }
})

 watch('state.form.service_id', (newVal, oldVal) => {
     console.log('service changed');
 }, { deep: true });

export default {
  state,
}
</code>```

I am trying to watch the change in state.form.service_id, but I am getting the following error:

[Vue warn]: Invalid watch source:  state.form.service_id A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types

If I replace the watch code with the following, then it works.

```<code> watch('state.form', (newVal, oldVal) => {
     console.log('form changed');
 }, { deep: true });
</code>```

But I need to watch for the change in state.form.service_id. Is there any solution?

答:
Try to use a getter function instead of the property path :

 watch(()=>state.form.service_id, (newVal, oldVal) => {
     console.log('service changed');
 }, { deep: true });

```

Body:
I have created a Simple State Management with Reactivity API

My Store file looks like the following:

import { reactive, watch  } from "vue";

const state = reactive({
   form : {
    service_id : null
   }
})

 watch('state.form.service_id', (newVal, oldVal) => {
     console.log('service changed');
 }, { deep: true });

export default {
  state,
}

I am trying to watch the change in state.form.service_id, but I am getting the following error:

[Vue warn]: Invalid watch source:  state.form.service_id A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types

If I replace the watch code with the following, then it works.

 watch('state.form', (newVal, oldVal) => {
     console.log('form changed');
 }, { deep: true });

But I need to watch for the change in state.form.service_id. Is there any solution?


问:
How to deserialize json date to java date (Using @JsonbDateFormat)
I have a problem where my program uses an API that sends the date in the format MMM d, YYYY, h:mm:ss a. And when it sends that date I get an error saying javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error: javax.json.bind.JsonbException: Unable to deserialize property 'create_time' because of: Error parsing class java.util.Date from value: Jan 1, 2022, 9:01:08 PM. Check your @JsonbDateFormat has all time units for class java.util.Date type, or consider using org.eclipse.yasson.YassonProperties#ZERO_TIME_PARSE_DEFAULTING.

I considered using yasson but it broke everything else .-.

    @POST
    @Path("example/thing")
    @Produces(MediaType.APPLICATION_JSON)
    public Response paypalWebhook(ExampleClass exampleClass) {
    // do stuff
}
```
<p>I get my json and transform it into an object</p>
<pre class="lang-java prettyprint-override"><code>public class ExampleClass implements Serializable {
    public String id;
    @JsonbDateFormat(value = "MMM d, YYYY, h:mm:ss a")
    public Date create_time;
}
</code>```

Btw I cant change the api nor can I change the way it is "given" to me.
This is the object, even with the annotation, nothing works.

** Edit: I am using the paypal api.

Example:

"create_time": "Jan 1, 2022, 9:01:08 PM"
```

答:
the month is not number but text.
you should use LLL instead of MMM
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html</p>

Body:
I have a problem where my program uses an API that sends the date in the format MMM d, YYYY, h:mm:ss a. And when it sends that date I get an error saying javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error: javax.json.bind.JsonbException: Unable to deserialize property 'create_time' because of: Error parsing class java.util.Date from value: Jan 1, 2022, 9:01:08 PM. Check your @JsonbDateFormat has all time units for class java.util.Date type, or consider using org.eclipse.yasson.YassonProperties#ZERO_TIME_PARSE_DEFAULTING.

I considered using yasson but it broke everything else .-.

    @POST
    @Path("example/thing")
    @Produces(MediaType.APPLICATION_JSON)
    public Response paypalWebhook(ExampleClass exampleClass) {
    // do stuff
}

I get my json and transform it into an object

public class ExampleClass implements Serializable {
    public String id;
    @JsonbDateFormat(value = "MMM d, YYYY, h:mm:ss a")
    public Date create_time;
}

Btw I cant change the api nor can I change the way it is "given" to me.
This is the object, even with the annotation, nothing works.

** Edit: I am using the paypal api.

Example:

"create_time": "Jan 1, 2022, 9:01:08 PM"


问:
How to combine array in php to dynamically?
I have code like this

```<code>$a =[
      [1,2],
      [4,6],
      [10,24]
    ];
</code>```

i want a output like this

```<code>    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )
</code>```

and i use code like this

```<code>print_r(array_merge($a[0],$a[1],$a[2]));
</code>```

if a have code like this and have more data

```<code>    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )
</code>```

writing like this is not good

```<code>print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));
</code>```

how to use array_merge in dinamic in there?

答:
Try:

```<code>function my_array_merge($array1, $array2) {
    foreach ($array2 as $key => $val) {
        if (is_array($val)) {
            $array1[$key] = my_array_merge($array1[$key], $array2[$key]);
        } else {
            if (is_numeric($key)) {
                $array1[] = $array2[$key];
            } else {
                $array1[$key] = $array2[$key];
            }
        }
    }
    return $array1;
}
</code>```

As far as I know, the above exactly works like array_merge(), but merges  arrays inside it:

```<code>$arr1 = array(array("a"));
$arr2 = array(array("b"));
</code>```

will become:

```<code>Array (
        [0] => Array (
                [0] => a
                [1] => b
        )
)
</code>```

Body:
I have code like this

$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this

    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this

print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data

    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )

writing like this is not good

print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there?

Body:
Try:

function my_array_merge($array1, $array2) {
    foreach ($array2 as $key => $val) {
        if (is_array($val)) {
            $array1[$key] = my_array_merge($array1[$key], $array2[$key]);
        } else {
            if (is_numeric($key)) {
                $array1[] = $array2[$key];
            } else {
                $array1[$key] = $array2[$key];
            }
        }
    }
    return $array1;
}

As far as I know, the above exactly works like array_merge(), but merges  arrays inside it:

$arr1 = array(array("a"));
$arr2 = array(array("b"));

will become:

Array (
        [0] => Array (
                [0] => a
                [1] => b
        )
)


问:
Grouped bar plot in ggplot
I have a survey file in which row are observation and column question.

Here are some fake data they look like:

```<code>People,Food,Music,People
P1,Very Bad,Bad,Good
P2,Good,Good,Very Bad
P3,Good,Bad,Good
P4,Good,Very Bad,Very Good
P5,Bad,Good,Very Good
P6,Bad,Good,Very Good
</code>```

My aim is to create this kind of plot with ggplot2.

I absolutely don't care of the colors, design, etc.

The plot doesn't correspond to the fake data

Here are my fake data:

```<code>raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
</code>```

But if I choose Y as count then I'm facing an issue about choosing the X and the Group values... I don't know if I can succeed without using reshape2... I've also tired to use reshape with melt function. But I don't understand how to use it...

答:
In @jakub's answer the calculations are done before the data is passed to ggplot(), which is why the stat in geom_bar is set to "identity" (i.e. take the data as is and do nothing with it).

Another approach is to let ggplot do the counting for you, hence we can make use of stat = "count", the default of geom_bar:

```<code>library(ggplot2)
ggplot(stack(df1[, -1]), aes(ind, fill = values)) +
         geom_bar(position = "dodge")
</code>```

data

```<code>df1 <- read.csv(text = "People,Food,Music,People
P1,Very Bad,Bad,Good
P2,Good,Good,Very Bad
P3,Good,Bad,Good
P4,Good,Very Bad,Very Good
P5,Bad,Good,Very Good
P6,Bad,Good,Very Good
P7,Bad,Very Bad,Good
P8,Very Good,Very Bad,Good
P9,Very Bad,Good,Bad
P10,Bad,Good,Very Bad
P11,Good,Bad,Very Bad
P12,Very Bad,Bad,Very Good
P13,Bad,Very Good,Bad
P14,Bad,Very Good,Very Bad
P15,Good,Good,Good
P16,Very Bad,Very Good,Very Bad
P17,Very Bad,Good,Good
P18,Very Bad,Very Bad,Bad
P19,Very Good,Very Bad,Very Bad
P20,Very Bad,Bad,Good", header = TRUE)
</code>```

Title: Grouped bar plot in ggplot

Body:
I have a survey file in which row are observation and column question.

Here are some fake data they look like:

People,Food,Music,People
P1,Very Bad,Bad,Good
P2,Good,Good,Very Bad
P3,Good,Bad,Good
P4,Good,Very Bad,Very Good
P5,Bad,Good,Very Good
P6,Bad,Good,Very Good

My aim is to create this kind of plot with ggplot2.

I absolutely don't care of the colors, design, etc.

The plot doesn't correspond to the fake data

Here are my fake data:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

But if I choose Y as count then I'm facing an issue about choosing the X and the Group values... I don't know if I can succeed without using reshape2... I've also tired to use reshape with melt function. But I don't understand how to use it...

Body:
In @jakub's answer the calculations are done before the data is passed to ggplot(), which is why the stat in geom_bar is set to "identity" (i.e. take the data as is and do nothing with it).

Another approach is to let ggplot do the counting for you, hence we can make use of stat = "count", the default of geom_bar:

library(ggplot2)
ggplot(stack(df1[, -1]), aes(ind, fill = values)) +
         geom_bar(position = "dodge")

data

df1 <- read.csv(text = "People,Food,Music,People
P1,Very Bad,Bad,Good
P2,Good,Good,Very Bad
P3,Good,Bad,Good
P4,Good,Very Bad,Very Good
P5,Bad,Good,Very Good
P6,Bad,Good,Very Good
P7,Bad,Very Bad,Good
P8,Very Good,Very Bad,Good
P9,Very Bad,Good,Bad
P10,Bad,Good,Very Bad
P11,Good,Bad,Very Bad
P12,Very Bad,Bad,Very Good
P13,Bad,Very Good,Bad
P14,Bad,Very Good,Very Bad
P15,Good,Good,Good
P16,Very Bad,Very Good,Very Bad
P17,Very Bad,Good,Good
P18,Very Bad,Very Bad,Bad
P19,Very Good,Very Bad,Very Bad
P20,Very Bad,Bad,Good", header = TRUE)


问:
SSL error: wrong version number. gsql -p postNum -d databaseName -r -U userName -h xx.xx.xx.xx
I try to connect remotely with a certificate. The database is up and running. But I get message:gsql: SSL error: wrong version number.
gsql -p postNum  -d databaseName -r -U userName -h xx.xx.xx.xx</p>

答:
Please check whether the following GUC parameters are correctly configured in postgresql.conf:

ssl: Enables SSL connections.

ssl_cert_file: Location of the SSL server certificate file.

ssl_key_file: Location of the SSL server private key file.

ssl_ca_file: Location of the SSL certificate authority file.

If only file names are set for the preceding files, the files must be stored in the data directory by default and the files permission must be set to 600.

After the preceding parameters are set, restart the database.


问:
Why can't I use a union type with redux connect?
Here's a short sample of what I'm trying to do:

```<code>import { connect } from "react-redux";

interface ErrorProps {
  error: true;
  description: string;
}

interface NoErrorProps {
  error: false;
}

type TestProps = ErrorProps | NoErrorProps;

function Test(props: TestProps) {
  return props.error ? <>Error: ${props.description}</> : <>OK</>;
}

// This is a test implementation that always returns no error
connect(() => ({ error: false }))(Test);

</code>```

However, I get an error:

```<code>Argument of type '(props: TestProps) => Element' is not assignable to parameter of type 'ComponentType<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>'.
  Type '(props: TestProps) => Element' is not assignable to type 'FunctionComponent<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>'.
    Types of parameters 'props' and 'props' are incompatible.
      Type 'PropsWithChildren<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>' is not assignable to type 'TestProps'.
        Type 'Matching<{ error: boolean; } & DispatchProp<AnyAction>, NoErrorProps> & { children?: ReactNode; }' is not assignable to type 'TestProps'.
          Type 'Matching<{ error: boolean; } & DispatchProp<AnyAction>, NoErrorProps> & { children?: ReactNode; }' is not assignable to type 'NoErrorProps'.
            Types of property 'error' are incompatible.
              Type 'boolean' is not assignable to type 'false'.
</code>```

Now, I have used algebraic data types for a long time and usually am pretty confident that I understand what I'm doing. But here I'll explain my reasoning in (probably) painfully obvious detail because I'm stumped and suspect that I misunderstand something very basic and fundamental.

I'm trying to decipher this error message, and while I'm not entirely sure what's happening on the left part of the type comparison (with Redux types), it seems that every line is a reason for the line before it. So, I look at these two lines, disregarding the types on the left:

```<code>   Type '...' is not assignable to type 'TestProps'.
     Type '...' is not assignable to type 'NoErrorProps'.
</code>```

And I notice that this means that whatever '...' means it does not change, so here I disregard it. But this sequence is not assignable to TestProps because it is not assignable to 'NoErrorProps'. Which means for something to be assignable TestProps, it must be assignable to NoErrorProps.

Which doesn't make any sense. I just checked that I'm still sane:

```<code>const _1: TestProps = { error: false };
const _2: TestProps = { error: true, description: "foo" };

</code>```

First variable is not assignable to ErrorProps, second is not assignable to NoErrorProps, but both are perfectly assignable to TestProps, because that's how union types work. Why do the lines in the error message above imply the opposite?

答:
I might be mistaken, but I think it is all about contravariance.

TS compiler complains that (props: TestProps) => Element is not assignable to (props: {error:boolean}) => Element.

More simple example:

type UnionFn = (props: TestProps) => Element;
type SingleFn = (props: { error: boolean }) => Element;

declare let unionFn: UnionFn;
declare let singleFn: SingleFn;

unionFn = singleFn; // ok
singleFn = unionFn; // error
```
<p>It might be strange, because <code>TestProps</code> is assignable to <code>{error: boolean}</code>:</p>
<pre class="lang-js prettyprint-override"><code>declare let union: Union;
declare let single: Single;

union = single // expected error
single = union; // ok
</code>```

However, when these types/values are in argument position, the arrow of inheritance turns into opposite way because arguments are in contravariant position. It means that singleFn is assignable to unionFn whereas unionFn is no more assignable to singleFn.

Hence, I think the issue is not in connect function typings.

More about *-variance you can find here

Here you can find my answer with more examples

Body:
Here's a short sample of what I'm trying to do:

import { connect } from "react-redux";

interface ErrorProps {
  error: true;
  description: string;
}

interface NoErrorProps {
  error: false;
}

type TestProps = ErrorProps | NoErrorProps;

function Test(props: TestProps) {
  return props.error ? <>Error: ${props.description}</> : <>OK</>;
}

// This is a test implementation that always returns no error
connect(() => ({ error: false }))(Test);

However, I get an error:

Argument of type '(props: TestProps) => Element' is not assignable to parameter of type 'ComponentType<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>'.
  Type '(props: TestProps) => Element' is not assignable to type 'FunctionComponent<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>'.
    Types of parameters 'props' and 'props' are incompatible.
      Type 'PropsWithChildren<Matching<{ error: boolean; } & DispatchProp<AnyAction>, TestProps>>' is not assignable to type 'TestProps'.
        Type 'Matching<{ error: boolean; } & DispatchProp<AnyAction>, NoErrorProps> & { children?: ReactNode; }' is not assignable to type 'TestProps'.
          Type 'Matching<{ error: boolean; } & DispatchProp<AnyAction>, NoErrorProps> & { children?: ReactNode; }' is not assignable to type 'NoErrorProps'.
            Types of property 'error' are incompatible.
              Type 'boolean' is not assignable to type 'false'.

Now, I have used algebraic data types for a long time and usually am pretty confident that I understand what I'm doing. But here I'll explain my reasoning in (probably) painfully obvious detail because I'm stumped and suspect that I misunderstand something very basic and fundamental.

I'm trying to decipher this error message, and while I'm not entirely sure what's happening on the left part of the type comparison (with Redux types), it seems that every line is a reason for the line before it. So, I look at these two lines, disregarding the types on the left:

   Type '...' is not assignable to type 'TestProps'.
     Type '...' is not assignable to type 'NoErrorProps'.

And I notice that this means that whatever '...' means it does not change, so here I disregard it. But this sequence is not assignable to TestProps because it is not assignable to 'NoErrorProps'. Which means for something to be assignable TestProps, it must be assignable to NoErrorProps.

Which doesn't make any sense. I just checked that I'm still sane:

const _1: TestProps = { error: false };
const _2: TestProps = { error: true, description: "foo" };

First variable is not assignable to ErrorProps, second is not assignable to NoErrorProps, but both are perfectly assignable to TestProps, because that's how union types work. Why do the lines in the error message above imply the opposite?

Body:
I might be mistaken, but I think it is all about contravariance.

TS compiler complains that (props: TestProps) => Element is not assignable to (props: {error:boolean}) => Element.

More simple example:

type UnionFn = (props: TestProps) => Element;
type SingleFn = (props: { error: boolean }) => Element;

declare let unionFn: UnionFn;
declare let singleFn: SingleFn;

unionFn = singleFn; // ok
singleFn = unionFn; // error

It might be strange, because TestProps is assignable to {error: boolean}:

declare let union: Union;
declare let single: Single;

union = single // expected error
single = union; // ok

However, when these types/values are in argument position, the arrow of inheritance turns into opposite way because arguments are in contravariant position. It means that singleFn is assignable to unionFn whereas unionFn is no more assignable to singleFn.

Hence, I think the issue is not in connect function typings.

More about *-variance you can find here

Here you can find my answer with more examples


问:
Adding new data based on maximum duplicates and number of minimum counts
```<code>import pandas as pd
data_list = [['Name', 'Fruit'],
              ['Abel', 'Apple'],
              ['Abel', 'Pear'],
              ['Abel', 'Coconut'],
              ['Abel', 'Pear'],
              ['Benny', 'Apple'],
              ['Benny', 'Apple'],
              ['Cain', 'Apple'],
              ['Cain', 'Coconut'],
              ['Cain', 'Pear'],
              ['Cain', 'Lemon'],
              ['Cain', 'Orange']]

record_df = pd.DataFrame(data_list[1:], columns = data_list[0])
record_df
</code>```

I am trying to create 2 extra data column in a pandas dataframe.

Count of the highest duplicate.

Count of fruits with the lowest duplicate.

So the end results would be

```<code>Name | Count of Highest Duplicate | Count of fruits with lowest duplicate
Abel | 2 | 2
Benny | 2 | 1
Cain | 1 | 5
</code>```

I have tried

```<code>record_df.groupby('Name')['Fruit'].nunique().reset_index()
</code>```

and

```<code>record_df.groupby('Name')['Fruit'].value_counts()
</code>```

but am unsure where to proceed from here.

答:
Use value_counts then groupby:

```<code>out = df.value_counts(['Name', 'Fruit']).groupby(level='Name') \
        .agg(**{'Count of Highest Duplicate': 'max',
                'Count of fruits with lowest duplicate': lambda x: sum(x==x.min())})
print(out)

# Output
       Count of Highest Duplicate  Count of fruits with lowest duplicate
Name
Abel                            2                                      2
Benny                           2                                      1
Cain                            1                                      5
</code>```

Body:
import pandas as pd
data_list = [['Name', 'Fruit'],
              ['Abel', 'Apple'],
              ['Abel', 'Pear'],
              ['Abel', 'Coconut'],
              ['Abel', 'Pear'],
              ['Benny', 'Apple'],
              ['Benny', 'Apple'],
              ['Cain', 'Apple'],
              ['Cain', 'Coconut'],
              ['Cain', 'Pear'],
              ['Cain', 'Lemon'],
              ['Cain', 'Orange']]

record_df = pd.DataFrame(data_list[1:], columns = data_list[0])
record_df

I am trying to create 2 extra data column in a pandas dataframe.

Count of the highest duplicate.

Count of fruits with the lowest duplicate.

So the end results would be

Name | Count of Highest Duplicate | Count of fruits with lowest duplicate
Abel | 2 | 2
Benny | 2 | 1
Cain | 1 | 5

I have tried

record_df.groupby('Name')['Fruit'].nunique().reset_index()

and

record_df.groupby('Name')['Fruit'].value_counts()

but am unsure where to proceed from here.

Body:
Use value_counts then groupby:

out = df.value_counts(['Name', 'Fruit']).groupby(level='Name') \
        .agg(**{'Count of Highest Duplicate': 'max',
                'Count of fruits with lowest duplicate': lambda x: sum(x==x.min())})
print(out)

# Output
       Count of Highest Duplicate  Count of fruits with lowest duplicate
Name
Abel                            2                                      2
Benny                           2                                      1
Cain                            1                                      5


问:
Is it possible to create a browser based html/javascript audio player, that handles most of the MPRIS commands?
I am trying to create a music player, that can handle most of the MPRIS commands.

During youtube is playing, playerctl list the firefox player (firefox.instance{id}), and if it has playlist then I can skip to previous / next item using $ playerctl -p firefox.instance{id} next. This works in chrome too.

I want to implement the same behavior in a React.js application, but first I'm looking for a html/javascript based solution.

One of my guesses that this is impossible (without using a browser add-on), because firefox implements this manually for each supported website.

Maybe I did something wrong, but no matter what I search for I couldn't find any information about this.

Thanks for reading / commenting!

答:
Media Session API seems to solve this problem pretty well: https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API

This event listener runs every time $ playerctl -p firefox.instance{id} next is run (or when any other MPRIS client calls 'next', like KDE connect on android):

```<code>  navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });
</code>```

It even works in chrome (except the skipad event). More information can be found on the MDN Web Docs 'Media Session API' page I linked above.

Body:
Media Session API seems to solve this problem pretty well: https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API

This event listener runs every time $ playerctl -p firefox.instance{id} next is run (or when any other MPRIS client calls 'next', like KDE connect on android):

  navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });

It even works in chrome (except the skipad event). More information can be found on the MDN Web Docs 'Media Session API' page I linked above.


问:
Use element to style inside

The emb is not a class but an element. Can I use this element to style the div or, the only way to do it is making emb a class such as .emb?

  Hello

```

答:
This is not how it works. You need to do e.g.:

  Hello

```

Title: Use element to style inside <div>

Body:
This is not how it works. You need to do e.g.:

<div class="emb">
  Hello
</div>

<style>
  .emb {
    font-weight: 500;
    font-style: italic;
    background: transparent;
    font-size: 18px
  }
</style>


问:
Java Preferences doesn't work in Windows 7
Recently I build an Java application. I use Java Preferences to store some information. When I ran my application in windows XP, the application run perfectly. I can store information and get the stored information. But when I ran it in Windows 7, Java Preference failed to store the information. Is there any solution?</p>

答: where do you have these properties files? Isn't the problem just with lack of permissions? I regularly code on Windows Vista and except for occasional problem with permissions everything works as it should. </p>


问:
Remove even numbers from a vector in c++
can somebody help me with this function: suppose that I need to remove all even numbers from a vector using reference: can I do that? Is the push_back correct or should I use something else?

void evenRemoe(vector<int>& arr) {
    for(int i = 0; i < arr.size(); i++) {
        if(arr[i] % 2 != 0) {
            push_back(arr[i]);
        }
    }
}
```

答:
From C++20 onwards you can use std::erase_if() , Prior to c++20 erase-remove idiom used to be the solution of this problem.

```<code>v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());
</code>```

Where is_even is a functor

Body:
From C++20 onwards you can use std::erase_if() , Prior to c++20 erase-remove idiom used to be the solution of this problem.

v.erase(std::remove_if(v.begin(), v.end(), is_even), v.end());

Where is_even is a functor


答:
You can use crosstab and standard operations:

```<code>df2 = pd.crosstab(record_df['Name'], record_df['Fruit'])
df2 = df2.where(df2.ne(0))

pd.DataFrame({'max': df2.max(axis=1),
              'count(min)': df2.eq(df2.min(axis=1), axis=0).sum(axis=1)},
             index=df2.index)
</code>```

output:

```<code>       max  count(min)
Name
Abel     2           2
Benny    2           1
Cain     1           5
</code>```

Title: Adding new data based on maximum duplicates and number of minimum counts

Body:
You can use crosstab and standard operations:

df2 = pd.crosstab(record_df['Name'], record_df['Fruit'])
df2 = df2.where(df2.ne(0))

pd.DataFrame({'max': df2.max(axis=1),
              'count(min)': df2.eq(df2.min(axis=1), axis=0).sum(axis=1)},
             index=df2.index)

output:

       max  count(min)
Name
Abel     2           2
Benny    2           1
Cain     1           5


问:
Camera calibration with single image? It seems to work, but am I missing something?
I have to do camera calibration. I understand the general concept and I have it working, but in many guides it says to use many images or at the very least two with different orientation. Why exactly is this necessary? I seem to be getting reasonably good results with a single image of 14x14 points:

I find the points with cv::findCirclesGrid and use cv::calibrateCamera to find the extrinsic and intrinsic parameters. Intrinsic guess is set to false. Principal point and aspect ratio are not fixed while tangential distortion is fixed to zero.

I then use cv::getOptimalNewCameraMatrix, cv::initUndistortRectifyMap and cv::remap to restore the image.

It seems to me the result is pretty good, but am I missing something? Is it actually wrong and just waiting to cause problems for me later?

Also before you ask why I don't just use multiple images to be sure; the software I am writing will be used with a semi-fixed camera stand to calibrate several cameras one at a time. So first off the stand would need to be modified in order to position the pattern at an angle or off centre, as currently it can only be moved closer or further away. Secondly the process should not be unnecessarily slowed down by having to capture more images.

Edit: To Micka asking "what happens if your viewing angle isnt 90° on the pattern? Can you try to rotate the pattern away from the camera?". I get a somewhat similar result, although it finds less distortion. From looking at the borders with a ruler it seems that the calibration from 90° is better, but it is really hard to tell.

答:
i check the paper , which opencv method using...that is zhangzhengyou's method.
that is n=1 , you can only get the focus .
in the paper , he says "

If n  3, we will have in general a unique solution b defined up to a
scale factor. If n à 2, we can impose the skewless constraint   à 0,
i.e., â0; 1; 0; 0; 0; 0äb à 0, which is added as an additional
equation to (9). (If n à 1, we can only solve two camera intrinsic
parameters, e.g.,   and  , assuming u0 and v0 are known (e.g., at the
image center) and   à 0, and that is indeed what we did in [19] for
head pose determination based on the fact that eyes and mouth are
reasonably coplanar. In fact, Tsai [23] already mentions that focal
length from one plane is possible, but incorrectly says that aspect
ratio is not.)  "


问:
type forward slash without using single quote, double quote and semi colon filter
ok, let me try a different approach.
I am not allowed to use either of the quotation  marks or semi colon.
I can get around to create a string by doing

```<code>let str=/^.i am a string$/
str = str.toString().slice(2, -2)
</code>```

however I have the following string

```<code>http://localhost:31337/?submit=
</code>```

because it has the / in them, I am unable to use the above method.
when I try to use /// represent 1 string, the server just chops everything and only keeps http:
I also tried to do just forward slash with

```<code>http:/\//glocalhost:31337/?submit=
</code>```

but it gives me an input error.
I thought ///g escaped forward slash.
Is there a way I can build the desired string?

答:
SOLVED:
I just needed to surround the string with []</p>

Body:
ok, let me try a different approach.
I am not allowed to use either of the quotation  marks or semi colon.
I can get around to create a string by doing

let str=/^.i am a string$/
str = str.toString().slice(2, -2)

however I have the following string

http://localhost:31337/?submit=

because it has the / in them, I am unable to use the above method.
when I try to use /// represent 1 string, the server just chops everything and only keeps http:
I also tried to do just forward slash with

http:/\//glocalhost:31337/?submit=

but it gives me an input error.
I thought ///g escaped forward slash.
Is there a way I can build the desired string?


问:
How to remove column row values from table according to another column with jquery
I have a question related to a dynamically mounted table.

So I wanted to know how I can edit the table removing values from rows according to values from another column with jquery? For example, I have the following table:

Start
End
balance
Trail
Id

01/11/2022
01/15/2022
4
high stretch
2

01/11/2022
01/15/2022
4
low stretch
2

01/25/2022
01/30/2022
6
high stretch
4

01/25/2022
01/30/2022
6
inert stretch
4

01/25/2022
01/30/2022
6
low stretch
4

Given this table, I wanted to do a merge based on the Id column, removing the balance values, as they are repeated for the same Id and in the end make the sum, returning the balance total.

So the new table would look like this:

Start
End
balance
Trail
Id

01/11/2022
01/15/2022
4
high stretch
2

01/11/2022
01/15/2022

low stretch
2

01/25/2022
01/30/2022
6
high stretch
4

01/25/2022
01/30/2022

inert stretch
4

01/25/2022
01/30/2022

low stretch
4

Total

10

Any idea how I can do this with jquery?

An important detail, this table is dynamically generated, so I can have more rows being generated with other values from other Ids or the same Id.

答:
function sumBalance(){
  var table = document.getElementById("balanceTbl");
  var tbody = table.tBodies[0];
  var tr = table.tBodies[0].rows;
  var totalBal = 0;
  for(i=0; i < tr.length;i++){
    var balance = tbody.rows[i].cells[2].children[0].value;
    totalBal += Number(balance);
  }
  document.getElementById("total").innerHTML = totalBal;
}
sumBalance();

document.querySelectorAll("input[name=balance]").forEach(function(balanceElem,pos){
  balanceElem.addEventListener("input",function(){
    sumBalance();
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}</code>```

Start
End
balance
Trail
Id

01/11/2022
01/15/2022
<input type="text" name="balance" value="4" size="2">
high stretch
2

01/11/2022
01/15/2022
<input type="text" name="balance" value="4" size="2">
low stretch
2

01/25/2022
01/30/2022
<input type="text" name="balance" value="6" size="2">
high stretch
4

01/25/2022
01/30/2022
<input type="text" name="balance" value="6" size="2">
inert stretch
4

01/25/2022
01/30/2022
<input type="text" name="balance" value="6" size="2">
low stretch
4

Total

```

Don't use id, because in HTML id should be unique between each element, Instead of ID use either name or class. Try to change the balance and see the total. Hope this sample will help. Thanks

Body:
function sumBalance(){
  var table = document.getElementById("balanceTbl");
  var tbody = table.tBodies[0];
  var tr = table.tBodies[0].rows;
  var totalBal = 0;
  for(i=0; i < tr.length;i++){
    var balance = tbody.rows[i].cells[2].children[0].value;
    totalBal += Number(balance);
  }
  document.getElementById("total").innerHTML = totalBal;
}
sumBalance();

document.querySelectorAll("input[name=balance]").forEach(function(balanceElem,pos){
  balanceElem.addEventListener("input",function(){
    sumBalance();
  })
})

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

<table id="balanceTbl">
<thead>
<tr>
<th>Start</th>
<th>End</th>
<th>balance</th>
<th>Trail</th>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr>
<td>01/11/2022</td>
<td>01/15/2022</td>
<td><input type="text" name="balance" value="4" size="2"></td>
<td>high stretch</td>
<td>2</td>
</tr>
<tr>
<td>01/11/2022</td>
<td>01/15/2022</td>
<td><input type="text" name="balance" value="4" size="2"></td>
<td>low stretch</td>
<td>2</td>
</tr>
<tr>
<td>01/25/2022</td>
<td>01/30/2022</td>
<td><input type="text" name="balance" value="6" size="2"></td>
<td>high stretch</td>
<td>4</td>
</tr>
<tr>
<td>01/25/2022</td>
<td>01/30/2022</td>
<td><input type="text" name="balance" value="6" size="2"></td>
<td>inert stretch</td>
<td>4</td>
</tr>
<tr>
<td>01/25/2022</td>
<td>01/30/2022</td>
<td><input type="text" name="balance" value="6" size="2"></td>
<td>low stretch</td>
<td>4</td>
</tr>
</tbody>
<tfoot>
<td>Total</td>
<td></td>
<td id="total"></td>
<td></td>
<td></td>
</tfoot>
</table>

Don't use id, because in HTML id should be unique between each element, Instead of ID use either name or class. Try to change the balance and see the total. Hope this sample will help. Thanks


问:
How Can I Split string every nth character, And Display like This?
I want to print the following string:

```<code>1234567890
</code>```

as follows:

```<code>123
456
789
0
</code>```

How can I do this in Python?

答:
You could use re.findall here:

inp = '1234567890'
output = '\n'.join(re.findall(r'.{1,3}', inp))
print(output)
```
<p>This prints:</p>
```123
456
789
0
```

Body:
I want to print the following string:

1234567890

as follows:

123
456
789
0

How can I do this in Python?

Body:
You could use re.findall here:

inp = '1234567890'
output = '\n'.join(re.findall(r'.{1,3}', inp))
print(output)

This prints:

123
456
789
0


问:
How to update the entire div after deleting each row?
I wrote a simple table, and in each row I'll update the div tag.

As you can see, each row contains two parts that are separated by :, and each part in my array separated by |.

so the output is something like this :

|3:Apple|5:Orange|1:Lemon

I'm very rookie in JS,So if you answer these two questions, I will be grateful.

How can I update the entire div after deleting each row?

According to the code I wrote(Just JS), do you suggest a shorter and cleaner way to update the div?
I feel that the code I wrote is very spaghetti.

$('.add-row').click(function() {
  row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
});
$(document).on('change', 'input[name="prodKind"]', function() {
  mainArr = [];
  var mainTable = $(this).closest('table');
  var tr = mainTable.find('tr');
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      tmpArr.push(values);
    });
    mainArr.push(tmpArr.join(":"));
  });
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').html(mainArr.join("|"));
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').trigger('blur');

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
<tr>
  <td>
<table>
  <tr>
<td>
  <table class='table tablemain' border=1>
    <tr>
      <td>number</td>
      <td>item</td>
      <td><span class="add-row font-icon-plus-sign">add</span></td>
    </tr>
  </table>
  <div class='kind-out'></div>
</td>
  </tr>
</table>
  </td>
</tr>
</table></code>```

答:
Make simpler functions to solve your issues
Also simplify the paths to the siblings

const row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";

const getValues = $table => $table.find('tr').map(function() {
  return $(this).find('.product_kind input').map(function() {
    return this.value
  }).get().join(":")
}).get().join("|");

const update = $mainTable => $mainTable
  .next('.kind-out')
  .html(getValues($mainTable));

$(document).on('change', 'input[name="prodKind"]', function() {
  const $mainTable = $(this).closest('.tablemain');
  update($mainTable)
});
$('.add-row').on('click', function() {
  $(this).closest('tbody').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  const $table = $(this).closest('.tablemain'); // must save before remove
  $(this).closest('tr').remove();
  update($table)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <table>
        <tr>
          <td>
            <table class='table tablemain' border=1>
              <tr>
                <td>number</td>
                <td>item</td>
                <td><span class="add-row font-icon-plus-sign">add</span></td>
              </tr>
            </table>
            <div class='kind-out'></div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table></code>```

Body:
I wrote a simple table, and in each row I'll update the div tag.

As you can see, each row contains two parts that are separated by :, and each part in my array separated by |.

so the output is something like this :

|3:Apple|5:Orange|1:Lemon

I'm very rookie in JS,So if you answer these two questions, I will be grateful.

How can I update the entire div after deleting each row?

According to the code I wrote(Just JS), do you suggest a shorter and cleaner way to update the div?
I feel that the code I wrote is very spaghetti.

$('.add-row').click(function() {
  row = "
<input type='number' name='prodKind' placeholder='number' />	<input dir='rtl' type='text' name='prodKind' placeholder='item' />	del
";
  $(this).closest('table').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  $(this).closest('tr').remove();
});
$(document).on('change', 'input[name="prodKind"]', function() {
  mainArr = [];
  var mainTable = $(this).closest('table');
  var tr = mainTable.find('tr');
  tr.each(function() {
    tmpArr = [];
    $(this).find('.product_kind').each(function() {
      var values = $(this).find('input').val();
      tmpArr.push(values);
    });
    mainArr.push(tmpArr.join(":"));
  });
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').html(mainArr.join("|"));
  $(this).parent().parent().parent().parent().closest('td').children('.kind-out').trigger('blur');

});

      number
      item
      add

Body:
Make simpler functions to solve your issues
Also simplify the paths to the siblings

const row = "<tr class='prod-row'><td class='product_kind'><input type='number' name='prodKind' placeholder='number' /></td><td class='product_kind'><input dir='rtl' type='text' name='prodKind' placeholder='item' /></td><td><span class='del-row font-icon-minus-sign'>del</span></td></tr>";

const getValues = $table => $table.find('tr').map(function() {
  return $(this).find('.product_kind input').map(function() {
    return this.value
  }).get().join(":")
}).get().join("|");

const update = $mainTable => $mainTable
  .next('.kind-out')
  .html(getValues($mainTable));

$(document).on('change', 'input[name="prodKind"]', function() {
  const $mainTable = $(this).closest('.tablemain');
  update($mainTable)
});
$('.add-row').on('click', function() {
  $(this).closest('tbody').append(row);
});
$('table').on('click', 'td span.del-row', function(e) {
  const $table = $(this).closest('.tablemain'); // must save before remove
  $(this).closest('tr').remove();
  update($table)
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <table>
        <tr>
          <td>
            <table class='table tablemain' border=1>
              <tr>
                <td>number</td>
                <td>item</td>
                <td><span class="add-row font-icon-plus-sign">add</span></td>
              </tr>
            </table>
            <div class='kind-out'></div>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>


问:
How to get week number of month for any given date on snowflake SQL
I'm trying to extract the week number of the month for any given date. If the month starts on a Saturday, it should be labelled 0. Thereafter, the weeks will be labelled 1, 2, 3, ...

For example, for Jan 2022, 1st Jan is Week 0, 2nd Jan is Week 1, 9th Jan is Week 2, 16 Jan is Week 3, 23 Jan is Week 4, and 30th Jan is Week 4.

I tried converting some MS SQL & TSQL codes from other Stack Overflow questions but it did not work on Snowflake.

I guess the alternative is to hardcode using Sunday dates but the code is far too long and has too many conditions. Hoping for a shorter, cleaner code using Snowflake's inbuilt SQL functions.

答:
You have to deal with the WEEK_START and WEEK_OF_YEAR_POLICY parameters.
The calculation should not be complicated, see my example (unfortunately you did not enter when your week start):

SHOW PARAMETERS LIKE 'WEEK%';
ALTER SESSION SET WEEK_OF_YEAR_POLICY=1, WEEK_START=7;

WITH sample_dates AS (
  SELECT DATEADD('DAY', SEQ4(), '2022-01-01 00:00:00'::timestamp) AS dt
    FROM TABLE(GENERATOR(ROWCOUNT => 365)) AS t
)
SELECT DATE(dt) AS "DATE"
     , DAYOFYEAR(dt) AS "DAY OF YEAR"
     , DAYOFMONTH(dt) AS "DAY OF MONTH"
     , DAYOFWEEK(dt) AS "DAY OF WEEK"
     , DAYNAME(dt) AS "DAY NAME"
     , WEEK(dt) AS "WEEK"
     , WEEKISO(dt) AS "WEEK ISO"
     , WEEKOFYEAR(dt) AS "WEEK OF YEAR"
     , IFF(DAYNAME(DATE_TRUNC("YEAR", dt)) = 'Sat', WEEK(dt) - 1, WEEK(dt)) AS "CALC_DATE"
     , IFF(DAYOFMONTH(dt) = 1 AND DAYNAME(dt) = 'Sat', 0, FLOOR((DAY(dt)+6.1)/7,0)) AS "WEEK OF MONTH"
  FROM sample_dates;
```


答:
try this:</p>
```<code>x = "1234567890"
n = 3

y = list([x[i:i+n] for i in range(0, len(x), n)])

for chunk in y:
    print(chunk)
</code>```

Title: How Can I Split string every nth character, And Display like This?

Body:
try this:

x = "1234567890"
n = 3

y = list([x[i:i+n] for i in range(0, len(x), n)])

for chunk in y:
    print(chunk)


问:
So set grid rows/columns to default filling?
When I create grid with row or column, if I don't specify width/height, column/row adjust it's height/width to it's content like this:

```<code>    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Button Content="TestBtn"
                Height="50"
                Width="100"/>

    </Grid>
</code>```

Row set it's height to 50.

Question: How to return row/column to that default behavior after custom setting the width/height in code? Like this:

```<code>    public void SetRowHeight(double height, bool setDefault)
    {
        if (setDefault)
        {
            Grid0Row1.DefaultHeightBehaivor = true;
        }
        else
        {
            Grid0Row1.Height = new GridLength(Height);
        }
    }
</code>```

答:
For that, you need to use new GridLength() with empty parameters and code will look like this:

```<code>public void SetRowHeight(double height, bool setDefault)
{
    if (setDefault)
    {
        Grid0Row1.Height = new GridLength();
    }
    else
    {
        Grid0Row1.Height = new GridLength(height);
    }
}
</code>```

Body:
When I create grid with row or column, if I don't specify width/height, column/row adjust it's height/width to it's content like this:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Button Content="TestBtn"
                Height="50"
                Width="100"/>

    </Grid>

Row set it's height to 50.

Question: How to return row/column to that default behavior after custom setting the width/height in code? Like this:

    public void SetRowHeight(double height, bool setDefault)
    {
        if (setDefault)
        {
            Grid0Row1.DefaultHeightBehaivor = true;
        }
        else
        {
            Grid0Row1.Height = new GridLength(Height);
        }
    }

Body:
For that, you need to use new GridLength() with empty parameters and code will look like this:

public void SetRowHeight(double height, bool setDefault)
{
    if (setDefault)
    {
        Grid0Row1.Height = new GridLength();
    }
    else
    {
        Grid0Row1.Height = new GridLength(height);
    }
}


问:
When is context.Result null inside of an action filter .NET?
I noticed in ASP.NET Core MVC ModelStateInvalidFilter checks if Context.Result == null before checking ModelState.IsValid? What's the reason?

答:
The answer in the Result property description comment in the ActionExecutingContext.cs:

Gets or sets the IActionResult to execute. Setting Result to a
non-null value inside an action filter will short-circuit the action
and any remaining action filters.

This means if the short-circuit of the action already initiated there is no reason to overwrite the previous value in case the context.ModelState.IsValid set to false. It would be wrong approach.


问:
animation: make water wave
I would like to build a simple animation for a school project.

I want to make water wave within a box in such a way that tilting the device causes the water to wave in a direction rather the other.

Is there a sample from where I can start to create such effect? Any help is super appreciated.

Thx,
mE

答: Use Lottie animation. That's so simple way to implement with some lines of code.</p>

ContentLicense: CC BY-SA 2.5

Title: animation: make water wave


问:
SocketException: Failed host lookup: ‘...com’ (OS Error: nodename nor servname provided, or not known, errno = 8)
We are in a situation where the production app is facing the following socket exception and not able to perform any other network operation after this.

```<code>DioError [DioErrorType.DEFAULT]: SocketException: Failed host lookup: ‘xyz.abc.com’ (OS Error: nodename nor servname provided, or not known, errno = 8)
</code>```

Note: Encountered repetitively with one user having iPhone X, iOS 14.4

We are using Dio as a network client, with Retrofit, which internally uses the HttpClient from the dart. With Dio the exception is not reproducible with the simulated environment but using HttpClient directly, the same exception can be reproduced with the following code in iOS simulator.

```<code>HttpClient userAgent = new HttpClient();
  bool run = true;
  while (run) {
    try {
      await userAgent.getUrl(Uri.parse('https://www.google.com'));
      print('Number of api executed');
    } catch (e) {
      print(e);
      if (e is SocketException) {
        if ((e as SocketException).osError.errorCode == 8)
          print('***** Exception Caught *****');
      }
    }
  }
</code>```

Once the exception was thrown, the HttpClient was not able to recover from that stale state and all other API requests were started failing with the same error.

We were able to recover from that stale state by force closing all the previous connections and opening up a new HttpClient.

```<code>  HttpClient userAgent = new HttpClient();
  bool run = true;
  while (run) {
    try {
      await userAgent.getUrl(Uri.parse('https://www.google.com'));
      print('Number of api executed');
    } catch (e) {
      print(e);

      if (e is SocketException) {
        if ((e as SocketException).osError.errorCode == 8)
          print('***** Exception Caught *****');
      }
      userAgent.close(force: true);
      print('Force closing previous connections');
      userAgent = HttpClient();
      print('Creating new HttpClient instance');
    }
  }
</code>```

One interesting fact is after every 236 requests the exception is raising. It could be because of file descriptors over usage but iOS has a limit of 256.

With a stable internet connection, this issue reproducible every time in iOS simulator.

Although I am not able to reproduce the issue with Dio client but as in production it is occurring. So I am seeking help to understand the root cause of this issue, also how we can prevent it?

Anyone who has come across this kind of situation and how you have overcome it, please help me.

Thanks in advance.

答:
i have same issue resolve with this code:-

Exmaple

```<code>//Add This Class
    class MyHttpOverrides extends HttpOverrides{
      @override
      HttpClient createHttpClient(SecurityContext? context){
        return super.createHttpClient(context)
          ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
      }
    }

    Future<void> main() async {
      HttpOverrides.global = MyHttpOverrides();      //call here
      runApp(const MyApp());
    }
</code>```

Body:
We are in a situation where the production app is facing the following socket exception and not able to perform any other network operation after this.

DioError [DioErrorType.DEFAULT]: SocketException: Failed host lookup: ‘xyz.abc.com’ (OS Error: nodename nor servname provided, or not known, errno = 8)

Note: Encountered repetitively with one user having iPhone X, iOS 14.4

We are using Dio as a network client, with Retrofit, which internally uses the HttpClient from the dart. With Dio the exception is not reproducible with the simulated environment but using HttpClient directly, the same exception can be reproduced with the following code in iOS simulator.

HttpClient userAgent = new HttpClient();
  bool run = true;
  while (run) {
    try {
      await userAgent.getUrl(Uri.parse('https://www.google.com'));
      print('Number of api executed');
    } catch (e) {
      print(e);
      if (e is SocketException) {
        if ((e as SocketException).osError.errorCode == 8)
          print('***** Exception Caught *****');
      }
    }
  }

Once the exception was thrown, the HttpClient was not able to recover from that stale state and all other API requests were started failing with the same error.

We were able to recover from that stale state by force closing all the previous connections and opening up a new HttpClient.

  HttpClient userAgent = new HttpClient();
  bool run = true;
  while (run) {
    try {
      await userAgent.getUrl(Uri.parse('https://www.google.com'));
      print('Number of api executed');
    } catch (e) {
      print(e);

      if (e is SocketException) {
        if ((e as SocketException).osError.errorCode == 8)
          print('***** Exception Caught *****');
      }
      userAgent.close(force: true);
      print('Force closing previous connections');
      userAgent = HttpClient();
      print('Creating new HttpClient instance');
    }
  }

One interesting fact is after every 236 requests the exception is raising. It could be because of file descriptors over usage but iOS has a limit of 256.

With a stable internet connection, this issue reproducible every time in iOS simulator.

Although I am not able to reproduce the issue with Dio client but as in production it is occurring. So I am seeking help to understand the root cause of this issue, also how we can prevent it?

Anyone who has come across this kind of situation and how you have overcome it, please help me.

Thanks in advance.

Body:
i have same issue resolve with this code:-

Exmaple

//Add This Class
    class MyHttpOverrides extends HttpOverrides{
      @override
      HttpClient createHttpClient(SecurityContext? context){
        return super.createHttpClient(context)
          ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
      }
    }

    Future<void> main() async {
      HttpOverrides.global = MyHttpOverrides();      //call here
      runApp(const MyApp());
    }


问:
jinja 2 nested dictionaries to yaml
I'm trying to use jinja2 to output a nested dictionary to a yaml file. However I'm not sure how to access the nested dicts.
With a flat dict for data I can use the below.

```<code> - request:
        path: {{ path }}
        headers:
          origin: 'somedomain.com'
          user-agent: 'agent'
          referer: 'some.domain.com'
          authority: 'somedomain.com'
        data:
          {% for key, value in data.items() -%}
          {{ key }}: '{{ value }}'
          {%- endfor %}
      response:
        content:
          file: {{ content }}
</code>```

However with a nested dict like below how do I achieve the output at the bottom?

```<code>{'toplevelkey1': {'nestedkey1': 'value1', 'nestedkey2': 123, 'nestedkey3': '55',
                 'nestedkey4': 1560}, 'toplevelkey34': 'df',
 'toplevelkey2': {'somekey12': 68, 'somekey58': False, 'somekey48': 3, 'somekey38': 'ADF',
                              'somekey39': 'St'}, 'toplevel34': 'T',
 'toplevel8': {'key33': 68, 'key94': 3, 'key83': 'T', 'key84': 'dog'}}
</code>```

Required output

```<code>   - request:
    path: /some/path
    headers:
      origin: 'somedomain.com'
      user-agent: 'agent'
      referer: 'somedomain.com'
      authority: 'somedomain.com'
    data:
      toplevelkey1:
        nestedkey1: 'value1'
        nestedkey2: '123
        ....      : ....
      toplevel34: 'T'
      toplevelkey2:
        'somekey12': 68
         .....     :  .....
  response:
    content:
      file: address.json
</code>```

答:
There is a somewhat smaller and more general solution:

```<code># License: public-domain
import yaml # This is pyyaml

def yaml_pretty(d, indent=10):
    dump = yaml.dump(d)
    res = ""
    for line in dump.split("\n"):
        res += " " * indent + line + "\n"
    return res
</code>```

This handles all types, e.g. also (nested) lists.

Title: jinja 2 nested dictionaries to yaml

Body:
I'm trying to use jinja2 to output a nested dictionary to a yaml file. However I'm not sure how to access the nested dicts.
With a flat dict for data I can use the below.

 - request:
        path: {{ path }}
        headers:
          origin: 'somedomain.com'
          user-agent: 'agent'
          referer: 'some.domain.com'
          authority: 'somedomain.com'
        data:
          {% for key, value in data.items() -%}
          {{ key }}: '{{ value }}'
          {%- endfor %}
      response:
        content:
          file: {{ content }}

However with a nested dict like below how do I achieve the output at the bottom?

{'toplevelkey1': {'nestedkey1': 'value1', 'nestedkey2': 123, 'nestedkey3': '55',
                 'nestedkey4': 1560}, 'toplevelkey34': 'df',
 'toplevelkey2': {'somekey12': 68, 'somekey58': False, 'somekey48': 3, 'somekey38': 'ADF',
                              'somekey39': 'St'}, 'toplevel34': 'T',
 'toplevel8': {'key33': 68, 'key94': 3, 'key83': 'T', 'key84': 'dog'}}

Required output

   - request:
    path: /some/path
    headers:
      origin: 'somedomain.com'
      user-agent: 'agent'
      referer: 'somedomain.com'
      authority: 'somedomain.com'
    data:
      toplevelkey1:
        nestedkey1: 'value1'
        nestedkey2: '123
        ....      : ....
      toplevel34: 'T'
      toplevelkey2:
        'somekey12': 68
         .....     :  .....
  response:
    content:
      file: address.json

Body:
There is a somewhat smaller and more general solution:

# License: public-domain
import yaml # This is pyyaml

def yaml_pretty(d, indent=10):
    dump = yaml.dump(d)
    res = ""
    for line in dump.split("\n"):
        res += " " * indent + line + "\n"
    return res

This handles all types, e.g. also (nested) lists.


问:
How can I use wrapped Groovy shell inside the groovy script?
I have a Java app through which I'm executing a Groovy Script, the problem occurs when my Script again has code to use the groovy shell to execute the Inner script.

something like this

```<code>import com.xx.WrappedGroovyShell
import java.lang.*

def scriptString = """
def test(str) {
   str.toLowerCase() // This doesn't work as GString can't seem to be treated as a String
}
"""

try {

def script =  WrappedGroovyShell.getInstance().getScript("Test1", scriptString)
def script2 =  new GroovyShell().parse(scriptString)

def example = 1
  def gstring = "OUR VALUE IS ${example}";
       println script instanceof GroovyObject // Statement returning false
       println script.test(gstring) // This throws an exception groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.runtime.GStringImpl.toLowerCase() is applicable for argument types: () values: []

       println script2 instanceof GroovyObject // Statement returns true
       println script2.test(gstring) //this one works

    println "Success"
} catch (ex) {
    println ex
}

return 0
</code>```

The getScript method in WrappedGroovyShell.java is as simple as

```<code>public Script getScript(String scriptName, String scriptBody){
  return new GroovyShell().parse(scriptBody);
}
</code>```

I will be thankful if someone let me know why two different behavior.

答:
new GroovyShell() creates a new groovy classloader with parent = GroovyShell.class.getClassLoader()

and if GString.class is unknown for parent classloader - then it will be loaded again.

two GString classes loaded by different classloaders are not equal that's why you could have unexpected exceptions like "method not found for parameter GString" or "can't cast GString to GString"

this code should work because it uses classloader of current groovy class

```<code>def scriptText='''
def test(str) {
   str.toLowerCase()
}
'''

def gs = new GroovyShell(this.getClass().getClassLoader())
def script = gs.parse(scriptText)

def arg = "GSTRING ${123}"
println script.test(arg)
</code>```

Body:
I have a Java app through which I'm executing a Groovy Script, the problem occurs when my Script again has code to use the groovy shell to execute the Inner script.

something like this

import com.xx.WrappedGroovyShell
import java.lang.*

def scriptString = """
def test(str) {
   str.toLowerCase() // This doesn't work as GString can't seem to be treated as a String
}
"""

try {

def script =  WrappedGroovyShell.getInstance().getScript("Test1", scriptString)
def script2 =  new GroovyShell().parse(scriptString)

def example = 1
  def gstring = "OUR VALUE IS ${example}";
       println script instanceof GroovyObject // Statement returning false
       println script.test(gstring) // This throws an exception groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.runtime.GStringImpl.toLowerCase() is applicable for argument types: () values: []

       println script2 instanceof GroovyObject // Statement returns true
       println script2.test(gstring) //this one works

    println "Success"
} catch (ex) {
    println ex
}

return 0

The getScript method in WrappedGroovyShell.java is as simple as

public Script getScript(String scriptName, String scriptBody){
  return new GroovyShell().parse(scriptBody);
}

I will be thankful if someone let me know why two different behavior.

Body:
new GroovyShell() creates a new groovy classloader with parent = GroovyShell.class.getClassLoader()

and if GString.class is unknown for parent classloader - then it will be loaded again.

two GString classes loaded by different classloaders are not equal that's why you could have unexpected exceptions like "method not found for parameter GString" or "can't cast GString to GString"

this code should work because it uses classloader of current groovy class

def scriptText='''
def test(str) {
   str.toLowerCase()
}
'''

def gs = new GroovyShell(this.getClass().getClassLoader())
def script = gs.parse(scriptText)

def arg = "GSTRING ${123}"
println script.test(arg)