问:
IIS 2019: The request was aborted: Could not create SSL/TLS secure channel
I've seen others post similar issues and go down the route of using the following code snippet

```<code>            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls12 |

</code>```

However, I'm still having issues with the following scenario.

I have a Web App running on IIS on Windows Server (An EC2 Instance Win 2019 Server) and a Microservice running on Kestrel.  If I RDP to the Win Server and open up Chrome/Firefox/Edge I can navigate to the micro-service, make a basic API call and see data come back.   However, when the IIS application tries to access the the API I get the following error in my logs

```<code>      InnerException:
</code>```

```<code>        >       Type:       HttpRequestException
        >       Message:    An error occurred while sending the request.
        >       Data:       0 entries
        >       Stack trace:
</code>```

```<code>              ----------------
              InnerException:

                      Type:       WebException
                      Message:    The request was aborted: Could not create SSL/TLS secure >channel.
                      Data:       0 entries
                      Stack trace:
</code>```

```<code>at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
                        InnerException is null
</code>```

The certificate is valid/trusted/secured.  So there's no issue there.

I'm assuming that when the request goes from the Web App in IIS and tries to reach out to the API, it doesn't like something?   Is there a way to get further info on why I'm getting the exception(s)

答:
Looks like this was the answer
https://trailheadtechnology.com/solving-could-not-create-ssl-tls-secure-channel-error-in-net-4-6-x/

I hope this saves someone some time and headaches

Body:
I've seen others post similar issues and go down the route of using the following code snippet

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls12 |

However, I'm still having issues with the following scenario.

I have a Web App running on IIS on Windows Server (An EC2 Instance Win 2019 Server) and a Microservice running on Kestrel.  If I RDP to the Win Server and open up Chrome/Firefox/Edge I can navigate to the micro-service, make a basic API call and see data come back.   However, when the IIS application tries to access the the API I get the following error in my logs

      InnerException:

        >       Type:       HttpRequestException
        >       Message:    An error occurred while sending the request.
        >       Data:       0 entries
        >       Stack trace:

              ----------------
              InnerException:

                      Type:       WebException
                      Message:    The request was aborted: Could not create SSL/TLS secure >channel.
                      Data:       0 entries
                      Stack trace:

at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
                        InnerException is null

The certificate is valid/trusted/secured.  So there's no issue there.

I'm assuming that when the request goes from the Web App in IIS and tries to reach out to the API, it doesn't like something?   Is there a way to get further info on why I'm getting the exception(s)


来源: stackexchange

问:
How to use nested arrays in props in vue3?
I'm using SFC and a setup script with Vue3 (and typescript), and I can't seem to create a prop that's a nested array:</p>
```<code>const props = defineProps({
    title: String,
    desc: String,
    columns: Array<Array<String>>,
});
</code>```

答:
The answer is in https://vuejs.org/api/sfc-script-setup.html#typescript-only-features

The syntax for typescript is different:

const props = defineProps<{
  foo: string
  bar?: number
}>()
```

ContentLicense: CC BY-SA 4.0

Body:
I'm using SFC and a setup script with Vue3 (and typescript), and I can't seem to create a prop that's a nested array:

const props = defineProps({
    title: String,
    desc: String,
    columns: Array<Array<String>>,
});


问:
How to show thousand in k format for bar values in chart.js
I have many bars with a thousand values like 35000, 12000, and 76560. So these values are getting overlapped with each other. I need to change Bar values not StepSize.

I want to show these values 35k, 12k and 76.5k format. This is my code

```<code>public barStatus() {
  var colors = ['#299DFF', '#80FFFF', '#F8362B', ];
  var chBar = document.getElementById("chBar");
  var chartData = {
    datasets: [{
      label: 'Success',
      data: [35000, 12000, 76560],
      backgroundColor: colors[0]
    }, ]
  }
  var barOptions_stacked = {
    onClick: this.Status,
    tooltips: {
      enabled: true
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'left',
        formatter: Math.round,
        font: {
          color: 'black'
        }
      },
    },
    hover: {
      animationDuration: 0
    },
    scales: {
      xAxes: [{
          barPercentage: 0.5,
          categoryPercentage: 0.5
        }
      ],
      yAxes: [{
        gridLines: {
          display: false
        },
        type: 'logarithmic',
        position: 'left',
        ticks: {
          min: 0, //minimum tick
          max: 100000, //maximum tick
          callback: function (value, index, values) {
            return Number(value.toString()); //pass tick values as a string into Number function
          }
        },
        afterBuildTicks: function (chartObj) { //Build ticks labelling as per your need
          chartObj.ticks = [];
          chartObj.ticks.push(0);
          chartObj.ticks.push(10);
          chartObj.ticks.push(100);
          chartObj.ticks.push(1000);
          chartObj.ticks.push(10000);
          chartObj.ticks.push(100000);
        },
        scaleLabel: {
          display: false
        },
        stacked: false
      }]
    },
  };
  this.Canvas = document.getElementById("chBar");
  this.chart = new Chart(this.Canvas, {
    type: "bar",
    data: chartData,
    options: barOptions_stacked
  });
}
</code>```

How can I do that?

Screenshot:

答: I have found the solution (just now). In config option its will have animation and call back with function onComplete. Here you can draw the label with any format you want. Please see this picture for code

Body:
I have many bars with a thousand values like 35000, 12000, and 76560. So these values are getting overlapped with each other. I need to change Bar values not StepSize.

I want to show these values 35k, 12k and 76.5k format. This is my code

public barStatus() {
  var colors = ['#299DFF', '#80FFFF', '#F8362B', ];
  var chBar = document.getElementById("chBar");
  var chartData = {
    datasets: [{
      label: 'Success',
      data: [35000, 12000, 76560],
      backgroundColor: colors[0]
    }, ]
  }
  var barOptions_stacked = {
    onClick: this.Status,
    tooltips: {
      enabled: true
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'left',
        formatter: Math.round,
        font: {
          color: 'black'
        }
      },
    },
    hover: {
      animationDuration: 0
    },
    scales: {
      xAxes: [{
          barPercentage: 0.5,
          categoryPercentage: 0.5
        }
      ],
      yAxes: [{
        gridLines: {
          display: false
        },
        type: 'logarithmic',
        position: 'left',
        ticks: {
          min: 0, //minimum tick
          max: 100000, //maximum tick
          callback: function (value, index, values) {
            return Number(value.toString()); //pass tick values as a string into Number function
          }
        },
        afterBuildTicks: function (chartObj) { //Build ticks labelling as per your need
          chartObj.ticks = [];
          chartObj.ticks.push(0);
          chartObj.ticks.push(10);
          chartObj.ticks.push(100);
          chartObj.ticks.push(1000);
          chartObj.ticks.push(10000);
          chartObj.ticks.push(100000);
        },
        scaleLabel: {
          display: false
        },
        stacked: false
      }]
    },
  };
  this.Canvas = document.getElementById("chBar");
  this.chart = new Chart(this.Canvas, {
    type: "bar",
    data: chartData,
    options: barOptions_stacked
  });
}

How can I do that?

Screenshot:


问:
Extract table from the website using scrapy
I want to scrape text from table they will give me data but they will not given me data in these format shown in pic

```<code>from scrapy import Spider
from scrapy.http import Request

class AuthorSpider(Spider):
    name = 'book'
    start_urls = ['https://blogsrl.it/gb/4-no-food']
    def parse(self, response):
        books = response.xpath("//h3/a/@href").extract()
        for book in books:
            url = response.urljoin(book)
            yield Request(url, callback=self.parse_book)

    def parse_book(self, response):
        rows=response.xpath("//dl[@class='data-sheet']")
        details={}
        for row in rows:
            key = row.xpath('.//dt//text()').get(default='').strip()
            value=row.xpath('.//dd/text()').getall()
            value = ''.join(value).strip()
            details[key] = value
        yield details
</code>```

答:
In your parse_book callback, the variable rows does not return a list but a single element so you can't loop over it. You need to loop over either the row names or the row values. See below snippet on how you can loop over the row names.

def parse_book(self, response):
    rows=response.xpath("//dl[@class='data-sheet']/dt")
    details={}
    for row in rows:
        key = row.xpath("./text()").get()
        value=row.xpath("./following-sibling::dd/text()").get()
        details[key] = value
    yield details
```

Body:
I want to scrape text from table they will give me data but they will not given me data in these format shown in pic

from scrapy import Spider
from scrapy.http import Request

class AuthorSpider(Spider):
    name = 'book'
    start_urls = ['https://blogsrl.it/gb/4-no-food']
    def parse(self, response):
        books = response.xpath("//h3/a/@href").extract()
        for book in books:
            url = response.urljoin(book)
            yield Request(url, callback=self.parse_book)

    def parse_book(self, response):
        rows=response.xpath("//dl[@class='data-sheet']")
        details={}
        for row in rows:
            key = row.xpath('.//dt//text()').get(default='').strip()
            value=row.xpath('.//dd/text()').getall()
            value = ''.join(value).strip()
            details[key] = value
        yield details


问:
Readiness-Probe another Service on boot-up of Pod
On my Kubernetes Setup, i have 2 Services - A and B.

Service B is dependent on Service A being fully started through.
I would now like to set a TCP Readiness-Probe in Pods of Service B, so they test if any Pod of Service A is fully operating.

the ReadinessProbe section of the deployment in Service B looks like:

```<code>readinessProbe:
  tcpSocket:
    host: serviceA.mynamespace.svc.cluster.local
    port: 1101 # same port of Service A Readiness Check
</code>```

I can apply these changes, but the Readiness Probe fails with:

```<code>Readiness probe failed: dial tcp: lookup serviceB.mynamespace.svc.cluster.local: no such host
</code>```

I use the same hostname on other places (e.g. i pass it as ENV to the container) and it works and gets resolved.

Does anyone have an idea to get the readiness working for another service or to do some other kind of dependency-checking between services?
Thanks :)

答:
In addition to Nick_Kh's answer, another workaround is to use probe by command, which is executed in a container.

To perform a probe, the kubelet executes the command cat /tmp/healthy in the target container. If the command succeeds, it returns 0, and the kubelet considers the container to be alive and healthy.

An example:

```<code>readinessProbe:
  exec:
    command:
     - sh
     - -c
     - wget -T2 -O- http://service
</code>```

Body:
On my Kubernetes Setup, i have 2 Services - A and B.

Service B is dependent on Service A being fully started through.
I would now like to set a TCP Readiness-Probe in Pods of Service B, so they test if any Pod of Service A is fully operating.

the ReadinessProbe section of the deployment in Service B looks like:

readinessProbe:
  tcpSocket:
    host: serviceA.mynamespace.svc.cluster.local
    port: 1101 # same port of Service A Readiness Check

I can apply these changes, but the Readiness Probe fails with:

Readiness probe failed: dial tcp: lookup serviceB.mynamespace.svc.cluster.local: no such host

I use the same hostname on other places (e.g. i pass it as ENV to the container) and it works and gets resolved.

Does anyone have an idea to get the readiness working for another service or to do some other kind of dependency-checking between services?
Thanks :)

Body:
In addition to Nick_Kh's answer, another workaround is to use probe by command, which is executed in a container.

To perform a probe, the kubelet executes the command cat /tmp/healthy in the target container. If the command succeeds, it returns 0, and the kubelet considers the container to be alive and healthy.

An example:

readinessProbe:
  exec:
    command:
     - sh
     - -c
     - wget -T2 -O- http://service


问:
SQL Server 2008: update date from row in same column
I've seen this question a lot, but I can't seem to get my SQL to work so I'm hoping someone can help.
I've confirmed that this code will work in Access, but it isn't working with SQL Server 2008.

```<code>UPDATE shop_orders AS t1, shop_orders AS t2
SET t1.shipstreet1 = t2.shipstreet1,
    t1.shipstreet2 = t2.shipstreet2,
    t1.shipcity = t2.shipcity,
    t1.shipregionstate = t2.shipregionstate
WHERE t1.orderid=3292
  AND t2.orderid=3641;
</code>```

Advice?

答:
The syntax for Update From is different for SQL server, the same query will not work in both.

See:
SQL update from one Table to another based on a ID match

For more information on Update From syntax.

ContentLicense: CC BY-SA 3.0

Body:
I've seen this question a lot, but I can't seem to get my SQL to work so I'm hoping someone can help.
I've confirmed that this code will work in Access, but it isn't working with SQL Server 2008.

UPDATE shop_orders AS t1, shop_orders AS t2
SET t1.shipstreet1 = t2.shipstreet1,
    t1.shipstreet2 = t2.shipstreet2,
    t1.shipcity = t2.shipcity,
    t1.shipregionstate = t2.shipregionstate
WHERE t1.orderid=3292
  AND t2.orderid=3641;

Advice?


问:
Regex: How to extract a word with a preceding number and exclude numbers and colon after that group
Consider the following strings:

```<code>1 Post 12:34

4 Posts 15:11

Deleted 8:46
</code>```

I need to get the first part with the number and exclude the second timestamps: This is what I've tried, but I get null for "deleted".

```<code>var poststatus = posts.match(/(^)[\d](?<!^)[\D\:]+/);
</code>```

答:
Give this a try:

```<code>/(.| )*(?= \d+:\d+)/g
</code>```

https://regex101.com/r/EvDkZr/1

Body:
Consider the following strings:

1 Post 12:34

4 Posts 15:11

Deleted 8:46

I need to get the first part with the number and exclude the second timestamps: This is what I've tried, but I get null for "deleted".

var poststatus = posts.match(/(^)[\d](?<!^)[\D\:]+/);

Body:
Give this a try:

/(.| )*(?= \d+:\d+)/g

https://regex101.com/r/EvDkZr/1


问:
Running an activity from a fragment
Im trying to run an activity from a button press in a fragment, however the app crashes when the button is pressed.

```<code>public class FitnessFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_fitness, container, false);

        Button btn1 = (Button) root
                .findViewById(R.id.trackCalories);

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), video_activity.class);
                ((MainActivity) getActivity()).startActivity(intent);

            }
        });

        return root;
    }
}
</code>```

I'm currently struggling to grasp the concept of launching activities from fragments, any help would be appreciated.

答:
You can simply do like this:</p>
```<code> btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
      startActivity(new Intent(requireActivity(), video_activity.class))
    }
});
</code>```

Title: Running an activity from a fragment

Body:
Im trying to run an activity from a button press in a fragment, however the app crashes when the button is pressed.

public class FitnessFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_fitness, container, false);

        Button btn1 = (Button) root
                .findViewById(R.id.trackCalories);

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), video_activity.class);
                ((MainActivity) getActivity()).startActivity(intent);

            }
        });

        return root;
    }
}

I'm currently struggling to grasp the concept of launching activities from fragments, any help would be appreciated.

Body:
You can simply do like this:

 btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
      startActivity(new Intent(requireActivity(), video_activity.class))
    }
});


问:
Finding the Most Efficient Way to Reduce a Fraction
As the title suggests I've been trying to find most efficient way to reduce a fraction (i.e. 10/20 -> 1/2) and I came up with this.

```<code>def recursive(n, d):
    i=1
    loop = True

    while loop == True:
        i += 1
        if n % i == 0:
            if d % i == 0:
                loop = False

        if i > min(n, d):
            return f'{n} / {d}'

    nn = n // i
    nd = d // i
    return recursive(nn, nd), f'{n}/{d} Common D: {i}'
</code>```

My thought process was in the worst case scenario this will count up to the minimum of the numerator, denominator pair - n/d doing (N) computations in the process. While if the fraction had something to reduce in the first place it would do so. And in doing so, it'd reduce (N), i.e. how much it needs to count in the first place.

For example given a random fraction like 206/202, it would immediately divide it in two and call the function again, with the new call only having to count to 101, therefore doing about (N/2) computations.

Wanting to test this, I made a control function that always counts to the minimum of the n/d pair (thus always doing N computations), as follows:

```<code>def big_O(n, d):
    list_ = [f'{n} / {d} OG']
    for iteration in range(2 ,min(n, d)+1):
        if n % iteration == 0:
            if d % iteration == 0:
                list_.append(f'{n//iteration} / {d//iteration} Common D: {iteration}')
    return list_
</code>```

And I timed them against each other with a
janky timer I had on hand
and a random number generator:

```<code>def gen():
    return randint(1,1000), randint(1,1000)
</code>```

However much to my surprise my function performed significantly worse I didn't save many of the results, but here is one which is pretty indicative of the rest:

Given 100,000 samples

SIMPLE: ORDERED BY SPEED

frac big O -- 2.3903738830000023 seconds

frac recursive -- 8.184171485 seconds

This came as shock to me as I thought in the worst case scenario, due to bad luck with getting un-reducible fractions, they should be roughly equal! So I calculated the amount of times the generator would come up with a fraction that couldn't be reduced and I got something around 60% of the time, and I thought to myself,

"Ok, what if I make them all even. Then given the logic above (206/202), surely my function should be faster."

```<code>def gen_even():
    return randrange(2,2002,2), randrange(2,2002,2)
</code>```

And the results are!

With 100,000 Samples

SIMPLE: ORDERED BY SPEED

frac.big_O() -- 4.2074602940000005 seconds

frac.recursive() -- 7.840177308999998 seconds

It's slightly better... BUT IT'S STILL WORSE! How can this be?! I don't get it. After this I looked at many, many different things, but in the end I couldn't figure it out. I did however find out some more fun facts, for instance once the fraction can be reduced twice (i.e. 12/8 : 6/4 : 3/2) then my function starts being better by a factor of how many more reductions there are.

For example with this generation function:

```<code>def genx4():
    return randint(1,1000)*4, randint(1,1000)*4
</code>```

The results look like this:

100,000 samples

SIMPLE: ORDERED BY SPEED

frac recursive -- 6.605415995000001 seconds

frac big O -- 8.567245255000003 seconds

And if you replace the *4 with *1000 they look like this

With only 100 samples!

SIMPLE: ORDERED BY SPEED

frac recursive -- 0.014295906999997499 seconds

frac big O -- 2.250979277999999 seconds

Except why is it only good here?! I don't know, so if any of the kind people who have read up to here have anything to say, from different possible solutions regarding reducing fractions to why my recursive function is worse given the above, please go ahead, and also thank you very much for your time!

答:
For the 'most efficient' solution, you're just looking for the GCD of n, d, so the Euclidean algorithm solves this in O(log(max(n,d)) multiplications. Unless you're a theoretician or dealing with massive numbers, it's probably not worth trying to optimize much beyond that. See, for example, the wiki on greatest common divisors for more information on GCD calculation, but to summarize, you'd have to use fast multiplication algorithms with inputs in the 'thousands of digits' range to start outperforming normal multiplication.

For the surprising timing results, it's likely due to while loop overhead compared to for-loops from Python internals. Try disassembling both functions-- the for-loop iteration is done in C, and the while loop iteration is done in Python bytecode, which is slower.

On the short time-scales you're measuring, performance can be highly unpredictable. As a result, timing many short loops might tell you more about the efficiency of the language's loop implementation than the algorithmic efficiency of your code.

The fact that you only saw results compatible with the asymptotic predictions when your inputs got large isn't all too surprising-- it's the core idea of asymptotic analysis.

Body:
As the title suggests I've been trying to find most efficient way to reduce a fraction (i.e. 10/20 -> 1/2) and I came up with this.

def recursive(n, d):
    i=1
    loop = True

    while loop == True:
        i += 1
        if n % i == 0:
            if d % i == 0:
                loop = False

        if i > min(n, d):
            return f'{n} / {d}'

    nn = n // i
    nd = d // i
    return recursive(nn, nd), f'{n}/{d} Common D: {i}'

My thought process was in the worst case scenario this will count up to the minimum of the numerator, denominator pair - n/d doing (N) computations in the process. While if the fraction had something to reduce in the first place it would do so. And in doing so, it'd reduce (N), i.e. how much it needs to count in the first place.

For example given a random fraction like 206/202, it would immediately divide it in two and call the function again, with the new call only having to count to 101, therefore doing about (N/2) computations.

Wanting to test this, I made a control function that always counts to the minimum of the n/d pair (thus always doing N computations), as follows:

def big_O(n, d):
    list_ = [f'{n} / {d} OG']
    for iteration in range(2 ,min(n, d)+1):
        if n % iteration == 0:
            if d % iteration == 0:
                list_.append(f'{n//iteration} / {d//iteration} Common D: {iteration}')
    return list_

And I timed them against each other with a
janky timer I had on hand
and a random number generator:

def gen():
    return randint(1,1000), randint(1,1000)

However much to my surprise my function performed significantly worse I didn't save many of the results, but here is one which is pretty indicative of the rest:

Given 100,000 samples

SIMPLE: ORDERED BY SPEED

frac big O -- 2.3903738830000023 seconds

frac recursive -- 8.184171485 seconds

This came as shock to me as I thought in the worst case scenario, due to bad luck with getting un-reducible fractions, they should be roughly equal! So I calculated the amount of times the generator would come up with a fraction that couldn't be reduced and I got something around 60% of the time, and I thought to myself,

"Ok, what if I make them all even. Then given the logic above (206/202), surely my function should be faster."

def gen_even():
    return randrange(2,2002,2), randrange(2,2002,2)

And the results are!

With 100,000 Samples

SIMPLE: ORDERED BY SPEED

frac.big_O() -- 4.2074602940000005 seconds

frac.recursive() -- 7.840177308999998 seconds

It's slightly better... BUT IT'S STILL WORSE! How can this be?! I don't get it. After this I looked at many, many different things, but in the end I couldn't figure it out. I did however find out some more fun facts, for instance once the fraction can be reduced twice (i.e. 12/8 : 6/4 : 3/2) then my function starts being better by a factor of how many more reductions there are.

For example with this generation function:

def genx4():
    return randint(1,1000)*4, randint(1,1000)*4

The results look like this:

100,000 samples

SIMPLE: ORDERED BY SPEED

frac recursive -- 6.605415995000001 seconds

frac big O -- 8.567245255000003 seconds

And if you replace the *4 with *1000 they look like this

With only 100 samples!

SIMPLE: ORDERED BY SPEED

frac recursive -- 0.014295906999997499 seconds

frac big O -- 2.250979277999999 seconds

Except why is it only good here?! I don't know, so if any of the kind people who have read up to here have anything to say, from different possible solutions regarding reducing fractions to why my recursive function is worse given the above, please go ahead, and also thank you very much for your time!


问:
How do I put a conditional and a loop in the same line?
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

```<code>foreach (0 .. 10) {
    print $_ if $_ % 2;
}
</code>```

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

```<code>[i for i in range(10) if i % 2]
</code>```

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

答:
For elements of a list which are odd

```<code>$_%2 and print for 0..10;
</code>```

or

```<code>$_&1 and print for 0..10;
</code>```

Or one may want elements at odd indices where that 0..10 stands for array indices

```<code>my @ary = 0..10;

$_&1 and print $ary[$_] for 0..$#ary;
</code>```

The syntax $#ary is for the index of the last element of array @ary.

The point being that Perl's and short-circuits so if the expression on its left-hand-side isn't true then what is on its right-hand-side doesn't run. (Same with or -- if the LHS is true the RHS isn't evaluated.)

If you indeed need array elements at odd indices can also do

```<code>my @ary = 0..10;

print for @ary[grep { $_&1 } 0..$#ary];
</code>```

All above print 13579 (no linefeed).  In a one-liner, to enter and run on the command-line

```<code>perl -we'$_%2 and print for 0..10'
</code>```

If you actually need to print each number on its own line, judged by a posted comment, replace print with say, like

```<code>$_%2 and say for 0..$#ary;
</code>```

for odd array elements from array @ary, or

```<code>$_&1 and say $ary[$_] for 0..$#ary;
</code>```

for array elements at odd indices.

Add use feature 'say'; to the beginning of the program (unless it is enabled already by other loaded tools/libraries).

Body:
I would like to put a conditional and loop on the same line on Perl. This is what I would like to achieve:

foreach (0 .. 10) {
    print $_ if $_ % 2;
}

which should give me 13579. I'm looking for a statement like loop comprehension in Python, e.g.

[i for i in range(10) if i % 2]

I know that print $_ foreach 0 .. 10; works but the problem is adding the conditional to the statement as well...

Body:
For elements of a list which are odd

$_%2 and print for 0..10;

or

$_&1 and print for 0..10;

Or one may want elements at odd indices where that 0..10 stands for array indices

my @ary = 0..10;

$_&1 and print $ary[$_] for 0..$#ary;

The syntax $#ary is for the index of the last element of array @ary.

The point being that Perl's and short-circuits so if the expression on its left-hand-side isn't true then what is on its right-hand-side doesn't run. (Same with or -- if the LHS is true the RHS isn't evaluated.)

If you indeed need array elements at odd indices can also do

my @ary = 0..10;

print for @ary[grep { $_&1 } 0..$#ary];

All above print 13579 (no linefeed).  In a one-liner, to enter and run on the command-line

perl -we'$_%2 and print for 0..10'

If you actually need to print each number on its own line, judged by a posted comment, replace print with say, like

$_%2 and say for 0..$#ary;

for odd array elements from array @ary, or

$_&1 and say $ary[$_] for 0..$#ary;

for array elements at odd indices.

Add use feature 'say'; to the beginning of the program (unless it is enabled already by other loaded tools/libraries).


问:
How to modify this HTML form to include a constant?
Here's an example of a search in our SirsiDynix Enterprise catalog using the CloudSourceOA option te=750777545
https://nyit.ent.sirsi.net/client/en_US/default/search/results?qu=html&te=750777545&rt=false%7C%7C%7C%3ECSOA%3Ctitle%7C%7C%7CTitle

I want to pass the variables from a form in libguides to the enterprise. I have a working example for searching "Everything" and a broken example for the CloudSourceOA
My Form sends the search types like title and the term that the user enters in the input field to the qu=, however, I don't know how to append the te=750777545. This value will always be set as I want the widget to always search cloudsource rather than everything.
Here's a link to my libguide for troubleshooting. I was unable to add the code successfully here.
https://libguides.nyit.edu/c.php?g=1216772&p=8899584&preview=77a637b8476d8bbe2575a12fd18e3b61

答:
It's unclear what te or the 750777545 value is, but if you need to hardcode that to your form you can do so with a hidden input set to that value. Fair warning, without knowing what this form field is, this may not be the best approach so you'll want to consult any documentation if this is specific to an internal NYIT application.

<form action="https://nyit.ent.sirsi.net/client/en_US/default/search/results?" id="searchForm" method="&te=""get"" name="searchForm">

Search the NYIT Catalogue

        <input name="ln" type="hidden" value="en_US">

        <select class="dropDown" id="restrictionDropDown" name="rt">
            <option value="">
                All Fields
            </option>
            <option value="false|||TITLE|||Title">
                Title
            </option>
            <option value="false|||AUTHOR|||AUTHOR">
                Author
            </option>
            <option value="false|||SUBJECT|||SUBJECT">
                Subject
            </option>
            <option value="false|||ISBN|||ISBN">
                ISBN
            </option>
            <option value="false|||ISSN|||ISSN">
                ISSN
            </option>
            <option value="false|||DOI|||DOI">
                DOI
            </option>
            <option value="false|||JOURNAL|||Journal Title">
                Journal Title
            </option>
        </select>
        <input type="hidden" id="te" name="te" value="750777545">

<input accesskey="s" id="qu" maxlength="256" name="qu" style="width:250px;" title="Search For:" type="text" value=""><input class="button" id="searchButton" title="Search" type="submit" value="Search">

</form>
```

Body:
It's unclear what te or the 750777545 value is, but if you need to hardcode that to your form you can do so with a hidden input set to that value. Fair warning, without knowing what this form field is, this may not be the best approach so you'll want to consult any documentation if this is specific to an internal NYIT application.

<form action="https://nyit.ent.sirsi.net/client/en_US/default/search/results?" id="searchForm" method="&te=&quot;&quot;get&quot;" name="searchForm">
    <h5>Search the NYIT Catalogue</h5>
    <div class="searchline">
        <input name="ln" type="hidden" value="en_US"><br>
        <select class="dropDown" id="restrictionDropDown" name="rt">
            <option value="">
                All Fields
            </option>
            <option value="false|||TITLE|||Title">
                Title
            </option>
            <option value="false|||AUTHOR|||AUTHOR">
                Author
            </option>
            <option value="false|||SUBJECT|||SUBJECT">
                Subject
            </option>
            <option value="false|||ISBN|||ISBN">
                ISBN
            </option>
            <option value="false|||ISSN|||ISSN">
                ISSN
            </option>
            <option value="false|||DOI|||DOI">
                DOI
            </option>
            <option value="false|||JOURNAL|||Journal Title">
                Journal Title
            </option>
        </select>
        <input type="hidden" id="te" name="te" value="750777545">
        <p><input accesskey="s" id="qu" maxlength="256" name="qu" style="width:250px;" title="Search For:" type="text" value=""><input class="button" id="searchButton" title="Search" type="submit" value="Search"></p>
    </div>
</form>


问:
Find a substring in cells across multiple columns in a Pandas dataframe
I have a large DataFrame with 50+ columns which I'm simplifying here below:

```<code>students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])
</code>```

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

```<code>boolDf = df.isin(['--->']).any().any()
</code>```

this only works for strings not substrings

```<code>columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()
</code>```

I get:

```<code>AttributeError: Can only use .str accessor with string values!
</code>```

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

答:
You can use .applymap() to test each individual value in a dataframe.

```<code>>>> df
      Name  Age Balance    Country      Currency
0  Samurai   34   777.0  usa--->jp    usd--->yen
1     Jack   31   555.5        usa           usd
2     Mojo   16   488.1        n/a           n/a
3     Jojo   32  119.11  uk--->usa  pound--->usd

>>> df.applymap(lambda x: isinstance(x, str) and '--->' in x)
    Name    Age  Balance  Country  Currency
0  False  False    False     True      True
1  False  False    False    False     False
2  False  False    False    False     False
3  False  False    False     True      True
</code>```

To use the .str accessor you can:

```<code>>>> df.select_dtypes(object).apply(lambda col: col.str.contains('--->'))
    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True
</code>```

The output differs a little - note the Age column is not there.

Body:
I have a large DataFrame with 50+ columns which I'm simplifying here below:

students = [('Samurai', 34, '777.0', 'usa--->jp', 'usd--->yen') ,
            ('Jack', 31, '555.5','usa','usd') ,
            ('Mojo', 16,'488.1','n/a','n/a') ,
            ('Jojo', 32,'119.11','uk--->usa','pound--->usd')]

# Create a DataFrame object
df = pd.DataFrame(students, columns=['Name', 'Age', 'Balance', 'Country','Currency'])

I'm trying to find

a) whether there are any instances of '--->' in any of the cells across the DataFrame?

b) if so where? (optional)

So far I've tried 2 approaches

boolDf = df.isin(['--->']).any().any()

this only works for strings not substrings

columns = list(df)
for col in columns:
    df[col].str.find('--->', 0).any()

I get:

AttributeError: Can only use .str accessor with string values!

(I believe this may only work for columns with string types)

Would appreciate any help. Open to other approaches as well.

Body:
You can use .applymap() to test each individual value in a dataframe.

>>> df
      Name  Age Balance    Country      Currency
0  Samurai   34   777.0  usa--->jp    usd--->yen
1     Jack   31   555.5        usa           usd
2     Mojo   16   488.1        n/a           n/a
3     Jojo   32  119.11  uk--->usa  pound--->usd

>>> df.applymap(lambda x: isinstance(x, str) and '--->' in x)
    Name    Age  Balance  Country  Currency
0  False  False    False     True      True
1  False  False    False    False     False
2  False  False    False    False     False
3  False  False    False     True      True

To use the .str accessor you can:

>>> df.select_dtypes(object).apply(lambda col: col.str.contains('--->'))
    Name  Balance  Country  Currency
0  False    False     True      True
1  False    False    False     False
2  False    False    False     False
3  False    False     True      True

The output differs a little - note the Age column is not there.


问:
Export certificate in Azure App Services
Would it be possible to export a SSL wildcard certificate used for HTTPS connection in Azure app services? The option to export and used the wildcard cert to another server with the same domain name seems to be missing in Azure App Services as seen below:

答:
There are a few ways SSL certificates are made available to App Services to be used for https connections.

There's App Service Certificates. These are exportable! This can be confusing because it sounds like the Private Key Certificates tab of the TLS/SSL settings within an App Service but it's actually its own thing in Azure that allows you to buy certificates through GoDaddy. Because you buy it, it's yours, and it would be silly if they didn't allow you to download it.
To export this, you go to the key vault you associated with this purchase and export the certificate from there.

Then there's free managed certificates within App services. These are not exportable! These are the certificates that you can generate with App Service from the Private Key Certificates tab by clicking on Create App Service Managed Certificate, provided you can pass domain ownership requirements with DNS records.

Then there's certificates that you provided to App Service yourself by choosing Upload Certificate from the Private Key Certificates tab of the TLS/SSL settings within an App Service. Sorry, you can't get these back out. It's assumed you'd still have the certificate if you provided it this way in the first place.

Lastly, there's certificates that were imported from Key Vault, by choosing Import Key Vault Certificate from the Private Key Certificates tab of the TLS/SSL settings within an App Service. These are exportable! Go to the Key Vault where the certificate is stored and export it, just as you would if you purchased a certificate through App Service Certificates.


问:
Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#
I basically have two DateTime variables

```<code> DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;
</code>```

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

```<code>if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
</code>```

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

答:
To compare two dateTime values in an if statement you can do:</p>
```<code>if(firstDate.Date > secondDate.Date)
{
  //Do something...
}
</code>```

Body:
I basically have two DateTime variables

 DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
 DateTime dateFinish;

dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:

if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}

I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.

Body:
To compare two dateTime values in an if statement you can do:

if(firstDate.Date > secondDate.Date)
{
  //Do something...
}


问:
How to turn a single row to multiple row in mysql?
ex:

the column 'genre' has a row of data:

```<code>+----------------------------+
|            genres          |
+----------------------------+
|   action, adventure, drama |       |
|                            |
+----------------------------+
</code>```

my desired output will be a column that holds the following data:

```<code>+------------+
|    genre   |
+------------+
| action     |
| adventure  |
| drama      |
+------------+
</code>```

how do I do it in mysql?

答:
first, to show all content of your table, u can use * (it's mean all)

SELECT * FROM <TableName>;
```
<p><img src="https://i.stack.imgur.com/W4x9Y.png" alt="enter image description here" /></p>
<p>for spesific column u can change it to column name,</p>
<pre class="lang-sql prettyprint-override"><code>SELECT <ColumnName> FROM <TableName>;
</code>```

Ex: in my case i want show just content of name. so i can write

SELECT name FROM users;
```

Body:
ex:

the column 'genre' has a row of data:

+----------------------------+
|            genres          |
+----------------------------+
|   action, adventure, drama |       |
|                            |
+----------------------------+

my desired output will be a column that holds the following data:

+------------+
|    genre   |
+------------+
| action     |
| adventure  |
| drama      |
+------------+

how do I do it in mysql?

Body:
first, to show all content of your table, u can use * (it's mean all)

SELECT * FROM <TableName>;

for spesific column u can change it to column name,

SELECT <ColumnName> FROM <TableName>;

Ex: in my case i want show just content of name. so i can write

SELECT name FROM users;


问:
How can I use the New-Object cmdlet in a PowerShell script when my constructor takes in a large array of bytes?
I am writing a PowerShell function/script (using the version that ships with Windows 10, which I believe is 5.0) to take in a GZip compressed Base64 string and decompress it, and then decode it under the assumption the original uncompressed/decoded string was Unicode encoded.

I am trying to instantiate a new object instance of type MemoryStream using this constructor and the New-Object cmdlet. It takes one parameter, which is an array of bytes.

PowerShell is unable to find a valid overload that accepts the array of bytes I am trying to pass as the constructor's parameter. I believe the issue is due to the array's relatively large length. Please see my code below:

```<code>Function DecompressString()
{
    param([parameter(Mandatory)][string]$TextToDecompress)

    try
    {
        $bytes = [Convert]::FromBase64String($TextToDecompress)

        $srcStreamParameters = @{
            TypeName = 'System.IO.MemoryStream'
            ArgumentList = ([byte[]]$bytes)
        }

        $srcStream = New-Object @srcStreamParameters
        $dstStream = New-Object -TypeName System.IO.MemoryStream

        $gzipParameters = @{
            TypeName = 'System.IO.Compression.GZipStream'
            ArgumentList = ([System.IO.Stream]$srcStream, [System.IO.Compression.CompressionMode]::Decompress)
        }

        $gzip = New-Object @gzipParameters
        $gzip.CopyTo($dstStream)
        $output = [Text.Encoding]::Unicode.GetString($dstStream.ToArray())
        Write-Output $output
    }
    catch
    {
        Write-Host "$_" -ForegroundColor Red
    }
    finally
    {
        if ($gzip -ne $null) { $gzip.Dispose() }
        if ($srcStream -ne $null) { $srcStream.Dispose() }
        if ($dstStream -ne $null) { $dstStream.Dispose() }
    }
}

DecompressString
$ExitPrompt = Read-Host -Prompt 'Press Enter to Exit'
</code>```

The error message I get is: Cannot find an overload for "MemoryStream" and the argument count: "1764".

Can anyone please clarify how I can get the script interpreter to use the constructor correctly with a large byte array?

答:
I thought I would share an answer to this question which I found very interesting, solution to the error has already been provided by Lance U. Matthews in his helpful comment, by adding the unary operator , before the $bytes assigned to the ArgumentList of New-Object, by doing so, the $bytes are passed as a single argument (array of bytes) and not as individual elements to the constructor of System.IO.MemoryStream:

$bytes = [Convert]::FromBase64String($compressedString)
$srcStreamParameters = @{
    TypeName     = 'System.IO.MemoryStream'
    ArgumentList = , $bytes
}

$srcStream = New-Object @srcStreamParameters
```
<p>Beginning in <strong>PowerShell 5.0</strong> and going forward, you can construct your memory stream with the following syntax, which is more efficient and straight forward:</p>
<pre class="lang-bash prettyprint-override"><code>$srcStream = [System.IO.MemoryStream]::new($bytes)
</code>```

As for the functions (Compress & Expand), I would like to share my take on these cool functions.

Required using statements and ArgumentCompleter for -Encoding Parameter.

using namespace System.Text
using namespace System.IO
using namespace System.IO.Compression
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language

Add-Type -AssemblyName System.IO.Compression

class EncodingCompleter : IArgumentCompleter {
    [IEnumerable[CompletionResult]] CompleteArgument (
        [string] $commandName,
        [string] $parameterName,
        [string] $wordToComplete,
        [CommandAst] $commandAst,
        [IDictionary] $fakeBoundParameters
    ) {
        [CompletionResult[]] $arguments = foreach($enc in [Encoding]::GetEncodings().Name) {
            if($enc.StartsWith($wordToComplete)) {
                [CompletionResult]::new($enc)
            }
        }
        return $arguments
    }
}
```
<ul>
<li>Compression from <em><strong>string</strong></em> to <em><strong>Base64 GZip compressed string</strong></em>:</li>
</ul>
<pre class="lang-bash prettyprint-override"><code>function Compress-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8',

        [Parameter()]
        [CompressionLevel] $CompressionLevel = 'Optimal'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $outStream = [MemoryStream]::new()
        $gzip      = [GZipStream]::new($outStream, [CompressionMode]::Compress, $CompressionLevel)
        $inStream  = [MemoryStream]::new($enc.GetBytes($string))
        $inStream.CopyTo($gzip)
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }

    try {
        [Convert]::ToBase64String($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
}
</code>```

Expansion from Base64 GZip compressed string to string:

function Expand-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $bytes     = [Convert]::FromBase64String($String)
        $outStream = [MemoryStream]::new()
        $inStream  = [MemoryStream]::new($bytes)
        $gzip      = [GZipStream]::new($inStream, [CompressionMode]::Decompress)
        $gzip.CopyTo($outStream)
        $enc.GetString($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }
}
```
<p>And for the little <em><strong>Length</strong></em> comparison, querying the Loripsum API:</p>
<pre class="lang-bash prettyprint-override"><code>$loremIp = Invoke-RestMethod loripsum.net/api/10/long
$compressedLoremIp = Compress-GzipString $loremIp

$loremIp, $compressedLoremIp | Select-Object Length

Length
------
  8353
  4940

(Expand-GzipString $compressedLoremIp) -eq $loremIp # => Should be True
</code>```

These 2 functions as well as Compression From File Path and Expansion from File Path can be found on this repo.

Body:
I am writing a PowerShell function/script (using the version that ships with Windows 10, which I believe is 5.0) to take in a GZip compressed Base64 string and decompress it, and then decode it under the assumption the original uncompressed/decoded string was Unicode encoded.

I am trying to instantiate a new object instance of type MemoryStream using this constructor and the New-Object cmdlet. It takes one parameter, which is an array of bytes.

PowerShell is unable to find a valid overload that accepts the array of bytes I am trying to pass as the constructor's parameter. I believe the issue is due to the array's relatively large length. Please see my code below:

Function DecompressString()
{
    param([parameter(Mandatory)][string]$TextToDecompress)

    try
    {
        $bytes = [Convert]::FromBase64String($TextToDecompress)

        $srcStreamParameters = @{
            TypeName = 'System.IO.MemoryStream'
            ArgumentList = ([byte[]]$bytes)
        }

        $srcStream = New-Object @srcStreamParameters
        $dstStream = New-Object -TypeName System.IO.MemoryStream

        $gzipParameters = @{
            TypeName = 'System.IO.Compression.GZipStream'
            ArgumentList = ([System.IO.Stream]$srcStream, [System.IO.Compression.CompressionMode]::Decompress)
        }

        $gzip = New-Object @gzipParameters
        $gzip.CopyTo($dstStream)
        $output = [Text.Encoding]::Unicode.GetString($dstStream.ToArray())
        Write-Output $output
    }
    catch
    {
        Write-Host "$_" -ForegroundColor Red
    }
    finally
    {
        if ($gzip -ne $null) { $gzip.Dispose() }
        if ($srcStream -ne $null) { $srcStream.Dispose() }
        if ($dstStream -ne $null) { $dstStream.Dispose() }
    }
}

DecompressString
$ExitPrompt = Read-Host -Prompt 'Press Enter to Exit'

The error message I get is: Cannot find an overload for "MemoryStream" and the argument count: "1764".

Can anyone please clarify how I can get the script interpreter to use the constructor correctly with a large byte array?

Body:
I thought I would share an answer to this question which I found very interesting, solution to the error has already been provided by Lance U. Matthews in his helpful comment, by adding the unary operator , before the $bytes assigned to the ArgumentList of New-Object, by doing so, the $bytes are passed as a single argument (array of bytes) and not as individual elements to the constructor of System.IO.MemoryStream:

$bytes = [Convert]::FromBase64String($compressedString)
$srcStreamParameters = @{
    TypeName     = 'System.IO.MemoryStream'
    ArgumentList = , $bytes
}

$srcStream = New-Object @srcStreamParameters

Beginning in PowerShell 5.0 and going forward, you can construct your memory stream with the following syntax, which is more efficient and straight forward:

$srcStream = [System.IO.MemoryStream]::new($bytes)

As for the functions (Compress & Expand), I would like to share my take on these cool functions.

Required using statements and ArgumentCompleter for -Encoding Parameter.

using namespace System.Text
using namespace System.IO
using namespace System.IO.Compression
using namespace System.Collections
using namespace System.Management.Automation
using namespace System.Collections.Generic
using namespace System.Management.Automation.Language

Add-Type -AssemblyName System.IO.Compression

class EncodingCompleter : IArgumentCompleter {
    [IEnumerable[CompletionResult]] CompleteArgument (
        [string] $commandName,
        [string] $parameterName,
        [string] $wordToComplete,
        [CommandAst] $commandAst,
        [IDictionary] $fakeBoundParameters
    ) {
        [CompletionResult[]] $arguments = foreach($enc in [Encoding]::GetEncodings().Name) {
            if($enc.StartsWith($wordToComplete)) {
                [CompletionResult]::new($enc)
            }
        }
        return $arguments
    }
}

Compression from string to Base64 GZip compressed string:

function Compress-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8',

        [Parameter()]
        [CompressionLevel] $CompressionLevel = 'Optimal'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $outStream = [MemoryStream]::new()
        $gzip      = [GZipStream]::new($outStream, [CompressionMode]::Compress, $CompressionLevel)
        $inStream  = [MemoryStream]::new($enc.GetBytes($string))
        $inStream.CopyTo($gzip)
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }

    try {
        [Convert]::ToBase64String($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
}

Expansion from Base64 GZip compressed string to string:

function Expand-GzipString {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string] $String,

        [Parameter()]
        [ArgumentCompleter([EncodingCompleter])]
        [string] $Encoding = 'utf-8'
    )

    try {
        $enc       = [Encoding]::GetEncoding($Encoding)
        $bytes     = [Convert]::FromBase64String($String)
        $outStream = [MemoryStream]::new()
        $inStream  = [MemoryStream]::new($bytes)
        $gzip      = [GZipStream]::new($inStream, [CompressionMode]::Decompress)
        $gzip.CopyTo($outStream)
        $enc.GetString($outStream.ToArray())
    }
    catch {
        $PSCmdlet.WriteError($_)
    }
    finally {
        $gzip, $outStream, $inStream | ForEach-Object Dispose
    }
}

And for the little Length comparison, querying the Loripsum API:

$loremIp = Invoke-RestMethod loripsum.net/api/10/long
$compressedLoremIp = Compress-GzipString $loremIp

$loremIp, $compressedLoremIp | Select-Object Length

Length
------
  8353
  4940

(Expand-GzipString $compressedLoremIp) -eq $loremIp # => Should be True

These 2 functions as well as Compression From File Path and Expansion from File Path can be found on this repo.


问:
How can I get the oauth_token data from my backend when it's sent via a http response to my frontend?
I am using react-twitter-auth as part of my OAuth 1.0a user authentication flow on my site. My goal is to authenticate a user and then access their username. So far I have a bunch of code I borrowed from a website. There is client side code and backend code.

The client starts the authentication flow, sending a request to http://localhost:4000/api/v1/auth/twitter/reverse. There, I see from a console.log statement that I have the oauth_token value that I will need later for step 3 of the so-called "3 legged auth" authentication flow that I am going through.

Here is the server route I am hitting:

```<code>router.route("/auth/twitter/reverse").post(function (req, res) {
  console.log(72);
  request.post(
    {
      url: "https://api.twitter.com/oauth/request_token",
      oauth: {
        oauth_callback: "http://localhost:3000/",
        consumer_key: twitterConfig.consumerKey,
        consumer_secret: twitterConfig.consumerSecret,
      },
    },
    function (err, r, body) {
      if (err) {
        console.log(err, 83);
        return res.send(500, { message: e.message });
      }

      var jsonStr =
        '{ "' + body.replace(/&/g, '", "').replace(/=/g, '": "') + '"}';
      console.log(jsonStr, 88);
      res.send(JSON.parse(jsonStr));
    }
  );
});
</code>```

I get values such as:

```<code>{ "oauth_token": "HnQ1SgAAAAAAAABco", "oauth_token_secret": "y1qeyxZeiCEWqkKz9y", "oauth_callback_confirmed": "true"} 88
</code>```

Some characters have been deleted in case that isn't data I should be exposing. Anyway:

I need that "oauth_token" value to make it to my client. Why? Because I'm getting a pin in the 3 legged auth part, and so I need both values to arrive on my server at the same time.

If i wasn't using the react-twitter-auth library, I would have no problem here, because I would just be sending a http request via fetch, and so I would have a .then() block to show me what the value of res.send(JSON.parse(jsonStr)); is on the frontend. But I don't have that, nothing is there to listen for the res.send() part. How can I listen for it?

Thanks

edit: I am critical of this library because it doesn't account for what happens with the PIN based strategy for 3 legged auth.

答:
Looking at react-twitter-auth codebase I'm not sure they support 3 legged auth as they are calling authenticate endpoint instead of authorize endpoint as stated in the documentation of twitter api

I would either try react-twitter-oauth forked from reacr-twitter-auth or go through the twitter documentation to implement it myself

Body:
I am using react-twitter-auth as part of my OAuth 1.0a user authentication flow on my site. My goal is to authenticate a user and then access their username. So far I have a bunch of code I borrowed from a website. There is client side code and backend code.

The client starts the authentication flow, sending a request to http://localhost:4000/api/v1/auth/twitter/reverse. There, I see from a console.log statement that I have the oauth_token value that I will need later for step 3 of the so-called "3 legged auth" authentication flow that I am going through.

Here is the server route I am hitting:

router.route("/auth/twitter/reverse").post(function (req, res) {
  console.log(72);
  request.post(
    {
      url: "https://api.twitter.com/oauth/request_token",
      oauth: {
        oauth_callback: "http://localhost:3000/",
        consumer_key: twitterConfig.consumerKey,
        consumer_secret: twitterConfig.consumerSecret,
      },
    },
    function (err, r, body) {
      if (err) {
        console.log(err, 83);
        return res.send(500, { message: e.message });
      }

      var jsonStr =
        '{ "' + body.replace(/&/g, '", "').replace(/=/g, '": "') + '"}';
      console.log(jsonStr, 88);
      res.send(JSON.parse(jsonStr));
    }
  );
});

I get values such as:

{ "oauth_token": "HnQ1SgAAAAAAAABco", "oauth_token_secret": "y1qeyxZeiCEWqkKz9y", "oauth_callback_confirmed": "true"} 88

Some characters have been deleted in case that isn't data I should be exposing. Anyway:

I need that "oauth_token" value to make it to my client. Why? Because I'm getting a pin in the 3 legged auth part, and so I need both values to arrive on my server at the same time.

If i wasn't using the react-twitter-auth library, I would have no problem here, because I would just be sending a http request via fetch, and so I would have a .then() block to show me what the value of res.send(JSON.parse(jsonStr)); is on the frontend. But I don't have that, nothing is there to listen for the res.send() part. How can I listen for it?

Thanks

edit: I am critical of this library because it doesn't account for what happens with the PIN based strategy for 3 legged auth.


问:
Difference in model feature importance and SHAP summary plot
I have been playing around the toy dataset to understand more about shap library and usage. I found this issue that the feature importances from the catboost regressor model is different than the features importances from the summary_plot in the shap library.

I am analyzing the feature importance from the model.feature_importances_ on X_train set and the summary plot from shap explainer on X_test set.

Here is my source code -

```<code>import catboost
from catboost import *
import shap
shap.initjs()
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

X,y = shap.datasets.boston()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

# Train Model
model = CatBoostRegressor(iterations=300, learning_rate=0.1, random_seed=123)
model.fit(X_train, y_train, verbose=False, plot=False)

# Compute feature importance dataframe
feat_imp_list = list(zip ( list(model.feature_importances_) , model.feature_names_) )
feature_imp_df = pd.DataFrame(sorted(feat_imp_list, key=lambda x: x[0], reverse=True) , columns = ['feature_value','feature_name'])
feature_imp_df
</code>```

```<code># Run shap explainer on X_test set
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)
</code>```

Why does DIS show up at rank 3 in the feature importance plot from Model but shows up at rank 7 in the summary plot from the SHAP library?

答:
Feature importance are always positive where as shap values are coefficients attached to independent variables(it can be negative and positive both).

Both are give you results in descending order:
-In Feature Importance you can see it start from max and goes down to min. Its sum necessarily need to be 100(i.e.100%) in any case.
-For shape values it just the coefficient attached to that particular feature. This is also in descending order (start from highest coefficient to lowest value). Its sum can be anything in real line(for any case).

P.S. you can compare these shap coefficients with coefficient from logistic regression model for better understanding.

Cheers!

Body:
I have been playing around the toy dataset to understand more about shap library and usage. I found this issue that the feature importances from the catboost regressor model is different than the features importances from the summary_plot in the shap library.

I am analyzing the feature importance from the model.feature_importances_ on X_train set and the summary plot from shap explainer on X_test set.

Here is my source code -

import catboost
from catboost import *
import shap
shap.initjs()
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

X,y = shap.datasets.boston()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

# Train Model
model = CatBoostRegressor(iterations=300, learning_rate=0.1, random_seed=123)
model.fit(X_train, y_train, verbose=False, plot=False)

# Compute feature importance dataframe
feat_imp_list = list(zip ( list(model.feature_importances_) , model.feature_names_) )
feature_imp_df = pd.DataFrame(sorted(feat_imp_list, key=lambda x: x[0], reverse=True) , columns = ['feature_value','feature_name'])
feature_imp_df

# Run shap explainer on X_test set
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

Why does DIS show up at rank 3 in the feature importance plot from Model but shows up at rank 7 in the summary plot from the SHAP library?


问:
Change the Privacy Status of a file using Google Drive Api and Python
How do I change the privacy status of a file using Google Drive Api and Python?
I can capture this state with file['shared'] which returns a boolean 0 (private) or 1 (public)

答:
I believe your current situation and your goal are as follows.

You want to change shared of a file from true to false using pydrive for python.

You have already been able to get and put values for a file using Google Drive API.

You are the owner of the file, and the file is put in your Google Drive.

In this case, how about the following sample script?

Sample script:

In this script, all permissions except for the owner are deleted.

ownerEmail = '###'  # Please set the owner's email address.
file_id = '###'  # Please set the file ID.
drive = GoogleDrive(gauth) # Please your your authorization script.

file = drive.CreateFile({'id': file_id})
permission_list = file.GetPermissions()
for obj in permission_list:
    if obj.get('emailAddress') != ownerEmail:
        file.DeletePermission(obj['id'])
```
<p>Or, if the file is publicly shared and you want to delete only the publicly shared permission, you can use the following script.</p>
<pre class="lang-py prettyprint-override"><code>file_id = '###'  # Please set the file ID.
drive = GoogleDrive(gauth) # Please your your authorization script.
drive.CreateFile({'id': file_id}).DeletePermission('anyoneWithLink')
</code>```

Reference:

Remove a Permission

Body:
I believe your current situation and your goal are as follows.

You want to change shared of a file from true to false using pydrive for python.

You have already been able to get and put values for a file using Google Drive API.

You are the owner of the file, and the file is put in your Google Drive.

In this case, how about the following sample script?

Sample script:

In this script, all permissions except for the owner are deleted.

ownerEmail = '###'  # Please set the owner's email address.
file_id = '###'  # Please set the file ID.
drive = GoogleDrive(gauth) # Please your your authorization script.

file = drive.CreateFile({'id': file_id})
permission_list = file.GetPermissions()
for obj in permission_list:
    if obj.get('emailAddress') != ownerEmail:
        file.DeletePermission(obj['id'])

Or, if the file is publicly shared and you want to delete only the publicly shared permission, you can use the following script.

file_id = '###'  # Please set the file ID.
drive = GoogleDrive(gauth) # Please your your authorization script.
drive.CreateFile({'id': file_id}).DeletePermission('anyoneWithLink')

Reference:

Remove a Permission


问:
Is it efficient to store icons and small images in AWS S3
Is it more efficient to store icons and small decorative images (eg arrow.jpg or Submit.jpg etc) on S3 vs on the hosting server's local disk ?

images/arrow.jpg (relative url to the hosting server)

vs

https://aws.com/images/arrow.jpg

I am not  concerned about the storage/space but the number of hits to the server because every page may contain 50 to 100 such icons and  small images. I am not using CDN

答:
When you say hosting server, you are ultimately going to store your volume on EBS, EFS ,( not instance store because it is not persistent).

There are many factors to distinguish based on efficiency but ultimately it will boil down to COST.

S3 is way cheaper, highly available, and more durable than EBS.

EBS is AZ bound but s3 is not. if you want to access to ebs in another az you will need to copy and snapshot and restore to another AZ.

with s3 you can utilize intelligent teiring with lifecycle policies to move your files automatically between different storage tiers for cost optimization.

however, if you want to fast access and low latency then EBS and EFS is a better option without a doubt.

s3 gives you unlimited storage but individual element size is limited to 5TB

For performance go for ebs , for cost go for s3.

NOTE : if you want to access your data on ebs or efs you would need to spin up an ec2 instance which also add cost

FAq for comparison
s3 v/s ebs v/s  efs

This post on stack is also a good read AWS EFS vs EBS vs S3 (differences & when to use?)


问:
Building a uwsgi plugin for python 3.9 failed for older version it works. Are there any other options?
i downloaded the latest source code uwsgi-2.0.19.1 and tried to build a uwsgi plugin
for python 3.9 but it failed every time. For other Versions like python3.6 or python3.8 it works and i used them in other Django Projects. For Example...

Here it works:

Command:

```<code>[user@me /uwsgi-2.0.19.1] $ make PROFILE=nolang

[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.6 ./uwsgi --build-plugin "plugins/python python36"
</code>```

Output:

```<code>*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python36_plugin.so
build time: 5 seconds
*** python36 plugin built and available in python36_plugin.so ***
</code>```

Command:

```<code>[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.8 ./uwsgi --build-plugin "plugins/python python38"
</code>```

Output:

```<code>*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python38_plugin.so
build time: 5 seconds
*** python38 plugin built and available in python38_plugin.so ***
</code>```

Here it fails:

"Datei oder Verzeichnis nicht gefunden" is german and means "File or directory not found".

command:

```<code>[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.9 ./uwsgi --build-plugin "plugins/python python39"
</code>```

outpu:

```<code>*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python39_plugin.so
In file included from plugins/python/python_plugin.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pyutils.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pyloader.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_handlers.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_headers.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/web3_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pump_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/gil.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/uwsgi_pymodule.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/profiler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/symimporter.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/tracebacker.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/raw.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
*** unable to build python39 plugin ***
</code>```

Question:

Does it mean python3.9 is not supported? Could not find anything in the uWSGI docs, maybe i missed it.

Can i download somewhere a already build plugin for python3.9 ? I am not allowed to sudo apt install anything because i am on a shared Server.

答:
hope this helps someone else that comes along a similar issue.
my problem was uwsgi using always python3.8 when i wanted it to use python3.9 (apt installs and pip3, etc. nothing worked, i couldn't get the python3.9 plugin for uwsgi)

my solution was to install python3.9-dev

$ sudo apt install python3.9-dev

instead of just 'python3.9'

then $ python3 -m pip uninstall uwsgi

and finally $ python3 -m pip install --no-cache-dir uwsgi

this apparently included the uwsgi python3.9 plugin required, while ensuring that i removed any cached python3.8 stuff in apt
glhf!

Body:
i downloaded the latest source code uwsgi-2.0.19.1 and tried to build a uwsgi plugin
for python 3.9 but it failed every time. For other Versions like python3.6 or python3.8 it works and i used them in other Django Projects. For Example...

Here it works:

Command:

[user@me /uwsgi-2.0.19.1] $ make PROFILE=nolang

[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.6 ./uwsgi --build-plugin "plugins/python python36"

Output:

*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python36_plugin.so
build time: 5 seconds
*** python36 plugin built and available in python36_plugin.so ***

Command:

[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.8 ./uwsgi --build-plugin "plugins/python python38"

Output:

*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python38_plugin.so
build time: 5 seconds
*** python38 plugin built and available in python38_plugin.so ***

Here it fails:

"Datei oder Verzeichnis nicht gefunden" is german and means "File or directory not found".

command:

[user@me /uwsgi-2.0.19.1] $ PYTHON=python3.9 ./uwsgi --build-plugin "plugins/python python39"

outpu:

*** uWSGI building and linking plugin from plugins/python ***
[gcc -pthread] python39_plugin.so
In file included from plugins/python/python_plugin.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pyutils.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pyloader.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_handlers.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_headers.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/wsgi_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/web3_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/pump_subhandler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/gil.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/uwsgi_pymodule.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/profiler.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/symimporter.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/tracebacker.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
In file included from plugins/python/raw.c:1:
plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden
    2 | #include <Python.h>
      |          ^~~~~~~~~~
compilation terminated.
*** unable to build python39 plugin ***

Question:

Does it mean python3.9 is not supported? Could not find anything in the uWSGI docs, maybe i missed it.

Can i download somewhere a already build plugin for python3.9 ? I am not allowed to sudo apt install anything because i am on a shared Server.


问:
One async call per button. How do I handle users clicking multiple buttons in quick succession?
I've an admin page with multiple buttons that make axios calls to change the content. Each button makes a different call.

When the user clicks button 1, data is retrieved from the server to be displayed onscreen. But if the user clicks button 1, then 2 in quick succession, the UI displays data from 1, then 2.

This isn't necessarily a massive problem, but I would like to know the best approach, as it does cause me issues when animating the data with gsap (see below).

Is the best approach to try and using tokens to cancel the axios request?

Codepen: Non-animation example
A slightly different example with animation

JS

```<code>document.body.addEventListener('click', async e => {
  const item1 = e.target.closest('.item1');
  const item2 = e.target.closest('.item2');
  const item3 = e.target.closest('.item3');

    if(item1) {
      await dummyAsync();
      changeContent(1);
    }
    if(item2) {
      await dummyAsync();
      changeContent(2);
    }
    if(item3) {
      await dummyAsync();
      changeContent(3);
    }
});

function dummyAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 2000);
  });
}

function changeContent(item) {
  // Clear previous content
  const wrapper = document.querySelector('.content-wrapper');
  while(wrapper.firstChild) wrapper.removeChild(wrapper.firstChild);

  const dummyTable = `<div class="table">This is table number: ${item}</div>`;

  // Add table
  wrapper.insertAdjacentHTML('afterbegin', dummyTable);
};
</code>```

HTML & CSS

```<code><div class="menu">
  <div class="item item1">Item1</div>
  <div class="item item2">Item2</div>
  <div class="item item3">Item3</div>
</div>
<div class="content-wrapper">
  <div class="content">Content</div>
</div>

.menu {
  display: flex;
  justify-content: space-evenly;
  width: 20rem;
  border: 1px solid lightgrey;
}
.item {
  cursor: pointer;
  padding: 1rem;
  z-index: 2;
}

.content-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 2rem;
  border: 1px solid lightgrey;
  height: 20rem;
}

.table {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 25rem;
  height: 10rem;
  border: 1px dotted grey;
}
</code>```

答:
You'd want to use a debounce for this, this limits the number of function calls that are made in a certain period of time.

Here's an example using your code: https://codepen.io/rdenton93/pen/MWOoBVK

```<code>import lodashDebounce from "https://cdn.skypack.dev/lodash.debounce@4.0.8";

document.body.addEventListener('click', async e => {
  const item1 = e.target.closest('.item1');
  const item2 = e.target.closest('.item2');
  const item3 = e.target.closest('.item3');

    if(item1) {
      await dummyAsync();
      changeContent(1);
    }
    if(item2) {
      await dummyAsync();
      changeContent(2);
    }
    if(item3) {
      await dummyAsync();
      changeContent(3);
    }
})

function dummyAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 2000);
  });
}

const changeContent = lodashDebounce((item) => {
  // Clear previous content
  const wrapper = document.querySelector('.content-wrapper');
  while(wrapper.firstChild) wrapper.removeChild(wrapper.firstChild);

  const dummyTable = `<div class="table">This is table number: ${item}</div>`;

  // Add table
  wrapper.insertAdjacentHTML('afterbegin', dummyTable);
},1* 1000); // only make one request per second
</code>```

Body:
I've an admin page with multiple buttons that make axios calls to change the content. Each button makes a different call.

When the user clicks button 1, data is retrieved from the server to be displayed onscreen. But if the user clicks button 1, then 2 in quick succession, the UI displays data from 1, then 2.

This isn't necessarily a massive problem, but I would like to know the best approach, as it does cause me issues when animating the data with gsap (see below).

Is the best approach to try and using tokens to cancel the axios request?

Codepen: Non-animation example
A slightly different example with animation

JS

document.body.addEventListener('click', async e => {
  const item1 = e.target.closest('.item1');
  const item2 = e.target.closest('.item2');
  const item3 = e.target.closest('.item3');

    if(item1) {
      await dummyAsync();
      changeContent(1);
    }
    if(item2) {
      await dummyAsync();
      changeContent(2);
    }
    if(item3) {
      await dummyAsync();
      changeContent(3);
    }
});

function dummyAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 2000);
  });
}

function changeContent(item) {
  // Clear previous content
  const wrapper = document.querySelector('.content-wrapper');
  while(wrapper.firstChild) wrapper.removeChild(wrapper.firstChild);

  const dummyTable = `<div class="table">This is table number: ${item}</div>`;

  // Add table
  wrapper.insertAdjacentHTML('afterbegin', dummyTable);
};

HTML & CSS

Item1

Item2

Item3

Content

.menu {
  display: flex;
  justify-content: space-evenly;
  width: 20rem;
  border: 1px solid lightgrey;
}
.item {
  cursor: pointer;
  padding: 1rem;
  z-index: 2;
}

.content-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 2rem;
  border: 1px solid lightgrey;
  height: 20rem;
}

.table {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 25rem;
  height: 10rem;
  border: 1px dotted grey;
}

Body:
You'd want to use a debounce for this, this limits the number of function calls that are made in a certain period of time.

Here's an example using your code: https://codepen.io/rdenton93/pen/MWOoBVK

import lodashDebounce from "https://cdn.skypack.dev/lodash.debounce@4.0.8";

document.body.addEventListener('click', async e => {
  const item1 = e.target.closest('.item1');
  const item2 = e.target.closest('.item2');
  const item3 = e.target.closest('.item3');

    if(item1) {
      await dummyAsync();
      changeContent(1);
    }
    if(item2) {
      await dummyAsync();
      changeContent(2);
    }
    if(item3) {
      await dummyAsync();
      changeContent(3);
    }
})

function dummyAsync() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 2000);
  });
}

const changeContent = lodashDebounce((item) => {
  // Clear previous content
  const wrapper = document.querySelector('.content-wrapper');
  while(wrapper.firstChild) wrapper.removeChild(wrapper.firstChild);

  const dummyTable = `<div class="table">This is table number: ${item}</div>`;

  // Add table
  wrapper.insertAdjacentHTML('afterbegin', dummyTable);
},1* 1000); // only make one request per second