问:
Can you throttle requests rather than responses in Cypress?
I am trying to end to end test a file upload page in Cypress, which includes testing if a file upload progress bar works.

Unfortunately, in the local environment the upload happens instantly so the progress bar is not shown.

I am aware that you can throttle the response speed using cy.intercept() to simulate slow networks.  However, this isn't slowing the request upload speed:

cy.intercept('post', `/route`, (req) => {
    req.on('response', (res) => {
        res.setThrottle(1000)
    })
}).as('post')
```

Is there any way that I can apply a throttle to the outgoing request?

答:
I think Cypress itself can only throttle or delay responses using cy.intercept() as mentioned in the question and described here: Throttle or delay response all incoming responses

However, you can probably use the Chrome Debugger Protocol from Chrome DevTools for that. Here you have the function Network.emulateNetworkConditions that allows you to throttle both download and upload throughput. This approach then assumes that your tests run in Chrome.

If you're unsure how to use this in your Cypress tests, here is a blog post about testing an application in offline network mode that uses a similar approach with Network.enable: Testing an Application in Offline Network Mode

Body:
I am trying to end to end test a file upload page in Cypress, which includes testing if a file upload progress bar works.

Unfortunately, in the local environment the upload happens instantly so the progress bar is not shown.

I am aware that you can throttle the response speed using cy.intercept() to simulate slow networks.  However, this isn't slowing the request upload speed:

cy.intercept('post', `/route`, (req) => {
    req.on('response', (res) => {
        res.setThrottle(1000)
    })
}).as('post')

Is there any way that I can apply a throttle to the outgoing request?


来源: stackexchange

问:
how to optimise fitting of gauss-hermite function in python?
What I have done so far:

I am trying to fit noisy data (which I generated myself by adding random noise to my function) to Gauss-Hermite function that I have defined. It works well in some cases for lower values of h3 and h4 but every once in a while it will produce a really bad fit even for lower h3, h4 values, and for higher h3, h4 values, it always gives a bad fit.

My code:

```<code>import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as mpl
import matplotlib.pyplot as plt

# Let's define the Gauss-Hermite function
#a=amplitude, x0=location of peak, sig=std dev, h3, h4
def gh_func(x, a, x0, sig, h3, h4):

    return a*np.exp(-.5*((x-x0)/sig)**2)*(1+h3*((-np.sqrt(3))*((x-x0)/sig)+(2/np.sqrt(3))*((x-x0)/sig)**3)+ h4*((np.sqrt(6)/4)+(-np.sqrt(6))*((x-x0)/sig)**2+(np.sqrt(6)/3)*(((x-x0)/sig)**4)))

#generate clean data
x = np.linspace(-10, 20, 100)
y = gh_func(x, 10, 5, np.sqrt(3), -0.10,-0.03) #it gives okay fit for h3=-0.10, h4=-0.03 but bad fits for higher values like h3=-0.4 and h4=-0.3.

#add noise to data

noise=np.random.normal(0,np.sqrt(0.5),size=len(x))
yn = y + noise

fig = mpl.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, c='k', label='analytic function')
ax.scatter(x, yn, s=5, label='fake noisy data')
fig.savefig('model_and_noise_h3h4.png')
# Executing curve_fit on noisy data
popt, pcov = curve_fit(gh_func, x, yn)

#popt returns the best fit values for parameters of the given model (func)

print('Fitted Parameters (Gaus_Hermite):\na = %.10f , x0 = %.10f , sig = %.10f\nh3 = %.10f , h4 = %.10f' \
%(popt[0],popt[1],popt[2],popt[3],popt[4]))

ym = gh_func(x, popt[0], popt[1], popt[2], popt[3], popt[4])
ax.plot(x, ym, c='r', label='Best fit')
ax.legend()
fig.savefig('model_fit_h3h4.png')
plt.legend(loc='upper left')
plt.xlabel("v")
plt.ylabel("f(v)")
</code>```

What I want to do:

I want to find a better fitting method than just curve_fit from scipy.optimize but I am not sure what I can use. Even if we end up using curve_fit, I need a way to produce better fits by providing initial guesses for the parameters which are generated automatically, e.g. one approach for only single peak gaussian is described in the accepted answer of this post (Jean Jacquelin's method):gaussian fitting inaccurate for lower peak width using Python. But this is just for mu,sigma and amplitude not h3,h4.

Besides curve_fit from scipy.optimize, I think there's one called lmfit: https://lmfit.github.io/lmfit-py/  but I am not sure how I will implement it in my code. I do not want to use manual initial guesses for the parameters. I want to be able to find the fitting automatically.

Thanks a lot!

答:
Using lmfit for this fitting problem would be straightforward, by creating a  lmfit.Model from your gh_func, with something like

```<code>from lmfit import Model
gh_model = Model(gh_func)
params = gh_model.make_params(x0=?, a=?, sig=?, h3=?, h4=?)
</code>```

where those question marks would have to be initial values for the parameters in question.

Your use of scipy.optimize.curve_fit does not provide initial values for the variables.  Unfortunately, this does not raise an error or give an indication of a problem because the authors of scipy.optimize.curve_fit have lied to you by making initial values optional. Initial values for all parameters are always required for all non-linear least-squares analyses.  It is not a choice of the implementation, it is a feature of the mathematical algorithm. What curve_fit hides from you is that leaving p0=None makes all initial values 1.0. Whether that is remotely appropriate depends on the model and data being fit - it cannot be always reasonable.  As an example, if the x values for your data extended from 9000 to 9500, and the peak function was centered around 9200, starting with x0 of 1 would almost certainly not find a suitable fit.  It is always deceptive to imply in any way that initial values are optional.  They just are not.  Not sometimes, not for well-defined problems.  Initial values are never, ever optional.

Initial values don't have to be perfect, but they need to be of the right scale.  Many people will warn you about "false minima" - getting stuck at a solution that is not bad but not "best". My experience is that the more common problem people run into is initial values that are so far off that the model is just not sensitive to small changes in their values, and so can never be optimized (with x0=1,sig=1 for data with x on [9000, 9500] and centered at 9200 being exactly in that category).

The answer to your question for your essential question of "providing initial guesses for the parameters which are generated automatically" is hard to answer without knowing the properties of your model function. You might be able to use some heuristics to guess values from a data set. Lmfit has such heuristic "guess parameter values from data" functions for many peak-like functions.  You probably have some sense for the physical (or other domain) for h3 and h4 and know what kinds of values are reasonable, and can probably give better initial values than h3=h4=1. It might be that you want to start with guessing parameters as if the data was simple Gaussian (say, using lmfit.Model.guess_from_peak()) and then use the difference of that and your data to get the scale for h3 and h4.

ContentLicense: CC BY-SA 4.0

Body:
What I have done so far:

I am trying to fit noisy data (which I generated myself by adding random noise to my function) to Gauss-Hermite function that I have defined. It works well in some cases for lower values of h3 and h4 but every once in a while it will produce a really bad fit even for lower h3, h4 values, and for higher h3, h4 values, it always gives a bad fit.

My code:

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as mpl
import matplotlib.pyplot as plt

# Let's define the Gauss-Hermite function
#a=amplitude, x0=location of peak, sig=std dev, h3, h4
def gh_func(x, a, x0, sig, h3, h4):

    return a*np.exp(-.5*((x-x0)/sig)**2)*(1+h3*((-np.sqrt(3))*((x-x0)/sig)+(2/np.sqrt(3))*((x-x0)/sig)**3)+ h4*((np.sqrt(6)/4)+(-np.sqrt(6))*((x-x0)/sig)**2+(np.sqrt(6)/3)*(((x-x0)/sig)**4)))

#generate clean data
x = np.linspace(-10, 20, 100)
y = gh_func(x, 10, 5, np.sqrt(3), -0.10,-0.03) #it gives okay fit for h3=-0.10, h4=-0.03 but bad fits for higher values like h3=-0.4 and h4=-0.3.

#add noise to data

noise=np.random.normal(0,np.sqrt(0.5),size=len(x))
yn = y + noise

fig = mpl.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y, c='k', label='analytic function')
ax.scatter(x, yn, s=5, label='fake noisy data')
fig.savefig('model_and_noise_h3h4.png')
# Executing curve_fit on noisy data
popt, pcov = curve_fit(gh_func, x, yn)

#popt returns the best fit values for parameters of the given model (func)

print('Fitted Parameters (Gaus_Hermite):\na = %.10f , x0 = %.10f , sig = %.10f\nh3 = %.10f , h4 = %.10f' \
%(popt[0],popt[1],popt[2],popt[3],popt[4]))

ym = gh_func(x, popt[0], popt[1], popt[2], popt[3], popt[4])
ax.plot(x, ym, c='r', label='Best fit')
ax.legend()
fig.savefig('model_fit_h3h4.png')
plt.legend(loc='upper left')
plt.xlabel("v")
plt.ylabel("f(v)")

What I want to do:

I want to find a better fitting method than just curve_fit from scipy.optimize but I am not sure what I can use. Even if we end up using curve_fit, I need a way to produce better fits by providing initial guesses for the parameters which are generated automatically, e.g. one approach for only single peak gaussian is described in the accepted answer of this post (Jean Jacquelin's method):gaussian fitting inaccurate for lower peak width using Python. But this is just for mu,sigma and amplitude not h3,h4.

Besides curve_fit from scipy.optimize, I think there's one called lmfit: https://lmfit.github.io/lmfit-py/  but I am not sure how I will implement it in my code. I do not want to use manual initial guesses for the parameters. I want to be able to find the fitting automatically.

Thanks a lot!

Body:
Using lmfit for this fitting problem would be straightforward, by creating a  lmfit.Model from your gh_func, with something like

from lmfit import Model
gh_model = Model(gh_func)
params = gh_model.make_params(x0=?, a=?, sig=?, h3=?, h4=?)

where those question marks would have to be initial values for the parameters in question.

Your use of scipy.optimize.curve_fit does not provide initial values for the variables.  Unfortunately, this does not raise an error or give an indication of a problem because the authors of scipy.optimize.curve_fit have lied to you by making initial values optional. Initial values for all parameters are always required for all non-linear least-squares analyses.  It is not a choice of the implementation, it is a feature of the mathematical algorithm. What curve_fit hides from you is that leaving p0=None makes all initial values 1.0. Whether that is remotely appropriate depends on the model and data being fit - it cannot be always reasonable.  As an example, if the x values for your data extended from 9000 to 9500, and the peak function was centered around 9200, starting with x0 of 1 would almost certainly not find a suitable fit.  It is always deceptive to imply in any way that initial values are optional.  They just are not.  Not sometimes, not for well-defined problems.  Initial values are never, ever optional.

Initial values don't have to be perfect, but they need to be of the right scale.  Many people will warn you about "false minima" - getting stuck at a solution that is not bad but not "best". My experience is that the more common problem people run into is initial values that are so far off that the model is just not sensitive to small changes in their values, and so can never be optimized (with x0=1,sig=1 for data with x on [9000, 9500] and centered at 9200 being exactly in that category).

The answer to your question for your essential question of "providing initial guesses for the parameters which are generated automatically" is hard to answer without knowing the properties of your model function. You might be able to use some heuristics to guess values from a data set. Lmfit has such heuristic "guess parameter values from data" functions for many peak-like functions.  You probably have some sense for the physical (or other domain) for h3 and h4 and know what kinds of values are reasonable, and can probably give better initial values than h3=h4=1. It might be that you want to start with guessing parameters as if the data was simple Gaussian (say, using lmfit.Model.guess_from_peak()) and then use the difference of that and your data to get the scale for h3 and h4.


问:
What other attribute should i add for my Gorm table?
My goal is to simply join three tables (Sorry my knowledge in sql is limited)

I'm building a community-based platform like Patreon where each community can have different plans (Free, Paid)

Example Code:

```<code>type User struct {
    Communities []Community `gorm:"many2many:user_communities" json:"communities"`
}

type Community struct {
    UserID `json:"userID"`
    Users []User `gorm:"many2many:user_communities" json:"users"`
    Plans []Plan `json:"plans"`
    // How do i add another attirbute to check for user with different plan?
}

type Plan struct {
    CommunityID uint `json:"communityID"`
    Name string `json:"name"`
    Price string `json:"price"`
}
</code>```

Based on the model above

One user can join many communities

One community can have many users

One user can own a community (creator)

and for each community, one user can join for the different plans (Free, Paid)

I'm more focused on how to solve number 4

So the question here is what should I add for my community table to differentiate between the user who joins as Free plan or Paid plan?

because I can only query users who belong to a specific community not users who belong to that community based on a Free or Paid plan.

Example query

```<code>// Find whether that user belongs to a community
if err := database.Mysql.Table("users u").Joins("JOIN user_communities uc ON u.id = uc.user_id").Where("u.id = ? AND uc.community_id = ?", userID, communityID).Select("1").Scan(&found).Error; err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": "error happened"})
    return
}
</code>```

答:
One way could be to make the plan part of the many-to-many table.

I don't know gorm really, but in plain SQL this could look something like this.

schema:

create table appUser (
  id serial not null,
  name text not null,
  primary key (id)
);

create table Community (
  id serial not null,
  owner_id int not null,
  name text not null,
  primary key (id),
  foreign key (owner_id) references appUser(id)
);

create table plan (
  id serial not null,
  community_id int not null,
  name text not null,
  price float not null,
  primary key (id),
  foreign key (community_id) references Community(id)
);

create table UserCommunity (
  user_id int not null,
  community_id int not null,
  plan_id int not null,
  primary key (user_id, community_id),
  foreign key (plan_id) references plan(id)
);
```
<p>usage:</p>
<pre class="lang-sql prettyprint-override"><code>insert into appUser (name) values ('maria'), ('jose'), ('clara');

insert into Community (name, owner_id) values ('community1', 1);

insert into plan (community_id, name, price) values
(1, 'free', 0.0), (1, 'paid', 10.0);

insert into UserCommunity (user_id, community_id, plan_id) values
  (2, 1, 1), (3, 1, 2);

select
  appUser.name as "user",
  community.name as "community",
  plan.name as "plan"
from appUser
  join UserCommunity on appUser.id = UserCommunity.user_id
  join Community on Community.id = UserCommunity.community_id
  join plan on plan.id = UserCommunity.plan_id
where plan.name = 'paid';
</code>```

Fiddle: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=bd37832969396a40944f40ef17f18465

Body:
My goal is to simply join three tables (Sorry my knowledge in sql is limited)

I'm building a community-based platform like Patreon where each community can have different plans (Free, Paid)

Example Code:

type User struct {
    Communities []Community `gorm:"many2many:user_communities" json:"communities"`
}

type Community struct {
    UserID `json:"userID"`
    Users []User `gorm:"many2many:user_communities" json:"users"`
    Plans []Plan `json:"plans"`
    // How do i add another attirbute to check for user with different plan?
}

type Plan struct {
    CommunityID uint `json:"communityID"`
    Name string `json:"name"`
    Price string `json:"price"`
}

Based on the model above

One user can join many communities

One community can have many users

One user can own a community (creator)

and for each community, one user can join for the different plans (Free, Paid)

I'm more focused on how to solve number 4

So the question here is what should I add for my community table to differentiate between the user who joins as Free plan or Paid plan?

because I can only query users who belong to a specific community not users who belong to that community based on a Free or Paid plan.

Example query

// Find whether that user belongs to a community
if err := database.Mysql.Table("users u").Joins("JOIN user_communities uc ON u.id = uc.user_id").Where("u.id = ? AND uc.community_id = ?", userID, communityID).Select("1").Scan(&found).Error; err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": "error happened"})
    return
}

Body:
One way could be to make the plan part of the many-to-many table.

I don't know gorm really, but in plain SQL this could look something like this.

schema:

create table appUser (
  id serial not null,
  name text not null,
  primary key (id)
);

create table Community (
  id serial not null,
  owner_id int not null,
  name text not null,
  primary key (id),
  foreign key (owner_id) references appUser(id)
);

create table plan (
  id serial not null,
  community_id int not null,
  name text not null,
  price float not null,
  primary key (id),
  foreign key (community_id) references Community(id)
);

create table UserCommunity (
  user_id int not null,
  community_id int not null,
  plan_id int not null,
  primary key (user_id, community_id),
  foreign key (plan_id) references plan(id)
);

usage:

insert into appUser (name) values ('maria'), ('jose'), ('clara');

insert into Community (name, owner_id) values ('community1', 1);

insert into plan (community_id, name, price) values
(1, 'free', 0.0), (1, 'paid', 10.0);

insert into UserCommunity (user_id, community_id, plan_id) values
  (2, 1, 1), (3, 1, 2);

select
  appUser.name as "user",
  community.name as "community",
  plan.name as "plan"
from appUser
  join UserCommunity on appUser.id = UserCommunity.user_id
  join Community on Community.id = UserCommunity.community_id
  join plan on plan.id = UserCommunity.plan_id
where plan.name = 'paid';

Fiddle: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=bd37832969396a40944f40ef17f18465


问:
Vertical alignment of a div element in container
I am trying to understand why vertical alignment of an element in div container goes to bottom of the parent when max-heigh is set below 100%. When I click div.first it sets either class name short or long to next  element. Class name short sets max-width of 3em. Class name long sets max-width to 100%. However, when class name is set to short while class name of other elements is set to long the div with class name short aligns itself to the bottom of the container. How to make it positions to the top of the parent?</p>
```<code>    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="letters-hoder">

        <div class="letter" >
            <div class="first" id="a">A</div>
            <div >
            <ul id="a-ul" class="short">
                <li>Apple</li>
                <li>Amazon</li>
                <li>Alphabet</li>
                <li>Analog Devices</li>
                <li>Applied Materials</li>
            </ul>
            </div>
        </div>

        <div class="letter" >
            <div class="first" id="b">B</div>
            <div>
                <ul id="b-ul" class="short">
                    <li>Broadcom</li>
                    <li>Booking.com</li>
                    <li>Bank of America</li>
                    <li>Boeing</li>
                    <li>Biogen</li>
                </ul>
            </div>
        </div>

</div>
    <script>

    let letters = document.getElementsByClassName('first')

    for (var i = 0; i < letters.length; i++) {
        letters[i].addEventListener('click', handleClick, false);
    }

        function handleClick(evt){

            let checkElement = document.getElementById(evt.target.id + "-ul")
            console.log(checkElement)
            if(checkElement.className ==="long"){
                checkElement.className="short"
            }else{
                checkElement.className="long"
            }
        }

    </script>

    <style>

        div.first{
            background-color: rgb(246, 247, 223);
            font-weight: bold;
            padding-left:5px;
            padding-top:2px;
            padding-bottom:2px;
        }

        div.letter{
            margin-left:10px;
            border:1px solid lightgray;
            border-radius: 5px;

        }

        div.letters-hoder{
            display:flex;
            align-items:start;
        }

        ul{
            margin-top: 0;
            padding-left:0;
            list-style-type: none;
            overflow:hidden;

        }

        ul.short{
             max-height:4em;
        }

        ul.long{
             max-height:100%;
        }

        li{
            margin-left:0px;
            margin-right:0px;
            margin-top:2px;
            border-bottom: 1px solid white;
            transition: 100ms;
            padding-left:5px;
            padding-right:5px;
        }

        div.letter{
            display: inline-block;

        }

        li:hover{
            cursor:pointer;
            border-bottom: 1px solid lightgray;
        }
    </style>
</body>
</html>
</code>```

答:
Add this CSS it will work.</p>
```<code>#letters-hoder{
  display: flex;
  align-items: baseline;
}

</code>```

Body:
I am trying to understand why vertical alignment of an element in div container goes to bottom of the parent when max-heigh is set below 100%. When I click div.first it sets either class name short or long to next  element. Class name short sets max-width of 3em. Class name long sets max-width to 100%. However, when class name is set to short while class name of other elements is set to long the div with class name short aligns itself to the bottom of the container. How to make it positions to the top of the parent?

    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

A

Apple

Amazon

Alphabet

Analog Devices

Applied Materials

B

Broadcom

Booking.com

Bank of America

Boeing

Biogen

Body:
Add this CSS it will work.

#letters-hoder{
  display: flex;
  align-items: baseline;
}


问:
Typedef in C, but a different way
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32
```
<p>I was expecting this to work too:</p>
<pre class="lang-c prettyprint-override"><code>struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);
</code>```

Is it just not possible to do it or I am missing something?

答:
```<code>struct myStr {...};
</code>```

This defines a struct and also a tag name for it. These tags have their own namespace, but they must be always preceded by struct.

```<code>struct my {...};
</code>```

therefore is enough; as in sizeof(struct my).

For the typedef:

```<code>typedef struct my myStr;
</code>```

Now myStr is of struct my type. I would prefer my_t, even though the _t is reserved.

Both at once is also possible:

```<code>typedef struct my {...} myStr;
</code>```

Without typedef, myStr would be a struct my itself. With, it defines a new name for that type.

Title: Typedef in C, but a different way

Body:
I am aware of the standard way to define a structure in C. But, in analogy with this:

// <typedef structureName alias>
typedef unsigned long int u_int32

I was expecting this to work too:

struct myStr {char name[100]; float avgProb; int severity;};
typedef myStr ms;
myStr ms = {name:"hell", avgProb:50.0, severity:5,};
printf("myR %f", ms.avgProb);

Is it just not possible to do it or I am missing something?

Body:
struct myStr {...};

This defines a struct and also a tag name for it. These tags have their own namespace, but they must be always preceded by struct.

struct my {...};

therefore is enough; as in sizeof(struct my).

For the typedef:

typedef struct my myStr;

Now myStr is of struct my type. I would prefer my_t, even though the _t is reserved.

Both at once is also possible:

typedef struct my {...} myStr;

Without typedef, myStr would be a struct my itself. With, it defines a new name for that type.


问:
send html table data to google sheet via apps-script
trying to get the cell values from html table and send them to google sheet via apps script:

index.html:

```<code>     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }
</code>```

code.gs:

```<code>function addRows(values) {

  var doc = SpreadsheetApp.openById("id");
  var sheet = doc.getSheetByName('newdata');
  var lastrow = sheet.getLastRow();
   sheet.getRange(lastrow+1, 1, values.length, values[0].length).setValues(values);
}
</code>```

i got an error in the console uncaught addRows, it seems that the array is not detected on the server side, can anyone help
thanks in advance

答:
This works well for me

gs:

```<code>function showSidebar() {
  const html = HtmlService.createTemplateFromFile('index');
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function addRows(values) {
  Browser.msgBox(values)
}
</code>```

html:

```<code>  <script>
    function ok(){
     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

      alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }
  </script>
</code>```

note that you have to transform the result in a 2D Array, for instance

```<code>function addRows(values) {
  var tab = [values]
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  sheet.getRange(1, 1, tab.length, tab[0].length).setValues(tab)
}
</code>```

Body:
trying to get the cell values from html table and send them to google sheet via apps script:

index.html:

     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }

code.gs:

function addRows(values) {

  var doc = SpreadsheetApp.openById("id");
  var sheet = doc.getSheetByName('newdata');
  var lastrow = sheet.getLastRow();
   sheet.getRange(lastrow+1, 1, values.length, values[0].length).setValues(values);
}

i got an error in the console uncaught addRows, it seems that the array is not detected on the server side, can anyone help
thanks in advance

Body:
This works well for me

gs:

function showSidebar() {
  const html = HtmlService.createTemplateFromFile('index');
  var evaluatHTML = html.evaluate().setTitle('Sidebar')
  SpreadsheetApp.getUi().showSidebar(evaluatHTML)
};

function addRows(values) {
  Browser.msgBox(values)
}

html:

  <script>
    function ok(){
     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

      alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }
  </script>

note that you have to transform the result in a 2D Array, for instance

function addRows(values) {
  var tab = [values]
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  sheet.getRange(1, 1, tab.length, tab[0].length).setValues(tab)
}


问:
Special characters in prompt variables changed?
I'm currently trying to learn more about CLI with my new Macbook Pro M1 and try to customize my promt.

In my home directory it is showing:

```<code>johndoe@Johns-MacBook-Pro ~ %
</code>```

in order to find out more about this prompt, I've typed:

```<code>echo $PS1
// output: %n@%m %1~ %#
</code>```

The variables n and m do not fit the explanation found online: https://www.howtogeek.com/307701/how-to-customize-and-colorize-your-bash-prompt/

As they refer to a list of following env variables:

\h = Hostname

\u = User name

\w = Current directory

\W = Basename of current directory

\d = Current date

\n = Newline

...

According to these source, this command:

```<code>PS1="\u:\w\$ "
</code>```

should lead to following prompt:

```<code>user:working_directory$
</code>```

It seems the variables have changed and so did the character from \ to %.
And unfortunately I can not find any information about the new variables.

Does anybody know more about it or has a link to an explanation?

答:
You're using zsh, not bash. Description of prompt sequences is
explained in zshmisc(1) (type man 1 zshmisc too see it). For
reference, it says:

```<code>   %n     $USERNAME.
   %m     The hostname up to the first `.'.  An integer may follow the `%'
          to  specify  how  many  components  of the hostname are desired.
          With a negative integer, trailing components of the hostname are
          shown.
   %~     As  %d  and %/, but if the current working directory starts with
          $HOME, that part is replaced by a `~'. Furthermore, if it has  a
          named  directory  as  its prefix, that part is replaced by a `~'
          followed by the name of the directory, but only if the result is
          shorter  than the full path; see Dynamic and Static named direc‐
          tories in zshexpn(1).
</code>```

Body:
I'm currently trying to learn more about CLI with my new Macbook Pro M1 and try to customize my promt.

In my home directory it is showing:

johndoe@Johns-MacBook-Pro ~ %

in order to find out more about this prompt, I've typed:

echo $PS1
// output: %n@%m %1~ %#

The variables n and m do not fit the explanation found online: https://www.howtogeek.com/307701/how-to-customize-and-colorize-your-bash-prompt/

As they refer to a list of following env variables:

\h = Hostname

\u = User name

\w = Current directory

\W = Basename of current directory

\d = Current date

\n = Newline

...

According to these source, this command:

PS1="\u:\w\$ "

should lead to following prompt:

user:working_directory$

It seems the variables have changed and so did the character from \ to %.
And unfortunately I can not find any information about the new variables.

Does anybody know more about it or has a link to an explanation?

Body:
You're using zsh, not bash. Description of prompt sequences is
explained in zshmisc(1) (type man 1 zshmisc too see it). For
reference, it says:

   %n     $USERNAME.
   %m     The hostname up to the first `.'.  An integer may follow the `%'
          to  specify  how  many  components  of the hostname are desired.
          With a negative integer, trailing components of the hostname are
          shown.
   %~     As  %d  and %/, but if the current working directory starts with
          $HOME, that part is replaced by a `~'. Furthermore, if it has  a
          named  directory  as  its prefix, that part is replaced by a `~'
          followed by the name of the directory, but only if the result is
          shorter  than the full path; see Dynamic and Static named direc‐
          tories in zshexpn(1).


问:
iPhone is not rendering properly my website on slow networks
I am experiencing strange iPhone behavior on my site, it doesn't display page correctly on slow (edge) networks however all works fine via Wi-Fi.

the page seems to be truncated but the footer and header of it are fine, it just looks like the container/content is missing or shortened (no constant sizes). Any ideas?

cheers,

/Marcin

答: I'd look for timeouts, particularly if you have Javascript loaders.</p>

ContentLicense: CC BY-SA 3.0


问:
How fast does Microsoft Defenfder for Cloud scan documents in a blob?
I am considering using Microsoft Defender on Cloud for Blob storage. A couple of things that I can't seem to find answers to are the following:

When does the scan occur?

Does it scan immediately when the file is uploaded? Or on a schedule of some sorts?

How fast is the scan of the file?

I understand that it uses a hash to compare the file to know viruses, but how long does this take?

I have already referenced this question: How Can I Tell If Microsoft Defender Has Scanned A Blob (a blob with no virus). However, the answer didn't quite get to the point of speed.

Thank you

答: From the documentation: "Security alerts are triggered for the following scenarios (typically from 1-2 hours after the event):", where hash reputation scanning is one of the scenarios.</p>


问:
Cross Account AWS Cognito Lambda Trigger
I have Cognito pool in account (11111111) with a lambda trigger for PreSignUp where the lambda function is in account (22222222). Im able to create the Cognito pool successfully however when I try to execute an action such as CreateUser I get the error UnexpectedLambdaException: PreSignUp invocation failed due to configuration.

I've updated the lambda resource policy to allow cross account access with the following statements:

```<code>{
      "Sid": "xaccount",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::11111111:root"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-west-2:22222222:function:my-function"
}
</code>```

and

```<code>{
      "Sid": "AllowCognitoInvoke",
      "Effect": "Allow",
      "Principal": {
        "Service": "cognito-idp.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-west-2:22222222:function:my-function",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:cognito-idp:us-east-1:11111111:userpool/*"
        }
      }
 }
</code>```

Not sure what other configuration Im missing. Has anyone successfully setup something similar before?

答:
Following up on my question. AWS support confirmed that you cannot configure Congito triggers to call lambda functions in a different account.

You can setup cross account lambda triggers on a Pool using the cli but you cant do it via the AWS Console. So if you do end up using the cli to setup cross account lambda triggers just know there is no way to invoke those fucntions.

In the end, I replicated the lambda trigger functions in the same account as the Cognito pool

Body:
I have Cognito pool in account (11111111) with a lambda trigger for PreSignUp where the lambda function is in account (22222222). Im able to create the Cognito pool successfully however when I try to execute an action such as CreateUser I get the error UnexpectedLambdaException: PreSignUp invocation failed due to configuration.

I've updated the lambda resource policy to allow cross account access with the following statements:

{
      "Sid": "xaccount",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::11111111:root"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-west-2:22222222:function:my-function"
}

and

{
      "Sid": "AllowCognitoInvoke",
      "Effect": "Allow",
      "Principal": {
        "Service": "cognito-idp.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-west-2:22222222:function:my-function",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:cognito-idp:us-east-1:11111111:userpool/*"
        }
      }
 }

Not sure what other configuration Im missing. Has anyone successfully setup something similar before?


问:
How to convert an array of numbers to bitmap image in python?
How do I convert a list of 1D numbers to a bitmap image?

I tried the following but it seems it doesn't quite work.

from PIL import Image

def get_img():
  img = Image.new('RGB', (255,255), "black") # Create a new black image
  pixels = img.load() # Create the pixel map
  width, height = img.size
  for i in range(width):    # For every pixel:
    for j in range(height):
      pixels[i,j] = (i, j, 100) # Set the colour accordingly
  return pixels

display(get_img()) # <PixelAccess at 0x7fca63ded7d0>
```

答:
PIL.Image has a function that takes a numpy array and converts it to an image: Image.from_array. You can use it to generate B&W, grayscale, RGB or RGBA images easily.

In you case, the cleanest way to build the image is:

import numpy as np
from PIL import Image

def get_img(width=255, height=255):
    data = np.arange(width * height, dtype=np.int64).reshape((height, width))
    img_data = np.empty((height, width, 3), dtype=np.uint8)
    img_data[:, :, 0] = data // height
    img_data[:, :, 1] = data % width
    img_data[:, :, 2] = 100
    return Image.fromarray(img_data)

display(get_img())
```

Result:

Note that although this way of building the data needs to go through the array 3 times, it is still faster than plain-python loops. For the default values of 255 by 255 images, it is almost 30 times faster.

Body:
PIL.Image has a function that takes a numpy array and converts it to an image: Image.from_array. You can use it to generate B&W, grayscale, RGB or RGBA images easily.

In you case, the cleanest way to build the image is:

import numpy as np
from PIL import Image

def get_img(width=255, height=255):
    data = np.arange(width * height, dtype=np.int64).reshape((height, width))
    img_data = np.empty((height, width, 3), dtype=np.uint8)
    img_data[:, :, 0] = data // height
    img_data[:, :, 1] = data % width
    img_data[:, :, 2] = 100
    return Image.fromarray(img_data)

display(get_img())

Result:

Note that although this way of building the data needs to go through the array 3 times, it is still faster than plain-python loops. For the default values of 255 by 255 images, it is almost 30 times faster.


问:
Convert Text-Formatted "Day Name, Month Name, Date of Month, Year" to "YYYY-MM-DD" Date Format
I have an Excel sheet with thousands of dates saved in Text format, written the following way:

I want these cells to be converted into "YYYY-MM-DD" format. However, Excel cannot detect these cells as Date Format; hence, when I try to use the "Format Cells" (or Ctrl+1) to change the date format, it does not work and stays the same. I need them to be in "YYYY-MM-DD" because I will be using the date in multiple functions throughout my workbook and the Text formatted Dates do not allow that.

答:
However, you can also use the Text To Columns inbuilt feature of Excel From Data Tab to turn those text formatted dates to actual Excel Dates, please follow the steps,

• Select The Range, In Image Below, Its A:A,

• Next From Data Tab, Click Text To Columns

• In Text To Columns Wizard - Step 1 Of 3 - Click Fixed Width Under Original Data Type and Press Next

• In The Step 2 Of 3 - Move The Lines With Arrow As Shown In The Image Below &
Press Next

Lines With Arrows(Signifies A Column Break)

• The Last & Final Step --> Step 3 Of 3, Under Data Preview, Select The Days Column  And Click -- Do Not Import Column(Skip) From Above Column Data Format & Same Way For The Last Blank Column As Well, Now Click The Date Column And Select From Above Column Data Format as Date (MDY) & Press Finish!

• To Confirm Whether Those Have Been Converted To Actual Excel Date Or Not, You May Use A Formula Like Below Or While Changing The Date Format You Can Select General Or Number Category To Verify

FORMULA USED TO VERIFY IN CELL B1

```<code>=ISNUMBER(A1)
</code>```

And You Are Done!

Body:
However, you can also use the Text To Columns inbuilt feature of Excel From Data Tab to turn those text formatted dates to actual Excel Dates, please follow the steps,

• Select The Range, In Image Below, Its A:A,

• Next From Data Tab, Click Text To Columns

• In Text To Columns Wizard - Step 1 Of 3 - Click Fixed Width Under Original Data Type and Press Next

• In The Step 2 Of 3 - Move The Lines With Arrow As Shown In The Image Below &
Press Next

Lines With Arrows(Signifies A Column Break)

• The Last & Final Step --> Step 3 Of 3, Under Data Preview, Select The Days Column  And Click -- Do Not Import Column(Skip) From Above Column Data Format & Same Way For The Last Blank Column As Well, Now Click The Date Column And Select From Above Column Data Format as Date (MDY) & Press Finish!

• To Confirm Whether Those Have Been Converted To Actual Excel Date Or Not, You May Use A Formula Like Below Or While Changing The Date Format You Can Select General Or Number Category To Verify

FORMULA USED TO VERIFY IN CELL B1

=ISNUMBER(A1)

And You Are Done!


问:
no "go to definition" and no function definition pop-up for golang code
I am using visual studio code to code in golang.

For this particular code example: https://golang.org/pkg/net/rpc/, I can't see any function definition pop-up, nor can I use "go to definition" in vscode by pressing F12. I can see the definition pop-up in other projects on my computer.

I have set my gopath in .bashrc in ubuntu 16.04 using the env.sh

All the plugin and visual studio code versions are the latest. What should I do to use the function definition prompt?

update: the problem is now solved by setting:

```<code>export GOPATH=`pwd`
</code>```

instead of:

```<code>export GOPATH=${GOPATH}:`pwd`
</code>```

Thank you all!Though I still have no idea to have multiple gopath working.

答: In my case, just run go mod tidy.

Body:
I am using visual studio code to code in golang.

For this particular code example: https://golang.org/pkg/net/rpc/, I can't see any function definition pop-up, nor can I use "go to definition" in vscode by pressing F12. I can see the definition pop-up in other projects on my computer.

I have set my gopath in .bashrc in ubuntu 16.04 using the env.sh

All the plugin and visual studio code versions are the latest. What should I do to use the function definition prompt?

update: the problem is now solved by setting:

export GOPATH=`pwd`

instead of:

export GOPATH=${GOPATH}:`pwd`

Thank you all!Though I still have no idea to have multiple gopath working.

Body: In my case, just run go mod tidy.


问:
LDAP python 3 (not working) but in PHP (working) where is the problem?
Python 3 code - not working:

import ldap3 as ldap

SERVER_NAME = 'serverip'
DN = 'dc=mydomain,dc=com,dc=br,ou=people'
USERNAME = 'no-reply'
PASSWORD = 'mypassword'

server = ldap.Server(SERVER_NAME,port=389, get_info='ALL')
connection = ldap.Connection(server, user='{}\\{}'.format(DN, USERNAME), password=PASSWORD)
connection.open()
if connection.bind():
    print('Authenticated!')
else:
    print('Not Authenticated')
    print(connection.result)
```
<p><strong>This is print result</strong></p>
<blockquote>
<p>Not Authenticated
{'result': 34, 'description': 'invalidDNSyntax', 'dn': '', 'message': >'invalid DN', 'referrals': None, 'saslCreds': None, 'type': 'bindResponse'}</p>
</blockquote>
<p>PHP code - working:</p>
<pre class="lang-php prettyprint-override"><code><?php
$username="no-reply";
$pass="mypassword";

$ldapconfig['host'] = 'serverip';
$ldapconfig['port'] = '389';
$ldapconfig['basedn'] = 'dc=mydomain,dc=com,dc=br';
$ldapconfig['usersdn'] = 'ou=people';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$dn="uid=".$username.",".$ldapconfig['usersdn'].",".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $pass)) {
  $ldap_result = @ldap_search($ds, $dn, "uid=".$username);
  $result = ldap_get_entries($ds, $ldap_result);
  print_r($result);
} else {
  print_r(new Exception("Error"));
}
?>
</code>```

I'm writing Python 3 code to use LDAP, but authentication is not working. However, my old code written in PHP works successfully. Where is the problem in my Python code?

答:
I managed to solve the problem, it was necessary to rewrite the code simplifying the commands.

```<code>from ldap3 import Server, Connection, ALL, SUBTREE

username = 'no-reply'
password = 'mypassword'
serverName   = 'ip_address'
DC = 'ou=people,dc=domain,dc=com,dc=contry'
server = Server(serverName, get_info=ALL)
conn = Connection(server, 'uid='+username+','+DC, password, auto_bind=True)
conn.search(search_base = DC,
                             search_filter = '(uid='+username+')',
                             search_scope = SUBTREE,
                             attributes = ['cn', 'givenName', 'company', 'title' ],
                             paged_size = 5)
print(conn.entries)
</code>```

Body:
Python 3 code - not working:

import ldap3 as ldap

SERVER_NAME = 'serverip'
DN = 'dc=mydomain,dc=com,dc=br,ou=people'
USERNAME = 'no-reply'
PASSWORD = 'mypassword'

server = ldap.Server(SERVER_NAME,port=389, get_info='ALL')
connection = ldap.Connection(server, user='{}\\{}'.format(DN, USERNAME), password=PASSWORD)
connection.open()
if connection.bind():
    print('Authenticated!')
else:
    print('Not Authenticated')
    print(connection.result)

This is print result

Not Authenticated
{'result': 34, 'description': 'invalidDNSyntax', 'dn': '', 'message': >'invalid DN', 'referrals': None, 'saslCreds': None, 'type': 'bindResponse'}

PHP code - working:

<?php
$username="no-reply";
$pass="mypassword";

$ldapconfig['host'] = 'serverip';
$ldapconfig['port'] = '389';
$ldapconfig['basedn'] = 'dc=mydomain,dc=com,dc=br';
$ldapconfig['usersdn'] = 'ou=people';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$dn="uid=".$username.",".$ldapconfig['usersdn'].",".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $pass)) {
  $ldap_result = @ldap_search($ds, $dn, "uid=".$username);
  $result = ldap_get_entries($ds, $ldap_result);
  print_r($result);
} else {
  print_r(new Exception("Error"));
}
?>

I'm writing Python 3 code to use LDAP, but authentication is not working. However, my old code written in PHP works successfully. Where is the problem in my Python code?

Body:
I managed to solve the problem, it was necessary to rewrite the code simplifying the commands.

from ldap3 import Server, Connection, ALL, SUBTREE

username = 'no-reply'
password = 'mypassword'
serverName   = 'ip_address'
DC = 'ou=people,dc=domain,dc=com,dc=contry'
server = Server(serverName, get_info=ALL)
conn = Connection(server, 'uid='+username+','+DC, password, auto_bind=True)
conn.search(search_base = DC,
                             search_filter = '(uid='+username+')',
                             search_scope = SUBTREE,
                             attributes = ['cn', 'givenName', 'company', 'title' ],
                             paged_size = 5)
print(conn.entries)


答:
You declared type specifier struct myStr.

```<code>struct myStr {char name[100]; float avgProb; int severity;};
</code>```

Thus in this typedef declaration

```<code>typedef myStr ms;
</code>```

the name myStr is undefined. To refer to the name myStr you need to precede it with the keyword struct like struct myStr.

You have to write

```<code>typedef struct myStr ms;
</code>```

So now ms becomes a type specifier that is an alias for the type specifier struct myStr..

Alternatively you may rewrite the typedef declaration also the following way

```<code>struct myStr typedef me;
</code>```

This declaration and the initializer list are incorrect.

```<code>myStr ms = {name:"hell", avgProb:50.0, severity:5,};
</code>```

You need to write for example

```<code>ms s = { .name = "hell", .avgProb = 50.0, .severity = 5,};
</code>```

or

```<code>ms s = { "hell", 50.0, 5,};
</code>```

Pay attention to that the last comma though may be present but is redundant.

If you wanted to have this declaration

```<code>myStr ms = { .name = "hell", .avgProb = 50.0, .severity = 5,};
</code>```

then the typedef declaration should look like

```<code>typedef struct myStr myStr;
</code>```

or

```<code>struct myStr typedef myStr;
</code>```

Title: Typedef in C, but a different way

Body:
You declared type specifier struct myStr.

struct myStr {char name[100]; float avgProb; int severity;};

Thus in this typedef declaration

typedef myStr ms;

the name myStr is undefined. To refer to the name myStr you need to precede it with the keyword struct like struct myStr.

You have to write

typedef struct myStr ms;

So now ms becomes a type specifier that is an alias for the type specifier struct myStr..

Alternatively you may rewrite the typedef declaration also the following way

struct myStr typedef me;

This declaration and the initializer list are incorrect.

myStr ms = {name:"hell", avgProb:50.0, severity:5,};

You need to write for example

ms s = { .name = "hell", .avgProb = 50.0, .severity = 5,};

or

ms s = { "hell", 50.0, 5,};

Pay attention to that the last comma though may be present but is redundant.

If you wanted to have this declaration

myStr ms = { .name = "hell", .avgProb = 50.0, .severity = 5,};

then the typedef declaration should look like

typedef struct myStr myStr;

or

struct myStr typedef myStr;


问:
Show/Hide divs based on Time/Opening Hours
I am trying to show/hide divs based on opening hours.

The div .open contains the headline "Our store is open" and the other div .close contains the headline "Our store is close".

The store has the following opening hours:

Monday: 09:00-12:00 & 14:00-18:00

Tuesday: 08:30-12:00 & 13:30-18:00

Wednesday: 09:00-12:00 & 14:30-18:00

Thursday: 09:00-12:00 & 14:00-18:00

Friday: 09:00-12:00 & 14:30-18:00

Saturday: 08:00-11:30

Sunday: Closed

The timezone is Germany (UTC+1).

So during the opening hours the div with the class .open should be displayed and the other div with the class .close should be hidden.

During the closed times the div with the class .close should be displayed and the div with the class .open should be hidden.

I also tried to add special days when the store is closed for a whole day. E.g. December 24 & December 26.

I have tried so much but always failed, I hope someone can help me with this.
Really appreciate any comment on this as i search for a solution for hours now.

I have tried the following Code (it works, but only with start & end time – I have not managed to get the breaks in each day. Likewise, I didn't manage to decline the special days (December 24 & 26) as closed):

var openHours = [
    {
        openHour: -1,
        openMinute: -1,
        closeHour: -1,
        closeMinute: -1,
    },
    {
        openHour: 9,
        openMinute: 00,
        closeHour: 18,
        closeMinute: 00,
    },
    {
        openHour: 8,
        openMinute: 30,
        closeHour: 18,
        closeMinute: 00,
    },
    {
        openHour: 9,
        openMinute: 00,
        closeHour: 18,
        closeMinute: 00,
    },
    {
        openHour: 9,
        openMinute: 00,
        closeHour: 18,
        closeMinute: 00,
    },
    {
        openHour: 9,
        openMinute: 00,
        closeHour: 18,
        closeMinute: 00,
    },
    {
        openHour: 8,
        openMinute: 00,
        closeHour: 11,
        closeMinute: 30,
    }
];

var d = new Date();
var dayOfWeek = d.getDay();
var hour = d.getHours();
var mins = d.getMinutes();
var open = true;
var todayHours = openHours[dayOfWeek];

if (hour >= todayHours.openHour && hour <= todayHours.closeHour) {
    if ((hour==todayHours.openHour && mins < todayHours.openMinute) || (hour==todayHours.closeHour && mins > todayHours.closeMinute)) {
        open = false;
    } else {
        open = true;
    }
} else {
    open = false;
}

if (open) {
    $('.open').show();
    $('.close').hide();
} else {
    $('.open').hide();
    $('.close').show();
}```

答:
I think, your code should work... The following works for me:

const openHours = [{
    openHour: -1,
    openMinute: -1,
    closeHour: -1,
    closeMinute: -1,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 8,
    openMinute: 30,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 8,
    openMinute: 00,
    closeHour: 11,
    closeMinute: 30,
  }
];

const d = new Date("February 14, 2022 18:00:00");
const dayOfWeek = d.getDay();
const hour = d.getHours();
const mins = d.getMinutes();
const todayHours = openHours[dayOfWeek];

let open = true;

if (hour >= todayHours.openHour && hour <= todayHours.closeHour) {
  if ((hour == todayHours.openHour && mins < todayHours.openMinute) || (hour == todayHours.closeHour && mins > todayHours.closeMinute)) {
    open = false;
  } else {
    open = true;
  }
} else {
  open = false;
}

if (open) {
  document.querySelector(".isopen.close").classList.add("hide");
} else {
  document.querySelector(".isopen.open").classList.add("hide");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.isopen {
  color: white;
  font-size: 2rem;
  width: max-content;
  padding: 1rem;
  margin: auto;
  height: 3rem;
  text-align: center;
}

div.isopen.open {
  background-color: green;
}

div.isopen.close {
  background-color: red;
}

div.isopen.hide {
  display: none;
}</code>```

Open

Closed
```

Body:
I think, your code should work... The following works for me:

const openHours = [{
    openHour: -1,
    openMinute: -1,
    closeHour: -1,
    closeMinute: -1,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 8,
    openMinute: 30,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 9,
    openMinute: 00,
    closeHour: 18,
    closeMinute: 00,
  },
  {
    openHour: 8,
    openMinute: 00,
    closeHour: 11,
    closeMinute: 30,
  }
];

const d = new Date("February 14, 2022 18:00:00");
const dayOfWeek = d.getDay();
const hour = d.getHours();
const mins = d.getMinutes();
const todayHours = openHours[dayOfWeek];

let open = true;

if (hour >= todayHours.openHour && hour <= todayHours.closeHour) {
  if ((hour == todayHours.openHour && mins < todayHours.openMinute) || (hour == todayHours.closeHour && mins > todayHours.closeMinute)) {
    open = false;
  } else {
    open = true;
  }
} else {
  open = false;
}

if (open) {
  document.querySelector(".isopen.close").classList.add("hide");
} else {
  document.querySelector(".isopen.open").classList.add("hide");
}

div.isopen {
  color: white;
  font-size: 2rem;
  width: max-content;
  padding: 1rem;
  margin: auto;
  height: 3rem;
  text-align: center;
}

div.isopen.open {
  background-color: green;
}

div.isopen.close {
  background-color: red;
}

div.isopen.hide {
  display: none;
}

<div class="isopen open">Open</div>
<div class="isopen close">Closed</div>


问:
Why can't I run a python command via a powershell script?
I have a powershell script which is meant to create a virtual environment with the following command:

```<code>py -3.6 -m venv --clear env
</code>```

I have verified that I can do this when I run the above command in a powershell window, and the environment is created. However when I run the powershell script via an azure release pipeline, I get the following error:

```<code>python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
</code>```

I have verified that my user PATH environment variable has all the necessary paths:

```<code>C:\Python36\Scripts\;C:\Python36\;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;C:\Python36\Lib\site-packages\pywin32_system32;C:\Python36\Lib\site-packages\win32;C:\Automation\app\env\Scripts;C:\Python38;C:\Python38\Scripts;C:\Python38\Lib\site-packages\win32;C:\Python38\Lib\site-packages\pywin32_system32
</code>```

Specs:

Python: 3.6.7
OS: Windows 10
Environment: Azure virtual machine.

Any help would be much appreciated.

答:
There seems to be a change when the variable is injected into the pipeline.

Try using:

```<code>PYTHON -3_6 -M VENV --clear ENV
</code>```

Environment variables:
Environment variables are specific to the operating system you are using. They are injected into a pipeline in platform-specific ways. The format corresponds to how environment variables get formatted for your specific scripting platform.

On UNIX systems (macOS and Linux), environment variables have the format $NAME. On Windows, the format is %NAME% for batch and $env:NAME in PowerShell.

System and user-defined variables also get injected as environment variables for your platform. When variables are turned into environment variables, variable names become uppercase, and periods turn into underscores. For example, the variable name any.variable becomes the variable name $ANY_VARIABLE.

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#environment-variables

Body:
I have a powershell script which is meant to create a virtual environment with the following command:

py -3.6 -m venv --clear env

I have verified that I can do this when I run the above command in a powershell window, and the environment is created. However when I run the powershell script via an azure release pipeline, I get the following error:

python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I have verified that my user PATH environment variable has all the necessary paths:

C:\Python36\Scripts\;C:\Python36\;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;C:\Python36\Lib\site-packages\pywin32_system32;C:\Python36\Lib\site-packages\win32;C:\Automation\app\env\Scripts;C:\Python38;C:\Python38\Scripts;C:\Python38\Lib\site-packages\win32;C:\Python38\Lib\site-packages\pywin32_system32

Specs:

Python: 3.6.7
OS: Windows 10
Environment: Azure virtual machine.

Any help would be much appreciated.

Body:
There seems to be a change when the variable is injected into the pipeline.

Try using:

PYTHON -3_6 -M VENV --clear ENV

Environment variables:
Environment variables are specific to the operating system you are using. They are injected into a pipeline in platform-specific ways. The format corresponds to how environment variables get formatted for your specific scripting platform.

On UNIX systems (macOS and Linux), environment variables have the format $NAME. On Windows, the format is %NAME% for batch and $env:NAME in PowerShell.

System and user-defined variables also get injected as environment variables for your platform. When variables are turned into environment variables, variable names become uppercase, and periods turn into underscores. For example, the variable name any.variable becomes the variable name $ANY_VARIABLE.

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#environment-variables


问:
pixi-essentials/SVG libtess.js library is undefined when I use SvgScene
Types of the library seem to not be recognized from typescript.
here is the error in chrome dev tools</p>

答:
The issue was with the libtess library itself. What fixed it was wraping the .min.js file like this:</p>
```<code>var libtess = (function() {
...
return this.libtess;
}).apply(new Object());
</code>```

Body:
The issue was with the libtess library itself. What fixed it was wraping the .min.js file like this:

var libtess = (function() {
...
return this.libtess;
}).apply(new Object());


问:
Hosting multiple applications using Azure Virtual Machine Scale Sets
Currently we own an application (App-A) which is hosted on Service Fabric cluster using VMSS instances. The VMSS instance has a public IP which points to App-A to route customer traffic. I want to add a new application (App-B) to the same service fabric cluster. How can I use the same VMSS instance to route customer traffic between App-A and App-B?</p>

答:
You can deploy AppB to listen on a different HTTP / HTTPS, that way the applications can run side by side on the same VM instance.
https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-service-manifest-resources</p>


问:
SQLAlchemy disable cascade on a relationship
In my database I have a view called my_view. I use the view to join it with another table my_table. Cause I don't now a way to map a view with the orm-mapper of SQLAlchemy, I mapped my_view like any other table. I give the primary-key in the relationship definition:

some_value = relationship("MyView", primaryjoin=my_view_id == MyView.id, useList=False)

This for fine, until I try to delete from my_table. The error is:

AssertionError: Dependency rule tried to blank-out primary key column 'my_view.id' on Instance '<MyView at 0x...>'

I am sure, the error happens, cause the mapper tries to delete a row from my_view. I found the cascade parameter, but I don't find out how I can stop it.

答:
You can use the relationship option: passive_deletes="all"

See https://docs-sqlalchemy.readthedocs.io/ko/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.passive_deletes

Additionally, setting the flag to the string value ‘all’ will disable
the “nulling out” of the child foreign keys, when there is no delete
or delete-orphan cascade enabled. This is typically used when a triggering
or error raise scenario is in place on the database side.


问:
Quasar Dialog Plugin fails to load with "TypeError: Cannot read properties of null (reading 'show')"
I'm trying to open a dialog from a separate component using the Quasar Dialog Plugin method described here, but when I click the button that should open the dialog, I get the following error in the console:

TypeError: Cannot read properties of null (reading 'show')

答:
The solution was to add ref="dialogRef" to the opening <q-dialog> tag of my dialog component as shown here.

Here's a screenshot of the diff that got it working:

As you can see in the screenshot, I was also missing the @hide handler and the class="q-dialog-plugin" class on the opening <q-card> tag, but those wouldn't have prevented the dialog from loading (I checked).


问:
How should I change currentIndex property of BottomNavigationBar on Navigating to another screen?
I have a bottom navigation bar widget for my Flutter app. On tapping specific item it is navigating to another screen. However, I don't know how to update current index in this case so that selected tab gets highlighted. Here is my code:

```<code>        BottomNavigationBar(
          backgroundColor: const Color(0xffFF7B19),
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              label: 'Events',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              label: 'Councils',
            ),
          ],
          currentIndex: 0,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
            }
          })
</code>```

I have tried creating a variable _selectedIndex for this which I was updating inside the function I have provided for onTap as shown:

```<code>          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
              _selectedIndex = 0;
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
              _selectedIndex = 1;
            }
</code>```

But this doesn't seems to work. I couldn't figure out how to do this.

答:
You could go with the first answer or you could go with TabBarView

```<code>return DefaultTabController(
  length: 2,
  child: Scaffold(
    body: TabBarView(
      children: [
        Container(),
        Container()
      ]
    ),
    bottomNavigationBar: TabBar(
      tabs: [
          GestureDetector(
            onTap: () {
              Navigator.push(context,
                MaterialPageRoute(builder: (context) => AllEventsScreen()));
            },
            child: Tab(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              text: 'Events',
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.push(
                context, MaterialPageRoute(builder: (context) => Councils()));
            },
            child: Tab(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              text: 'Councils',
            ),
          )]
    )
  ),
);
</code>```

Body:
I have a bottom navigation bar widget for my Flutter app. On tapping specific item it is navigating to another screen. However, I don't know how to update current index in this case so that selected tab gets highlighted. Here is my code:

        BottomNavigationBar(
          backgroundColor: const Color(0xffFF7B19),
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              label: 'Events',
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              label: 'Councils',
            ),
          ],
          currentIndex: 0,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
            }
          })

I have tried creating a variable _selectedIndex for this which I was updating inside the function I have provided for onTap as shown:

          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
            if (index == 0) {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AllEventsScreen()));
              _selectedIndex = 0;
            } else {
              Navigator.push(
                  context, MaterialPageRoute(builder: (context) => Councils()));
              _selectedIndex = 1;
            }

But this doesn't seems to work. I couldn't figure out how to do this.

Body:
You could go with the first answer or you could go with TabBarView

return DefaultTabController(
  length: 2,
  child: Scaffold(
    body: TabBarView(
      children: [
        Container(),
        Container()
      ]
    ),
    bottomNavigationBar: TabBar(
      tabs: [
          GestureDetector(
            onTap: () {
              Navigator.push(context,
                MaterialPageRoute(builder: (context) => AllEventsScreen()));
            },
            child: Tab(
              icon: Icon(
                Icons.calendar_today_rounded,
                size: lh / 25,
              ),
              text: 'Events',
            ),
          ),
          GestureDetector(
            onTap: () {
              Navigator.push(
                context, MaterialPageRoute(builder: (context) => Councils()));
            },
            child: Tab(
              icon: Icon(
                Icons.people_alt_outlined,
                size: lh / 25,
              ),
              text: 'Councils',
            ),
          )]
    )
  ),
);


问:
I made a Student registration program using arraylist in Java and had problems in arranging the result in descending order by Percentage
When I run the option to sort the results, the first 2 are in correct form but the remaining are just the copy of the 2nd detail. The other functions run fairly smoothly, the only problem I am facing is with the sort() function. I have given it much thoughts to no avail.

import java.util.ArrayList;
import java.util.Scanner;

class Test {

    public static int totaln=0;
    public static ArrayList<String> fname;
    public static ArrayList<String> lname;
    public static ArrayList<String> dob;
    public static ArrayList<String> gender;
    public static ArrayList<Integer> standard;
    public static ArrayList<Integer> rollno;
    public static ArrayList<Float> maths;
    public static ArrayList<Float> science;
    public static ArrayList<Float> social;
    public static ArrayList<Float> eng;
    public static ArrayList<Float> percentage ;

     public static void entry() {

        int num;

        Scanner sc=new Scanner(System.in);
         fname= new ArrayList<>();
         lname= new ArrayList<>();
         dob= new ArrayList<>();
         gender= new ArrayList<>();
         standard= new ArrayList<>();
         rollno= new ArrayList<>();
         maths =new ArrayList<>();
         science = new ArrayList<>();
         social = new ArrayList<>();
         eng = new ArrayList<>();
         percentage = new ArrayList<>();

        System.out.print("Enter the number of students: ");
        num = sc.nextInt();
        if(num==0 || num<0){
            System.out.println("Invalid Entry.");
        }
           else {
                for (int i = 0; i < num; i++) {
                    System.out.println();
                    System.out.println("Student: " +(i+1));
                    System.out.print("Enter the standard: ");
                    standard.add(sc.nextInt());
                    System.out.print("Enter the first name: ");
                    fname.add(sc.next());
                    System.out.print("Enter the last name: ");
                    lname.add(sc.next());
                    System.out.print("Enter the roll no: ");
                    rollno.add(sc.nextInt());
                    System.out.print("Enter the date of birth: ");
                    dob.add(sc.next());
                    System.out.print("Enter the gender: ");
                    gender.add(sc.next());
                    System.out.print("Enter the marks in Maths: ");
                    maths.add(sc.nextFloat());
                    System.out.print("Enter the marks in Science: ");
                    science.add(sc.nextFloat());
                    System.out.print("Enter the marks in Social: ");
                    social.add(sc.nextFloat());
                    System.out.print("Enter the marks in English: ");
                    eng.add(sc.nextFloat());
                    percentage.add((maths.get(i)+ science.get(i)+ social.get(i)+ eng.get(i))/4);
                }
                totaln+=num;

            }

    }
    public static void display(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Student Details");
            for (int i=0;i<totaln;i++){
                System.out.println();
                System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                System.out.println("Standard: "+standard.get(i));
                System.out.println("Roll no: " +rollno.get(i));
                System.out.println("Date of birth: " +dob.get(i));
                System.out.println("Gender: " +gender.get(i));
                System.out.println("Percentage: " +percentage.get(i));
            }

        }

    }
    public static void search(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            System.out.println();
            System.out.println("Enter the roll no of the student to search: ");
            roll = sc.nextInt();
            int s=0;

            for(int i=0;i<totaln;i++){
                if(roll==rollno.get(i)){
                    s=s+1;
                    System.out.println();
                    System.out.println("Name " +fname.get(i)+" "+lname.get(i));
                    System.out.println("Standard: "+standard.get(i));
                    System.out.println("Roll no: " +rollno.get(i));
                    System.out.println("Maths: "+maths.get(i));
                    System.out.println("Science: "+science.get(i));
                    System.out.println("Social: "+social.get(i));
                    System.out.println("English: "+eng.get(i));
                    System.out.println("Percentage: " +percentage.get(i));

                }

            }
            if(s>0) {
                System.out.println("Invalid entry. ");
            }
        }

    }
    public static void sort(){
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int c= percentage.size();
            for (int i=0; i<c-1; i++)
            {
                int pos = i;
                for (int j=i+1; j<c; j++)
                {
                    if (percentage.get(j) > percentage.get(pos))
                    {
                        pos = j;
                    }
                }
                float t1 = percentage.get(pos);
                percentage.add(pos, percentage.get(i)) ;
                percentage.add(i,t1);

                String f = fname.get(pos);
                fname.add(pos,fname.get(i));
                fname.add(i,f);

                String l = lname.get(pos);
                lname.add(pos,lname.get(i));
                lname.add(i,l);
            }
            System.out.println("The required order: ");

            for (int i=0;i<3;i++){
                System.out.println("Rank: " +(i+1));
                System.out.println("Percentage: "+percentage.get(i));
                System.out.println("Name: " +fname.get(i)+" "+lname.get(i));
            }

        }
    }

    public static void delete(){
        int roll;
        Scanner sc= new Scanner(System.in);
        if(totaln==0){
            System.out.println("No data has been entered.");
        }
        else{
            int choice;
            System.out.println("Enter 1 to delete all record:");
            System.out.println("Enter 2 to delete the record of a student");
            choice= sc.nextInt();
            if(choice==1){
                totaln=0;
                System.out.println("All the records have been deleted.");

            }
            else if(choice==2){
                System.out.println();
                System.out.println("Enter the roll no of the student you miss delete the record of: ");
                roll = sc.nextInt();

                for(int i=0;i<totaln;i++){
                    if(roll==rollno.get(i)){
                        for(int j=i;j<totaln;j++){
                            standard.remove(j);
                            fname.remove(j);
                            lname.remove(j);
                            rollno.remove(j);
                            dob.remove(j);
                            gender.remove(j);
                            percentage.remove(j);
                        }
                        totaln--;
                        System.out.println("The record has been deleted.");

                    }
                }

            }
            else {
                System.out.println("Invalid input.");
            }

        }

    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int value;
        char ch;
        do {
            System.out.println("Enter 1 to enter data.");
            System.out.println("Enter 2 to show data.");
            System.out.println("Enter 3 to search data.");
            System.out.println("Enter 4 to view the result in descending order: ");
            System.out.println("Enter 5 to delete data.");
            System.out.println("Enter 6 to exit.");
            System.out.println();
            System.out.print("Enter the value: ");
            value=sc.nextInt();
            switch(value){
                case 1:
                    entry();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    search();
                    break;
                case 4:
                    sort();
                    break;
                case 5:
                    delete();
                    break;
                case 6:
                    break;
                default:
                    System.out.println("Invalid input.");
                    break;
            }
            System.out.println("Do you want to continue(y/n): ");
            ch=sc.next().charAt(0);
        }while(ch=='y' || ch=='Y');
    }
}
```

答:
Instead of using different arraylist for each property, create an object of Student

```<code>class Student implements Comparable<Student>{
String name = "";
String gender = "";
Double percentage = 0.0;

Student( String name,
String gender ,
Double percentage){
    this.name = name;
    this.gender = gender;
    this.percentage = percentage;
}

@Override
public int compareTo(Student s) {
     int firstPercentage = (int) Math.round(this.percentage);
      int secondPercentage = (int) Math.round(s.percentage);
    return  firstPercentage - secondPercentage;
}
</code>```

}

and then create list of object like this

```<code>  Student s1 = new Student("student1", "male",  10.0);
 Student s2 = new Student("student2", "male",  20.0);
 Student s3 = new Student("student3", "female", 30.0);
 Student s4 = new Student("student4", "male",  40.0);
 Student s5 = new Student("student5", "female",  90.0);
 Student s6 = new Student("student6", "male",  80.0);

ArrayList<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);
</code>```

first sort them using collections, here sort and reverse will work as per percentage because you've implemented Comparable in Student class which is comparing object on the basis of percentage in compareTo() method.

```<code>Collections.sort(students);
</code>```

and then reverse the list by collections

```<code>Collections.reverse(students);
</code>```

and then you have list of students in descending order with respect to percentage

```<code> for(Student i : students){
        System.out.println(i.percentage);
}
</code>```

Body:
Instead of using different arraylist for each property, create an object of Student

class Student implements Comparable<Student>{
String name = "";
String gender = "";
Double percentage = 0.0;

Student( String name,
String gender ,
Double percentage){
    this.name = name;
    this.gender = gender;
    this.percentage = percentage;
}

@Override
public int compareTo(Student s) {
     int firstPercentage = (int) Math.round(this.percentage);
      int secondPercentage = (int) Math.round(s.percentage);
    return  firstPercentage - secondPercentage;
}

}

and then create list of object like this

  Student s1 = new Student("student1", "male",  10.0);
 Student s2 = new Student("student2", "male",  20.0);
 Student s3 = new Student("student3", "female", 30.0);
 Student s4 = new Student("student4", "male",  40.0);
 Student s5 = new Student("student5", "female",  90.0);
 Student s6 = new Student("student6", "male",  80.0);

ArrayList<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);

first sort them using collections, here sort and reverse will work as per percentage because you've implemented Comparable in Student class which is comparing object on the basis of percentage in compareTo() method.

Collections.sort(students);

and then reverse the list by collections

Collections.reverse(students);

and then you have list of students in descending order with respect to percentage

 for(Student i : students){
        System.out.println(i.percentage);
}


问:
How to run scipy's BFGS on GPU
I'd like to run scipy implementation of BFGS optimization algorithm on GPU and scipy seems not to support GPUs. The target function which I want to run on GPU is the following one which is part of the implementation of this repository:

```<code>//here the variable initializations

opts = {'gtol': effective_gamma, 'norm': 2}
result = minimize(private_loss, x0, (x, y), method='BFGS', jac=private_gradient, options=opts,
callback=cb)
</code>```

I know there is Tensorflow Probablity implementation of BFGS, but I couldn't find out how I can convert this scipy function into Tensordlow Probablity. Any Idea how I could to run the following function on GPU with minimum code change?

答:
Here are two suggestions of mine:

jax.scipy:
Jax contains the implementation of scipy and also supports GPUs and TPUs. You can theoretically install it, convert your numpy variables to jax.numpy and call jax.scipy.optimize.minimize(params):

```<code> import jax.numpy as jnp
 from jax.scipy.optimize import minimize

 // here x0,x,y initialization and private_loss and private_gradient functions definition

 x0 = jax.numpy.asarray(x0)
 x = jax.numpy.asarray(x)
 y = jax.numpy.asarray(y)

 opts = {'gtol': effective_gamma, 'norm': 2}
 result = minimize(private_loss, x0, (x, y), method='BFGS', jac=private_gradient, options=opts, callback=cb)

 // here rest of the code
</code>```

Dont foget to also take care of converting the variables which will be used in private_loss and private_gradient function to jax.numpy.

Tensorflow Probability: As you already mentioned, you can also use bfgs_minimize implementation by tensorflow.
based on the colab here, your code will be something like this:

```<code> def make_val_and_grad_fn(value_fn):
   @functools.wraps(value_fn)
   def val_and_grad(param):
     return tfp.math.value_and_gradient(value_fn, param)
   return val_and_grad

 def run(optimizer):
   result2 = optimizer()
   return np_value(result2)

 @make_val_and_grad_fn
 def private_loss(param):
     // here private_loss

 x_var = tf.Variable(x)
 y_var = tf.Variable(y, dtype = tf.float64)
 x0 = tf.Variable(x0)

 tolerance = effective_gamma

 @tf.function
 def minimize_with_bfgs():
     result1 = tfp.optimizer.bfgs_minimize(
     private_loss,
     initial_position=tf.constant(x0),
     tolerance=tolerance)
     return result1

 results = run(minimize_with_bfgs)
</code>```

Title: How to run scipy's BFGS on GPU

Body:
I'd like to run scipy implementation of BFGS optimization algorithm on GPU and scipy seems not to support GPUs. The target function which I want to run on GPU is the following one which is part of the implementation of this repository:

//here the variable initializations

opts = {'gtol': effective_gamma, 'norm': 2}
result = minimize(private_loss, x0, (x, y), method='BFGS', jac=private_gradient, options=opts,
callback=cb)

I know there is Tensorflow Probablity implementation of BFGS, but I couldn't find out how I can convert this scipy function into Tensordlow Probablity. Any Idea how I could to run the following function on GPU with minimum code change?

Body:
Here are two suggestions of mine:

jax.scipy:
Jax contains the implementation of scipy and also supports GPUs and TPUs. You can theoretically install it, convert your numpy variables to jax.numpy and call jax.scipy.optimize.minimize(params):

 import jax.numpy as jnp
 from jax.scipy.optimize import minimize

 // here x0,x,y initialization and private_loss and private_gradient functions definition

 x0 = jax.numpy.asarray(x0)
 x = jax.numpy.asarray(x)
 y = jax.numpy.asarray(y)

 opts = {'gtol': effective_gamma, 'norm': 2}
 result = minimize(private_loss, x0, (x, y), method='BFGS', jac=private_gradient, options=opts, callback=cb)

 // here rest of the code

Dont foget to also take care of converting the variables which will be used in private_loss and private_gradient function to jax.numpy.

Tensorflow Probability: As you already mentioned, you can also use bfgs_minimize implementation by tensorflow.
based on the colab here, your code will be something like this:

 def make_val_and_grad_fn(value_fn):
   @functools.wraps(value_fn)
   def val_and_grad(param):
     return tfp.math.value_and_gradient(value_fn, param)
   return val_and_grad

 def run(optimizer):
   result2 = optimizer()
   return np_value(result2)

 @make_val_and_grad_fn
 def private_loss(param):
     // here private_loss

 x_var = tf.Variable(x)
 y_var = tf.Variable(y, dtype = tf.float64)
 x0 = tf.Variable(x0)

 tolerance = effective_gamma

 @tf.function
 def minimize_with_bfgs():
     result1 = tfp.optimizer.bfgs_minimize(
     private_loss,
     initial_position=tf.constant(x0),
     tolerance=tolerance)
     return result1

 results = run(minimize_with_bfgs)


问:
Different ways to add functions to Javascript object
In Javascript is there any difference between these two ways of adding a function to an object?  Is one preferable for any reason?  </p>

```<code>function ObjA() {
    this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };

var A = new ObjA();
A.AlertA();
A.AlertB();
</code>```

答:
Sure there is a difference. If you define this.AlertA, you are defining a method that is local  for the instance of ObjA. If you add AlertA to the prototype of the ObjA constructor, it is defined for every instance of ObjA. The latter is, in this case, more efficient, because it's only assigned once, whilst a local method is assigned every time you create an instance of ObjA.

So using this.AlertA in:

```<code>var A = new ObjA,
    B = new ObjA,
    C = new ObjA;
</code>```

for A, B and C the constructor has to add the method AlertA. AlertB on the other hand, is only added once. You can check that using:

```<code>function ObjA() {
        alert('adding AlertA!');
        this.AlertA = function() {
            alert("A");
        };

        if (!ObjA.prototype.AlertB) {
            alert('adding AlertB!');
            ObjA.prototype.AlertB = function() {
                alert("B");
            };
        }
}

var A = new ObjA,  //=>  alerts adding AlertA! and alerts adding AlertB!
    B = new ObjA,  //=>  alerts adding AlertA!
    C = new ObjA;  //=>  alerts adding AlertA!
</code>```

Body:
In Javascript is there any difference between these two ways of adding a function to an object?  Is one preferable for any reason?

function ObjA() {
    this.AlertA = function() { alert("A"); };
}
ObjA.prototype.AlertB = function() { alert("B"); };

var A = new ObjA();
A.AlertA();
A.AlertB();

Body:
Sure there is a difference. If you define this.AlertA, you are defining a method that is local  for the instance of ObjA. If you add AlertA to the prototype of the ObjA constructor, it is defined for every instance of ObjA. The latter is, in this case, more efficient, because it's only assigned once, whilst a local method is assigned every time you create an instance of ObjA.

So using this.AlertA in:

var A = new ObjA,
    B = new ObjA,
    C = new ObjA;

for A, B and C the constructor has to add the method AlertA. AlertB on the other hand, is only added once. You can check that using:

function ObjA() {
        alert('adding AlertA!');
        this.AlertA = function() {
            alert("A");
        };

        if (!ObjA.prototype.AlertB) {
            alert('adding AlertB!');
            ObjA.prototype.AlertB = function() {
                alert("B");
            };
        }
}

var A = new ObjA,  //=>  alerts adding AlertA! and alerts adding AlertB!
    B = new ObjA,  //=>  alerts adding AlertA!
    C = new ObjA;  //=>  alerts adding AlertA!


问:
How to install external library from source for cmake to find it?
Say I am writing a library my_project that uses some other library dependency_lib.
What I'm currently doing during development is: I've cloned the code of the dependency to some normal, human accessible directory in my file system. I've built that library according to the instructions from its developers, and now I have a shared library dependency_lib.so somewhere in that directory.
Then in my CMakeLists.txt I have:

```<code>find_library(DEPENDENCY_LIB dependency_lib HINTS /home/my_name/Documents/path/to/the/built/dependency/lib)
target_link_libraries(my_project PRIVATE ${DEPENDENCY_LIB})
</code>```

This works great for me, but obviously when other people clone my code and try to build it, they will have that external library at some other location on their system, so this won't work for them.

Is there some standard location to put built libraries in for cmake to find them, where I can assume other developers also put their built libraries in?

Is it even reasonable for me to expect other developers/users of my library to also clone the source code of the dependency and build it, or is there some other solution for external dependencies on C++?
Any comments, explanations and resources on dependency management with cmake are very appreciated.

Bonus question: Why can't this be as simple as Python with pip, Rust with cargo or JavaScript with npm?

答:
Mostly, developers add SDKs folder to let others use the required SDKs. It may be because they did minor/major changes inside the library and it became a custom build version and special for them. So, it means,  they have to pack it inside the project since others can't find the modified version of that library. And I think, this is what you're looking for:

```<code>find_package(Library ${LIB_VERSION} EXACT REQUIRED PATHS "${LIB_DIR}")
</code>```

By declaring PATHS you can have CMake look for the libraries specific directories.

Body:
Say I am writing a library my_project that uses some other library dependency_lib.
What I'm currently doing during development is: I've cloned the code of the dependency to some normal, human accessible directory in my file system. I've built that library according to the instructions from its developers, and now I have a shared library dependency_lib.so somewhere in that directory.
Then in my CMakeLists.txt I have:

find_library(DEPENDENCY_LIB dependency_lib HINTS /home/my_name/Documents/path/to/the/built/dependency/lib)
target_link_libraries(my_project PRIVATE ${DEPENDENCY_LIB})

This works great for me, but obviously when other people clone my code and try to build it, they will have that external library at some other location on their system, so this won't work for them.

Is there some standard location to put built libraries in for cmake to find them, where I can assume other developers also put their built libraries in?

Is it even reasonable for me to expect other developers/users of my library to also clone the source code of the dependency and build it, or is there some other solution for external dependencies on C++?
Any comments, explanations and resources on dependency management with cmake are very appreciated.

Bonus question: Why can't this be as simple as Python with pip, Rust with cargo or JavaScript with npm?

Body:
Mostly, developers add SDKs folder to let others use the required SDKs. It may be because they did minor/major changes inside the library and it became a custom build version and special for them. So, it means,  they have to pack it inside the project since others can't find the modified version of that library. And I think, this is what you're looking for:

find_package(Library ${LIB_VERSION} EXACT REQUIRED PATHS "${LIB_DIR}")

By declaring PATHS you can have CMake look for the libraries specific directories.


问:
Unable to generate assets to build and debug. OmniSharp server is not running
On Visual Studio (VS) Code, coding on C#. I'm trying to generate assets to build and debug and I'm getting the following error message: Unable to generate assets to build and debug. OmniSharp server is not running.

I'm running:

.NET version 3.1.301

Windows 8.1

Visual Studio Code 1.46.1 (user setup)

Powershell 5.1

So far I've tried unistalling VS code and the C# extention, I updated the omnisharp.path to latest at settings.json and updated the powershell version.

The code I'm trying to generate the assets for build and debug does run, so I'm uncertain where else I should look for the source of the problem.

If you require any more details feel free to ask

答: Install the C# Extension, once installed click on the arrow on the side of the uninstall button and then click install another version. First I tried one from 2 months ago, it did not work, then I tried one from 6 months and it worked perfectly!</p>


问:
velero backups failing for "backup resource list not found"
After the upgrade of velero from 1.3.2 to 1.7.7 backups started failing.
When describing the failing backup:

```<code>velero backup describe mypod-20220204170020 --details

Name:         mypod-20220204170020
Namespace:    velero
Labels:       velero.io/schedule-name=mypod
              velero.io/storage-location=default
Annotations:  velero.io/source-cluster-k8s-gitversion=v1.21.2
              velero.io/source-cluster-k8s-major-version=1
              velero.io/source-cluster-k8s-minor-version=21

Phase:  Failed (run `velero backup logs mypod-20220204170020` for more information)

Errors:    0
Warnings:  0

Namespaces:
  Included:  mypod
  Excluded:  <none>

Resources:
  Included:        *
  Excluded:        <none>
  Cluster-scoped:  auto

Label selector:  <none>

Storage Location:  default

Velero-Native Snapshot PVs:  auto

TTL:  168h0m0s

Hooks:  <none>

Backup Format Version:  1.1.0

Started:    2022-02-04 18:00:20 +0100 CET
Completed:  2022-02-04 18:00:41 +0100 CET

Expiration:  2022-02-11 18:00:20 +0100 CET

Total items to be backed up:  64
Items backed up:              64

Resource List:  <backup resource list not found>

Velero-Native Snapshots:  <error getting snapshot info: file not found>
</code>```

At first sight it seems like the backups were made correctly:

Errors:    0

Warnings:  0

Items backup: 64 of 64

However, right at the bottom (and only when adding the --details flag with the describe command), you see these two mentions:

```<code>Resource List:  <backup resource list not found>
Velero-Native Snapshots:  <error getting snapshot info: file not found>
</code>```

Is there some clever way to troubleshoot this further? Or do someone have thoughts on what might be the issue here?

Running on AKS (1.21.2)

Using velero-plugin-for-microsoft-azure:v1.3.1 for snapshots to azure

Much appreciated!

答:
Not sure if this solves the issue for everyone, but it worked for me.
After searching inside the velero source code repo,
I located the following go package velero/pkg/cmd/util/output/backup_describer.go that contained the error message I found when describing the failing backup.

See line 328 (1)

The hints at (2) in the source code led me to search on upload issues.
As I am using the velero-plugin-for-microsoft-azure to handle uploads to Azure the following GitHub issue finally gave me the nudge in the right direction.

Seems like the velero-plugin-for-microsoft-azure required more memory (512Mi) since v1.5.3 (if I understood it correctly).
The limits on my one were still at 256Mi and failing, I increased the limits to 512Mi and, presto! It started working again.

A big shout out to David L. Smith-Uchida whose breadcrumbs led me to the solution!

Body:
After the upgrade of velero from 1.3.2 to 1.7.7 backups started failing.
When describing the failing backup:

velero backup describe mypod-20220204170020 --details

Name:         mypod-20220204170020
Namespace:    velero
Labels:       velero.io/schedule-name=mypod
              velero.io/storage-location=default
Annotations:  velero.io/source-cluster-k8s-gitversion=v1.21.2
              velero.io/source-cluster-k8s-major-version=1
              velero.io/source-cluster-k8s-minor-version=21

Phase:  Failed (run `velero backup logs mypod-20220204170020` for more information)

Errors:    0
Warnings:  0

Namespaces:
  Included:  mypod
  Excluded:  <none>

Resources:
  Included:        *
  Excluded:        <none>
  Cluster-scoped:  auto

Label selector:  <none>

Storage Location:  default

Velero-Native Snapshot PVs:  auto

TTL:  168h0m0s

Hooks:  <none>

Backup Format Version:  1.1.0

Started:    2022-02-04 18:00:20 +0100 CET
Completed:  2022-02-04 18:00:41 +0100 CET

Expiration:  2022-02-11 18:00:20 +0100 CET

Total items to be backed up:  64
Items backed up:              64

Resource List:  <backup resource list not found>

Velero-Native Snapshots:  <error getting snapshot info: file not found>

At first sight it seems like the backups were made correctly:

Errors:    0

Warnings:  0

Items backup: 64 of 64

However, right at the bottom (and only when adding the --details flag with the describe command), you see these two mentions:

Resource List:  <backup resource list not found>
Velero-Native Snapshots:  <error getting snapshot info: file not found>

Is there some clever way to troubleshoot this further? Or do someone have thoughts on what might be the issue here?

Running on AKS (1.21.2)

Using velero-plugin-for-microsoft-azure:v1.3.1 for snapshots to azure

Much appreciated!