问:
How does using two variables in for loop work
I started reading the python documentation. I ended up with this statement:

Code that modifies a collection while iterating over that same
  collection can be tricky to get right. Instead, it is usually more
  straight-forward to loop over a copy of the collection or to create a
  new collection:

```<code># Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
</code>```

I can't understand the solution. How is this code working?
I mean i get the idea of using one variable to iterate over a list but using two is complicated to understand.
Source: https://docs.python.org/3/tutorial/controlflow.html#for-statements

答:
I had the same confusion. The example as given doesn't work. The piece that is missing is the dictionary object 'users' at the start. At that point in the tutorial we haven't been taught about them. https://docs.python.org/3/library/stdtypes.html#index-50

A working version is

```<code>users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status
</code>```

If you want to see the contents then you can print it out. Try this:

```<code>users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

print("Users after deleting.")
for user, status in users.items():
    print(user, status)

users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

print("active_users.items")
for user, status in active_users.items():
    print(user, status)
</code>```

Body:
I started reading the python documentation. I ended up with this statement:

Code that modifies a collection while iterating over that same
  collection can be tricky to get right. Instead, it is usually more
  straight-forward to loop over a copy of the collection or to create a
  new collection:

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

I can't understand the solution. How is this code working?
I mean i get the idea of using one variable to iterate over a list but using two is complicated to understand.
Source: https://docs.python.org/3/tutorial/controlflow.html#for-statements

Body:
I had the same confusion. The example as given doesn't work. The piece that is missing is the dictionary object 'users' at the start. At that point in the tutorial we haven't been taught about them. https://docs.python.org/3/library/stdtypes.html#index-50

A working version is

users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

If you want to see the contents then you can print it out. Try this:

users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

print("Users after deleting.")
for user, status in users.items():
    print(user, status)

users = { "John": "inactive",
               "Helen": "active",
               "James": "active", # and so on...
            }

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

print("active_users.items")
for user, status in active_users.items():
    print(user, status)


来源: stackexchange

问:
do you know of any python component(s) for syntax highlighting?
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>

答: Other than pygments?  http://pygments.org/</p>

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5


问:
Ignoring the newline character while splitting the multiline string
I have a string like below

```<code>s = '''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''
</code>```

I want to split the string. I used splitlines() But it's not giving the output I'm expected.
It also splitting the string if it contain \n in middle of the string. What i want is I want to ignore the newline characters in middle of the strings while splitting the string. Is there any way can I solve this without using the files.

```<code>for line in s.splitlines():
    #line = somfunction(line)
    print(line)
</code>```

Output of above code

```<code>printf("
Float value is %f
", flt);
printf("Integer value is %d
" , no);
printf("Double value is %lf
", dbl);
printf("
Octal value is %o
", no);
printf("Hexadecimal value is %x
", no);
return 0;
</code>```

Expected Output:

```<code>printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
</code>```

答:
Try this</p>

```<code>s = r'''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''

for line in s.splitlines():
    print(line)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string like below

s = '''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''

I want to split the string. I used splitlines() But it's not giving the output I'm expected.
It also splitting the string if it contain \n in middle of the string. What i want is I want to ignore the newline characters in middle of the strings while splitting the string. Is there any way can I solve this without using the files.

for line in s.splitlines():
    #line = somfunction(line)
    print(line)

Output of above code

printf("
Float value is %f
", flt);
printf("Integer value is %d
" , no);
printf("Double value is %lf
", dbl);
printf("
Octal value is %o
", no);
printf("Hexadecimal value is %x
", no);
return 0;

Expected Output:

printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;

Body:
Try this

s = r'''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''

for line in s.splitlines():
    print(line)


问:
Can somebody help me with bootstrap4 carousel-indicators
I have added text previous and next instead of regular carousel-indicators. i was able to center align the text horizontally but vertically it is not centered.

Below are the carousel-indicators html and styles:

```<code>.carousel-indicators {
   top: 400px;
}
.carousel-indicators li {
   position: relative;
   left: 20px;
   width: 208px;
   height: 56px;
   border-radius: 12px;
   background-color: var(--dark-blue);
   margin-right: 2em;
   text-indent: unset;
   color: var(--white-bg);
   font-size: 20px;
   cursor: pointer;
}
.carousel-indicators .active {
   background-color: var(--dark-blue);
}

<ol class="carousel-indicators text-uppercase text-center">
   <li data-target="#mycarouselIndicators" data-slide-to="0" class="active" > Previous </li>
   <li data-target="#mycarouselIndicators" data-slide-to="1">Next</li>
</ol>
</code>```

答:
Add style="bottom: 50%;" to your
 and it should work as expected.

```<code><ol class="carousel-indicators text-uppercase text-center" style="bottom: 50%;">
   <li data-target="#mycarouselIndicators" data-slide-to="0" class="active" > Previous </li>
   <li data-target="#mycarouselIndicators" data-slide-to="1">Next</li>
</ol>

</code>```

Body:
I have added text previous and next instead of regular carousel-indicators. i was able to center align the text horizontally but vertically it is not centered.

Below are the carousel-indicators html and styles:

.carousel-indicators {
   top: 400px;
}
.carousel-indicators li {
   position: relative;
   left: 20px;
   width: 208px;
   height: 56px;
   border-radius: 12px;
   background-color: var(--dark-blue);
   margin-right: 2em;
   text-indent: unset;
   color: var(--white-bg);
   font-size: 20px;
   cursor: pointer;
}
.carousel-indicators .active {
   background-color: var(--dark-blue);
}

 Previous

Next

Body:
Add style="bottom: 50%;" to your <ol> and it should work as expected.

<ol class="carousel-indicators text-uppercase text-center" style="bottom: 50%;">
   <li data-target="#mycarouselIndicators" data-slide-to="0" class="active" > Previous </li>
   <li data-target="#mycarouselIndicators" data-slide-to="1">Next</li>
</ol>


问:
How to send custom CAN messages using ELM327?
I'm working with a ELM327 and I'd like to be able to set the header and data portions of CAN messages to be sent.  I see that there is a code for setting the header for messages

```<code>SH xxyyzz
</code>```

But I'm having trouble finding out how to set the data portion and control when the message gets sent.

Do these both occur when I send a ASCII request for a PID with extra characters for the data field?

And would that use the header that was set by the SH command?

Is there a better way to do this?

Datasheet: http://elmelectronics.com/DSheets/ELM327DS.pdf

答:
If you're using an ELM327 chipset, you need to call ATSH or AT SH, to set the header first. Then send the message separately (The data bytes).

https://www.sparkfun.com/datasheets/Widgets/ELM327_AT_Commands.pdf

ContentLicense: CC BY-SA 3.0

Body:
I'm working with a ELM327 and I'd like to be able to set the header and data portions of CAN messages to be sent.  I see that there is a code for setting the header for messages

SH xxyyzz

But I'm having trouble finding out how to set the data portion and control when the message gets sent.

Do these both occur when I send a ASCII request for a PID with extra characters for the data field?

And would that use the header that was set by the SH command?

Is there a better way to do this?

Datasheet: http://elmelectronics.com/DSheets/ELM327DS.pdf


问:
Has FB.Canvas.setAutoResize() stopped working for anyone else?
I maintain a few different Facebook applications, and across them I use

```<code>FB.Canvas.setAutoResize();
</code>```

to resize the height of the application.

In the last few hours this has stopped working on all of my applications, without any of my code being changed.

I found a user that seems to have the same problem here.

My main question is, has anyone else had this happen to their applications today?

Does anyone know if this is a bug or has support for setAutoResize() suddenly been dropped?

答: Other users seem to be having this issue as well http://bugs.developers.facebook.net/show_bug.cgi?id=10889</p>

Body:
I maintain a few different Facebook applications, and across them I use

FB.Canvas.setAutoResize();

to resize the height of the application.

In the last few hours this has stopped working on all of my applications, without any of my code being changed.

I found a user that seems to have the same problem here.

My main question is, has anyone else had this happen to their applications today?

Does anyone know if this is a bug or has support for setAutoResize() suddenly been dropped?


问:
How to wrap http.Handler in method
The simplest way to get file system in go is the code below.

```<code>http.Handle("/files", http.StripPrefix(pathPrefix, http.FileServer(root)))
</code>```

But for the purpose of objective design, I prefer to wrap the body of function in the method like this.

```<code>f := file{}
http.Handle("/download", f.download)
http.Handle("/upload", f.upload)
</code>```

How should I wrap the content of code in the file struct method?

答:
You can do it by using http.HandleFunc rather than http.Handle:

```<code>f := file{}
http.HandleFunc("/download", f.download)
http.HandleFunc("/upload", f.upload)
</code>```

Assuming it has the right signature (ie, assuming that f.download is defined as something like func (f file) download(w http.ResponseWriter, r *http.Request)), then it should do what you want.

Title: How to wrap http.Handler in method

Body:
The simplest way to get file system in go is the code below.

http.Handle("/files", http.StripPrefix(pathPrefix, http.FileServer(root)))

But for the purpose of objective design, I prefer to wrap the body of function in the method like this.

f := file{}
http.Handle("/download", f.download)
http.Handle("/upload", f.upload)

How should I wrap the content of code in the file struct method?

Body:
You can do it by using http.HandleFunc rather than http.Handle:

f := file{}
http.HandleFunc("/download", f.download)
http.HandleFunc("/upload", f.upload)

Assuming it has the right signature (ie, assuming that f.download is defined as something like func (f file) download(w http.ResponseWriter, r *http.Request)), then it should do what you want.


问:
Hiding IonTab on subpages - Ionic React 5
I am building Ionic React application, and the version of ionic is 5. In my application, I have bottom navigation. I have mentioned the logic of bottom navigation in App.tsx.

I have an add button on the Dashboard page on clicking that button I want a page to open which will not contain the bottom navigation. I got many answers over the internet which is for Ionic-Angular. I am specifically looking for an answer Ionic-React.

```<code>App.tsx
     <IonContent>
        <IonReactRouter>
          <IonTabs>
            <IonRouterOutlet>
              <Route path="/profile" component={Profile} exact={true} />
              <Route path="/dashboard" component={Dashboard} exact={true} />
              <Route path="/dashboard/addInfo" component={Info} exact={true} />
              <Route path="/" render={() => <Redirect to="/dashboard" />} exact={true} />
            </IonRouterOutlet>
            <IonTabBar slot="bottom">
              <IonTabButton tab="home" href="/home">
                <IonIcon icon={home} />
                <IonLabel>Home</IonLabel>
              </IonTabButton>
              <IonTabButton tab="profile" href="/profile">
                <IonIcon icon={profile} />
                <IonLabel>Profile</IonLabel>
              </IonTabButton>
              <IonTabButton tab="dashboard" href="/dashboard">
                <IonIcon icon={grid} />
                <IonLabel>Dashboard</IonLabel>
              </IonTabButton>
            </IonTabBar>
          </IonTabs>
        </IonReactRouter>
      </IonContent>
</code>```

答:
I did something like this and that worked for me. I created an id for the tabs and then manipulated that to show or hide</p>

```<code>    function showTab() {
       const tabBar = document.getElementById('appTabBar');
       if (tabBar !== null) {
           console.log("enabled")
           tabBar.style.display = 'flex';
       }
    }

function hideTab() {
   const tabBar = document.getElementById('appTabBar');
   if (tabBar !== null) {
      tabBar.style.display = 'none';
   }
}

<IonTabBar slot="bottom" id="appTabBar" >
      <IonTabButton tab="account" href="/account">
           <IonIcon icon={personCircleOutline}/>
           <IonLabel>Profile</IonLabel>
           </IonTabButton>
    </IonTabBar>
</code>```

Body:
I am building Ionic React application, and the version of ionic is 5. In my application, I have bottom navigation. I have mentioned the logic of bottom navigation in App.tsx.

I have an add button on the Dashboard page on clicking that button I want a page to open which will not contain the bottom navigation. I got many answers over the internet which is for Ionic-Angular. I am specifically looking for an answer Ionic-React.

App.tsx
     <IonContent>
        <IonReactRouter>
          <IonTabs>
            <IonRouterOutlet>
              <Route path="/profile" component={Profile} exact={true} />
              <Route path="/dashboard" component={Dashboard} exact={true} />
              <Route path="/dashboard/addInfo" component={Info} exact={true} />
              <Route path="/" render={() => <Redirect to="/dashboard" />} exact={true} />
            </IonRouterOutlet>
            <IonTabBar slot="bottom">
              <IonTabButton tab="home" href="/home">
                <IonIcon icon={home} />
                <IonLabel>Home</IonLabel>
              </IonTabButton>
              <IonTabButton tab="profile" href="/profile">
                <IonIcon icon={profile} />
                <IonLabel>Profile</IonLabel>
              </IonTabButton>
              <IonTabButton tab="dashboard" href="/dashboard">
                <IonIcon icon={grid} />
                <IonLabel>Dashboard</IonLabel>
              </IonTabButton>
            </IonTabBar>
          </IonTabs>
        </IonReactRouter>
      </IonContent>

Body:
I did something like this and that worked for me. I created an id for the tabs and then manipulated that to show or hide

    function showTab() {
       const tabBar = document.getElementById('appTabBar');
       if (tabBar !== null) {
           console.log("enabled")
           tabBar.style.display = 'flex';
       }
    }

function hideTab() {
   const tabBar = document.getElementById('appTabBar');
   if (tabBar !== null) {
      tabBar.style.display = 'none';
   }
}

<IonTabBar slot="bottom" id="appTabBar" >
      <IonTabButton tab="account" href="/account">
           <IonIcon icon={personCircleOutline}/>
           <IonLabel>Profile</IonLabel>
           </IonTabButton>
    </IonTabBar>


问:
How to store results of a for loop in a vector or a list in R
I want to run a simple for loop and store values in a list or a vector. For example:

```<code>ex = c(10,11,17)

for (i in (0:length(ex))){
  if ex[i] < 12 {
    # store the value in a vector
  }
}
</code>```

How can I do this, when I do not know the length of the vector and therefore cannot define it first?

答:
You can do this without for loop :

```<code>ex[ex < 12]
#[1] 10 11
</code>```

Or using Filter :

```<code>Filter(function(x) x < 12, ex)
</code>```

However, if you want to do this with for loop you can try :

```<code>count <- 1
result_vec <- numeric()

for (i in ex) {
   if (i < 12) {
    result_vec[count] <- i
    count <- count + 1
  }
}
</code>```

Body:
I want to run a simple for loop and store values in a list or a vector. For example:

ex = c(10,11,17)

for (i in (0:length(ex))){
  if ex[i] < 12 {
    # store the value in a vector
  }
}

How can I do this, when I do not know the length of the vector and therefore cannot define it first?

Body:
You can do this without for loop :

ex[ex < 12]
#[1] 10 11

Or using Filter :

Filter(function(x) x < 12, ex)

However, if you want to do this with for loop you can try :

count <- 1
result_vec <- numeric()

for (i in ex) {
   if (i < 12) {
    result_vec[count] <- i
    count <- count + 1
  }
}


问:
Unable to create AWS Rekognition project in Console nor cli
I have followed the tutorial on how to create an AWS Rekognition custom labels project.

In the console, I am unable to see, as mentionned, the points 2, 3 and 4:

In the left pane, choose Use Custom Labels. The Amazon Rekognition Custom Labels landing page is shown.

Choose Get started.

Choose Create Project.

In the cli, I am able to make a call to the API and have a prediction on an image in my bucket.

But if I try aws rekognition create-project --project-name my-project, I get an error An error occurred (AccessDeniedException) when calling the CreateProject operation.

I have tried with both root user and  a newly created user with permissions AmazonRekognitionFullAccess and AdministratorAccess and my credentials are set as well.

I used aws configure and correctly passed my access key, secret key and region. I checked it in ~/.aws/credentials and ~/.aws/config.

Don't know what I am missing here, any help would be appreciate.

答:
From the error message posted, even though you mention that the IAM user has the required permissions, it still points towards insufficient permissions or maybe incorrect region. To debug try the following:

Execute the get-caller-identity CLI command to check whether the credentials used are for the IAM user with the AmazonRekognitionFullAccess policy attached.

Verify that you are invoking the command in a region where Rekognition Custom Labels is available.

Amazon Rekognition Custom Labels is available in US East (N. Virginia), US East (Ohio), US West (Oregon), and Europe (Ireland).


答:
You can achieve the desired result using a string raw notation in your s definition.

```<code>s = r'''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''
</code>```

Notice the r in leading of string. In python this mean a string raw.

Here is the documentation

Title: Ignoring the newline character while splitting the multiline string

Body:
You can achieve the desired result using a string raw notation in your s definition.

s = r'''printf("\nFloat value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("\nOctal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;'''

Notice the r in leading of string. In python this mean a string raw.

Here is the documentation


问:
Passing in a different parameter type than the one specified works in Golang?
I have 3 packages total: repository, restrict, and main.

In my repository package, I have a structure called "RestrictionRuleRepository" defined as:

```<code>type RestrictionRuleRepository struct {
    storage map[string]float64
}
</code>```

In another package restrict, I have a "NewService" function defined:

```<code>func NewService(repository rule.Repository) Service {
    return &service{
        repository: repository,
    }
}
</code>```

Finally, in my package main, I have these two lines of code:

```<code>ruleRepo := repository.RestrictionRuleRepository{}

restrictionService := restrict.NewService(&ruleRepo)
</code>```

My code is compiling without any errors. Why is this allowed in Golang? Doesn't my NewService function expect a Repository type, but I am passing in the address of a RestrictionRuleRepository struct to it?

答:
Most likely rule.Repository is an interface and the *RestrictionRuleRepository type just happens to implement that interface.

Here is an example:

```<code>package main

import (
    "fmt"
)

type Repository interface {
    SayHi()
}

type RestrictionRuleRepository struct {
    storage map[string]float64
}

func (r *RestrictionRuleRepository) SayHi() {
    fmt.Println("Hi!")
}

type service struct {
    repository Repository
}

type Service interface {
    MakeRepoSayHi()
}

func NewService(repository Repository) Service {
    return &service{
        repository: repository,
    }
}

func (s *service) MakeRepoSayHi() {
    s.repository.SayHi()
}

func main() {
    ruleRepo := RestrictionRuleRepository{}
    restrictionService := NewService(&ruleRepo)
    restrictionService.MakeRepoSayHi()
}

</code>```

This compiles fine as you can see in https://play.golang.org/p/bjKYZLiVKCh.

I also recommend https://tour.golang.org/methods/9 as a good place to get started with interfaces.

Body:
I have 3 packages total: repository, restrict, and main.

In my repository package, I have a structure called "RestrictionRuleRepository" defined as:

type RestrictionRuleRepository struct {
    storage map[string]float64
}

In another package restrict, I have a "NewService" function defined:

func NewService(repository rule.Repository) Service {
    return &service{
        repository: repository,
    }
}

Finally, in my package main, I have these two lines of code:

ruleRepo := repository.RestrictionRuleRepository{}

restrictionService := restrict.NewService(&ruleRepo)

My code is compiling without any errors. Why is this allowed in Golang? Doesn't my NewService function expect a Repository type, but I am passing in the address of a RestrictionRuleRepository struct to it?

Body:
Most likely rule.Repository is an interface and the *RestrictionRuleRepository type just happens to implement that interface.

Here is an example:

package main

import (
    "fmt"
)

type Repository interface {
    SayHi()
}

type RestrictionRuleRepository struct {
    storage map[string]float64
}

func (r *RestrictionRuleRepository) SayHi() {
    fmt.Println("Hi!")
}

type service struct {
    repository Repository
}

type Service interface {
    MakeRepoSayHi()
}

func NewService(repository Repository) Service {
    return &service{
        repository: repository,
    }
}

func (s *service) MakeRepoSayHi() {
    s.repository.SayHi()
}

func main() {
    ruleRepo := RestrictionRuleRepository{}
    restrictionService := NewService(&ruleRepo)
    restrictionService.MakeRepoSayHi()
}

This compiles fine as you can see in https://play.golang.org/p/bjKYZLiVKCh.

I also recommend https://tour.golang.org/methods/9 as a good place to get started with interfaces.


问:
Container xx didn't respond to HTTP pings on port: 8080, failing site start or Unable to bind to http://localhost:5000 on the IPv6 loopback interface
I've been deployed my app with FTP several times and always worked until now. I'm not using docker, so I suppose azure is dockerizing my app after I upload the files.
I'm getting two errors, I'm not sure if are related with the port, my lunchsettings.json, my startup project...
I'm using net core 3.1 and angular 6.

I've tried adding PORT, ASPNETCORE_URLS...and other variables to Azure application settings...

Here the error:

Logs from Azure: Diagnose and solve problems: Application Logs

2020-05-29T05:34:18.801Z INFO - Starting container for site
2020-05-29T05:34:18.802Z INFO - docker run -d -p 6115:8080 --name upisite_0_99ae64d5 -e WEBSITE_SITE_NAME=Upisite -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=upisite.azurewebsites.net -e WEBSITE_INSTANCE_ID=cdbb42914fa53f4972f5e7c6469f3e4ef2f3e5cb1017cfc16cde43debbb77243 appsvc/dotnetcore:3.1-latest_20200101.1

2020-05-29T05:34:18.805Z INFO - Logging is not enabled for this container.
Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here.
2020-05-29T05:37:18.731Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 178.6585207 sec
2020-05-29T05:37:33.866Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 193.7941907 sec
2020-05-29T05:37:51.054Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 210.9819339 sec
2020-05-29T05:38:06.216Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 226.14369 sec
2020-05-29T05:38:15.145Z ERROR - Container upisite_0_99ae64d5 for site upisite did not start within expected time limit. Elapsed time = 235.0733223 sec
**2020-05-29T05:38:15.154Z ERROR - Container upisite_0_99ae64d5 didn't respond to HTTP pings on port: 8080, failing site start. See container logs for debugging.
2020-05-29T05:38:15.175Z INFO - Stopping site upisite because it failed during startup.**

Logs from Azure: Diagnose and solve problems: Container Crash

2020-06-01T16:54:06.752807040Z [40m[1m[33mwarn[39m[22m[49m: Microsoft.AspNetCore.Server.Kestrel[0]
2020-06-01T16:54:06.752872042Z       Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
2020-06-01T16:54:06.806104175Z 2020-06-01 16:54:06.7760|WARN|Microsoft.AspNetCore.Server.Kestrel|Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
2020-06-01T16:54:06.998607188Z 2020-06-01 16:54:06.9983|INFO|Microsoft.Hosting.Lifetime|Now listening on: http://localhost:5000

Mi Program class

```<code>public static void Main(string[] args)
        {
            // ASP.NET Core 3.0+:
            // The UseServiceProviderFactory call attaches the
            // Autofac provider to the generic hosting mechanism.
            var host = Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                })
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webHostBuilder => {
                    webHostBuilder
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseIISIntegration()
              .UseStartup<Startup>();
                })
                .Build();
            host.Run();
        }
</code>```

* Mi Startup class *

```<code> public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
            this.Configuration = builder.Build();
        }
</code>```

* Mi lunchsettings.json *

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

答:
Azure web app only support port 80 and 443. For more details, you can see post1 and post2.

I can see the error which contains port 8080. I guess this might be the cause of the error, you can check it.

If u need use port 8080, you can use Cloud Services or Virtual Machines.

Body:
I've been deployed my app with FTP several times and always worked until now. I'm not using docker, so I suppose azure is dockerizing my app after I upload the files.
I'm getting two errors, I'm not sure if are related with the port, my lunchsettings.json, my startup project...
I'm using net core 3.1 and angular 6.

I've tried adding PORT, ASPNETCORE_URLS...and other variables to Azure application settings...

Here the error:

Logs from Azure: Diagnose and solve problems: Application Logs

2020-05-29T05:34:18.801Z INFO - Starting container for site
2020-05-29T05:34:18.802Z INFO - docker run -d -p 6115:8080 --name upisite_0_99ae64d5 -e WEBSITE_SITE_NAME=Upisite -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=upisite.azurewebsites.net -e WEBSITE_INSTANCE_ID=cdbb42914fa53f4972f5e7c6469f3e4ef2f3e5cb1017cfc16cde43debbb77243 appsvc/dotnetcore:3.1-latest_20200101.1

2020-05-29T05:34:18.805Z INFO - Logging is not enabled for this container.
Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here.
2020-05-29T05:37:18.731Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 178.6585207 sec
2020-05-29T05:37:33.866Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 193.7941907 sec
2020-05-29T05:37:51.054Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 210.9819339 sec
2020-05-29T05:38:06.216Z INFO - Waiting for response to warmup request for container upisite_0_99ae64d5. Elapsed time = 226.14369 sec
2020-05-29T05:38:15.145Z ERROR - Container upisite_0_99ae64d5 for site upisite did not start within expected time limit. Elapsed time = 235.0733223 sec
**2020-05-29T05:38:15.154Z ERROR - Container upisite_0_99ae64d5 didn't respond to HTTP pings on port: 8080, failing site start. See container logs for debugging.
2020-05-29T05:38:15.175Z INFO - Stopping site upisite because it failed during startup.**

Logs from Azure: Diagnose and solve problems: Container Crash

2020-06-01T16:54:06.752807040Z [40m[1m[33mwarn[39m[22m[49m: Microsoft.AspNetCore.Server.Kestrel[0]
2020-06-01T16:54:06.752872042Z       Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
2020-06-01T16:54:06.806104175Z 2020-06-01 16:54:06.7760|WARN|Microsoft.AspNetCore.Server.Kestrel|Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
2020-06-01T16:54:06.998607188Z 2020-06-01 16:54:06.9983|INFO|Microsoft.Hosting.Lifetime|Now listening on: http://localhost:5000

Mi Program class

public static void Main(string[] args)
        {
            // ASP.NET Core 3.0+:
            // The UseServiceProviderFactory call attaches the
            // Autofac provider to the generic hosting mechanism.
            var host = Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                })
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webHostBuilder => {
                    webHostBuilder
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseIISIntegration()
              .UseStartup<Startup>();
                })
                .Build();
            host.Run();
        }

* Mi Startup class *

 public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
            this.Configuration = builder.Build();
        }

* Mi lunchsettings.json *

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:5000",
      "sslPort": 0
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}


问:
Modifying HTML structure using Javascript and the effects on Search Engines
I have a nested ul menu structure that starts off like this:

```<code><div id="left">
    <ul id="left-nav">
        <li>
            <a href="#">Link 1</a>
            <ul class=".sub-nav">
                <li><a href="#">Sublink 1</a></li>
                <li><a href="#">Sublink 2</a></li>
                <li><a href="#">Sublink 3</a></li>
            </ul>
        </li>
        <li>
            <a href="#">Link 2</a>
            <ul class=".sub-nav">
                <li><a href="#">Sublink 1</a></li>
                <li><a href="#">Sublink 2</a></li>
                <li><a href="#">Sublink 3</a></li>
            </ul>
        </li>
    </ul>
</div>
</code>```

Due to a design requirement, I have to have all subnavs outside of their parent
s and append them to the #left container using jQuery.

I also keep a reference to each subnav using ids/data attributes

```<code>var $left = $("#left");
$(".sub-nav").each(function(index) {
    $(this).attr("id", "subnav" + index);
    $(this).parent().data("subnav", index);
    var offsetTop = $(this).parent().position().top;
    $(this).css("top", offsetTop);
    $(this).appendTo($left);
});
</code>```

Here's the resulting HTML

```<code><div id="left">
    <ul id="left-nav">
        <li>
            <a href="#" data-subnav="subnav1">Link 1</a>
        </li>
        <li>
            <a href="#" data-subnav="subnav2">Link 2</a>
        </li>
    </ul>
    <ul class=".sub-nav" id="subnav1">
        <li><a href="#">Sublink 1</a></li>
        <li><a href="#">Sublink 2</a></li>
        <li><a href="#">Sublink 3</a></li>
    </ul>
    <ul class=".sub-nav" id="subnav2">
        <li><a href="#">Sublink 1</a></li>
        <li><a href="#">Sublink 2</a></li>
        <li><a href="#">Sublink 3</a></li>
    </ul>
</div>
</code>```

The menu now works perfectly but I have concerns about the fact that I'm changing the HTML structure and that the semantics are now off. Will this have any impact on Search Engines? Should I have any other concerns?

答:
Google's Webmaster tools has the option to 'fetch as googlebot' - which will show you the document after Google's indexer has parsed it. Run it through there and check for yourself, if you can.

Googlebot definitely doesn't execute javascript. There's some evidence that it can read inline javascript in order to extract URLs to be crawled (for instance, to follow links that have 'onclick' attributes attached to them). You don't need to be concerned about it running your DOM manipulation code.

Body:
I have a nested ul menu structure that starts off like this:

            Link 1

Sublink 1

Sublink 2

Sublink 3

            Link 2

Sublink 1

Sublink 2

Sublink 3

Due to a design requirement, I have to have all subnavs outside of their parent
s and append them to the #left container using jQuery.

I also keep a reference to each subnav using ids/data attributes

var $left = $("#left");
$(".sub-nav").each(function(index) {
    $(this).attr("id", "subnav" + index);
    $(this).parent().data("subnav", index);
    var offsetTop = $(this).parent().position().top;
    $(this).css("top", offsetTop);
    $(this).appendTo($left);
});

Here's the resulting HTML

            Link 1

            Link 2

Sublink 1

Sublink 2

Sublink 3

Sublink 1

Sublink 2

Sublink 3

The menu now works perfectly but I have concerns about the fact that I'm changing the HTML structure and that the semantics are now off. Will this have any impact on Search Engines? Should I have any other concerns?


问:
Very small labels in HERE Maps
As per the HERE Maps JS API platform.createDefaultLayers, by changing the ppi parameter, the font size will be adjusted. But, I'm unable to see any difference in the map. As can be seen in the screenshot below, the labels are too small. How can I make the labels readable in a 7inch 1080p display?

var defaultLayers = platform.createDefaultLayers(512,  320 );

 //Step 2: initialize a map
 var map = new H.Map(document.getElementById('slide-map'),
    defaultLayers.vector.normal.map,{
    center: {lat:27.7279, lng:85.3284},
    zoom: 18,
    pixelRatio: 1
  });```

答:
When I changed defaultLayers.vector.normal.map to defaultLayers.raster.normal.map, the tileSize and ppi parameters started affecting the label size.

var defaultLayers = platform.createDefaultLayers(512,  320 );

 //Step 2: initialize a map
 var map = new H.Map(document.getElementById('slide-map'),
    defaultLayers.raster.normal.map,{
    center: {lat:27.7279, lng:85.3284},
    zoom: 18,
    pixelRatio: 1
  });```

Title: Very small labels in HERE Maps


问:
Async await not behaving properly
Trying to figure out why this does not execute in the order I'm expecting it to. I'm expecting 2 to be the last to execute but it's completing before everything else finishes running.
Can't understand why it's returning the function after 4 and before listening to the stream.

```<code>Future mainFn() async {
    print('Listen 1');
    Ob o = await listenFn();
    print('Listen 2');
    return await someFn(o);
  }

Future<Ob> listenFn() async {
    o = new Ob();
    print('Listen 3');
    Stream<Ct> stream = await getCt();
    print('Listen 4');
    stream.listen((Ct _ct) {
      print('Listen 7');
      if (!cts.contains(_ct)) {
        setState(() {
          cts.add(_ct);
        });
      }
    }, onError: (a) {
      print('Listen 8');
      print(a);
    }, onDone: () async {
      print('Listen 9');
      o = await addOb(cts); <-- This function returns Future<Ob>
    });
  await stream.drain();
  print('Listen 14');
  return o;
  }

Future<Stream<Ct>> getCt() async {
  print('Listen 5');
  final String url = 'API_URL';
  final client = new http.Client();
  final request = http.Request('get', Uri.parse(url));
  final streamedRest = await client.send(request);
  print('Listen 6');
  return streamedRest.stream
      .transform(utf8.decoder)
      .transform(json.decoder)
      .map((data) => Helper.getData(data))
      .expand((data) => (data as List))
      .map((data) {
    return Ct.fromJSON(data);
  });
}
</code>```

I'm getting

```<code>I/flutter (22211): Listen 1
I/flutter (22211): Listen 3
I/flutter (22211): Listen 5
I/flutter (22211): Listen 6
I/flutter (22211): Listen 4
I/flutter (22211): Listen 2
I/flutter (22211): Listen 7 <-- 4 Ct items in the stream
I/flutter (22211): Listen 7
I/flutter (22211): Listen 7
I/flutter (22211): Listen 7
I/flutter (22211): Listen 9
I/flutter (22211): Listen 10 <-- added more of these along the way
I/flutter (22211): Listen 11
I/flutter (22211): Listen 12
I/flutter (22211): Listen 13
</code>```

答:
So if anyone stumbles upon this in the future, I've chanced upon a solution to this. The answer is to use await for.

stream.listen() sets up code that will be put on the event queue when an event arrives, then following code is executed.

await for suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens.

```<code>await for(String s in stream) { print(s); }
</code>```

Credit: https://stackoverflow.com/a/42613676/12689749

Title: Async await not behaving properly

Body:
Trying to figure out why this does not execute in the order I'm expecting it to. I'm expecting 2 to be the last to execute but it's completing before everything else finishes running.
Can't understand why it's returning the function after 4 and before listening to the stream.

Future mainFn() async {
    print('Listen 1');
    Ob o = await listenFn();
    print('Listen 2');
    return await someFn(o);
  }

Future<Ob> listenFn() async {
    o = new Ob();
    print('Listen 3');
    Stream<Ct> stream = await getCt();
    print('Listen 4');
    stream.listen((Ct _ct) {
      print('Listen 7');
      if (!cts.contains(_ct)) {
        setState(() {
          cts.add(_ct);
        });
      }
    }, onError: (a) {
      print('Listen 8');
      print(a);
    }, onDone: () async {
      print('Listen 9');
      o = await addOb(cts); <-- This function returns Future<Ob>
    });
  await stream.drain();
  print('Listen 14');
  return o;
  }

Future<Stream<Ct>> getCt() async {
  print('Listen 5');
  final String url = 'API_URL';
  final client = new http.Client();
  final request = http.Request('get', Uri.parse(url));
  final streamedRest = await client.send(request);
  print('Listen 6');
  return streamedRest.stream
      .transform(utf8.decoder)
      .transform(json.decoder)
      .map((data) => Helper.getData(data))
      .expand((data) => (data as List))
      .map((data) {
    return Ct.fromJSON(data);
  });
}

I'm getting

I/flutter (22211): Listen 1
I/flutter (22211): Listen 3
I/flutter (22211): Listen 5
I/flutter (22211): Listen 6
I/flutter (22211): Listen 4
I/flutter (22211): Listen 2
I/flutter (22211): Listen 7 <-- 4 Ct items in the stream
I/flutter (22211): Listen 7
I/flutter (22211): Listen 7
I/flutter (22211): Listen 7
I/flutter (22211): Listen 9
I/flutter (22211): Listen 10 <-- added more of these along the way
I/flutter (22211): Listen 11
I/flutter (22211): Listen 12
I/flutter (22211): Listen 13

Body:
So if anyone stumbles upon this in the future, I've chanced upon a solution to this. The answer is to use await for.

stream.listen() sets up code that will be put on the event queue when an event arrives, then following code is executed.

await for suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens.

await for(String s in stream) { print(s); }

Credit: https://stackoverflow.com/a/42613676/12689749


问:
Cumulative count on date data from datetime format
I have a table looks like:

```<code>ID entry_time
abc123 2020-05-29 10:29:18.000
def456 2020-05-30 13:12:43.000
...
</code>```

I want to do cumulative count by date, so I did:

select entry_time, count (*) OVER (ORDER BY entry_time) as TOTAL_NUM from my_table;

It is okay, but it will count based on datetime format. I would like to count only on date (i.e. by day, don't care about time).

How would I do that?

Many thanks,

答:
You can try by converting entry time to date.

```<code>select
    convert(date, entry_time) as entry_time,
    count (*) OVER (ORDER BY convert(date, entry_time)) as total_num
from my_table;
</code>```

Body:
I have a table looks like:

ID entry_time
abc123 2020-05-29 10:29:18.000
def456 2020-05-30 13:12:43.000
...

I want to do cumulative count by date, so I did:

select entry_time, count (*) OVER (ORDER BY entry_time) as TOTAL_NUM from my_table;

It is okay, but it will count based on datetime format. I would like to count only on date (i.e. by day, don't care about time).

How would I do that?

Many thanks,

Body:
You can try by converting entry time to date.

select
    convert(date, entry_time) as entry_time,
    count (*) OVER (ORDER BY convert(date, entry_time)) as total_num
from my_table;


问:
Splitting std::vector of size m into vector of vectors of size n
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

```<code>terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc
</code>```

答:
If you're just after some code that can split a vector into a vector of up-to-five-element vectors, this should do it. It's bigger than necessary only because of the test harness around it.

The "meat" of the code is the templated function makeVecOfVecs(), and the single-line call to it. It's quite handy to do this sort of thing as a template since it then becomes easy to extend to other data types. The code is:

```<code>#include <iostream>
#include <vector>

// From a flat vector, construct a vector of sub-vectors, each of a
// specific size (except the last sub-vector, which may be smaller).

template<class T>
std::vector<std::vector<T>>
makeVecOfVecs(
    const std::vector<T> &in,
    unsigned int sz
) {
    std::vector<std::vector<T>> out;
    for (int i = 0; i < in.size(); i += sz) {
        if (in.size() - i < sz)
            sz = in.size() - i;

        std::vector<T> newVec(sz);
        std::copy(in.begin() + i, in.begin() + i + sz, newVec.begin());
        out.push_back(newVec);

        // As pointed out in a comment, you could probably
        // replace the three preceding lines with just:
        //    out.emplace_back(in.begin() + i, in.begin() + i + sz);
        // and avoid creating newVec.
    }

    return out;
}

// Test harness for the above function.

int main(int argc, char *argv[]) {
    // Default to 17 values, allow for override. Could probably
    // make more robust, but is IS only test code.

    int count = 17;
    if (argc > 1)
        count = atoi(argv[1]);

    // Input data for testing, print for validation.

    std::vector<int> in;
    for (int i = 0; i < count; ++i)
        in.push_back(i + 1);
    std::cout << "\nInput (" << count << "):";
    for (const auto &inElem: in)
        std::cout << " " << inElem;
    std::cout << "\n";

    auto out = makeVecOfVecs<int>(in, 5);

    // Output of result for validation.

    std::cout << "Output:\n";
    for (const auto &outElem1: out) {
        std::cout << "   ";
        for (const auto &outElem2: outElem1)
            std::cout << " " << outElem2;
        std::cout << "\n";
    }
}
</code>```

A few sample runs are shown below for validation (you'll see I've asked for a chunk size of 10 rather than 5, that's just to use less space in the answer):

```<code>pax:~> for i in "" 22 20 0 -9 1; do ./testprog ${i}; done

Input (17): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17

Input (22): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17 18 19 20
    21 22

Input (20): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17 18 19 20

Input (0):
Output:

Input (-9):
Output:

Input (1): 1
Output:
    1
</code>```

Body:
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

Body:
If you're just after some code that can split a vector into a vector of up-to-five-element vectors, this should do it. It's bigger than necessary only because of the test harness around it.

The "meat" of the code is the templated function makeVecOfVecs(), and the single-line call to it. It's quite handy to do this sort of thing as a template since it then becomes easy to extend to other data types. The code is:

#include <iostream>
#include <vector>

// From a flat vector, construct a vector of sub-vectors, each of a
// specific size (except the last sub-vector, which may be smaller).

template<class T>
std::vector<std::vector<T>>
makeVecOfVecs(
    const std::vector<T> &in,
    unsigned int sz
) {
    std::vector<std::vector<T>> out;
    for (int i = 0; i < in.size(); i += sz) {
        if (in.size() - i < sz)
            sz = in.size() - i;

        std::vector<T> newVec(sz);
        std::copy(in.begin() + i, in.begin() + i + sz, newVec.begin());
        out.push_back(newVec);

        // As pointed out in a comment, you could probably
        // replace the three preceding lines with just:
        //    out.emplace_back(in.begin() + i, in.begin() + i + sz);
        // and avoid creating newVec.
    }

    return out;
}

// Test harness for the above function.

int main(int argc, char *argv[]) {
    // Default to 17 values, allow for override. Could probably
    // make more robust, but is IS only test code.

    int count = 17;
    if (argc > 1)
        count = atoi(argv[1]);

    // Input data for testing, print for validation.

    std::vector<int> in;
    for (int i = 0; i < count; ++i)
        in.push_back(i + 1);
    std::cout << "\nInput (" << count << "):";
    for (const auto &inElem: in)
        std::cout << " " << inElem;
    std::cout << "\n";

    auto out = makeVecOfVecs<int>(in, 5);

    // Output of result for validation.

    std::cout << "Output:\n";
    for (const auto &outElem1: out) {
        std::cout << "   ";
        for (const auto &outElem2: outElem1)
            std::cout << " " << outElem2;
        std::cout << "\n";
    }
}

A few sample runs are shown below for validation (you'll see I've asked for a chunk size of 10 rather than 5, that's just to use less space in the answer):

pax:~> for i in "" 22 20 0 -9 1; do ./testprog ${i}; done

Input (17): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17

Input (22): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17 18 19 20
    21 22

Input (20): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Output:
    1 2 3 4 5 6 7 8 9 10
    11 12 13 14 15 16 17 18 19 20

Input (0):
Output:

Input (-9):
Output:

Input (1): 1
Output:
    1


问:
Python ElementTree generate not well formed XML file with special character '\x0b'
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)
```

<p><strong>Generated XML</strong>: <code><root>\x0b</root></code> </p>

<p><strong>Error</strong>: </p>

```Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6
```

答: \x0b is an XML restricted character.  There is a good description of valid and restricted characters in the answers to this question.

Body:
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)

Generated XML: <root>\x0b</root>

Error:

Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6


问:
Script to find the last cell edited in a Google sheet has recently stopped
Firstly I am NO programmer - but I found a pretty simple script that we have been running for years on a shared Google sheet that simply finds the last edited cell in a large amount of data. It worked brilliantly, you open the sheet and in no time you're looking at the last line that had been edited and you can begin your data entry. Recently - it simply stopped?
I'm seeing posts about V8 but looking at the script - it says it's running on V8?

```<code>function onOpen() {
  var ThisSheet = SpreadsheetApp.getActiveSpreadsheet();
  var StartingTab = ThisSheet.getSheetByName("Key# 20-30K");  // The default tab being opened
  var LastRow = ThisSheet.getLastRow() + 1;  // One past the last row that has been entered in the spreadsheet
  var LastCellString = "A"+LastRow+":A"+LastRow;  // The string representing the last cell to position to
  var LastCell = ThisSheet.getRange(LastCellString); // The internal variable of the last cell
  StartingTab.setActiveRange(LastCell)  // Actually perform the repositioning to the last cell
}
</code>```

This is the script - any help would be very cool.

Grant

答:
This really isn't that much different but it does work.

```<code>function onOpen() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName("Key# 20-30K");
  sh.getRange(sh.getLastRow()+1,1).activate();
}
</code>```

You do have to authorize the script before you use it.

Body:
Firstly I am NO programmer - but I found a pretty simple script that we have been running for years on a shared Google sheet that simply finds the last edited cell in a large amount of data. It worked brilliantly, you open the sheet and in no time you're looking at the last line that had been edited and you can begin your data entry. Recently - it simply stopped?
I'm seeing posts about V8 but looking at the script - it says it's running on V8?

function onOpen() {
  var ThisSheet = SpreadsheetApp.getActiveSpreadsheet();
  var StartingTab = ThisSheet.getSheetByName("Key# 20-30K");  // The default tab being opened
  var LastRow = ThisSheet.getLastRow() + 1;  // One past the last row that has been entered in the spreadsheet
  var LastCellString = "A"+LastRow+":A"+LastRow;  // The string representing the last cell to position to
  var LastCell = ThisSheet.getRange(LastCellString); // The internal variable of the last cell
  StartingTab.setActiveRange(LastCell)  // Actually perform the repositioning to the last cell
}

This is the script - any help would be very cool.

Grant

Body:
This really isn't that much different but it does work.

function onOpen() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName("Key# 20-30K");
  sh.getRange(sh.getLastRow()+1,1).activate();
}

You do have to authorize the script before you use it.


问:
Combine collection of DataFrames into one big DataFrame
Suppose I have 3 DataFrames. One such DataFrame has a column name that's not in the other two.

```<code>using DataFrames

df1 = DataFrame([['a', 'b', 'c'], [1, 2, 3]], ["name", "id"])
df2 = DataFrame([['d', 'e', 'f'], [4, 5, 6]], ["name", "id"])
df3 = DataFrame([['x', 'y', 'z'], [7, 8, 9], [11, 22, 33]], ["name", "id", "num"])
</code>```

And each DataFrame is an element of a Vector.

```<code>dfs = [df1, df2, df3]
</code>```

I want to combine all of these DataFrames into one big DataFrame. Here's what I've tried:

```<code>df = reduce(x -> vcat(x, cols=:union), dfs)
# MethodError: no method matching (::var"#55#56")(::DataFrame, ::DataFrame)
</code>```

So, how do I do it in Julia?

Bonus points: Can I do it in base Julia, without DataFrames.jl (note: df3 has more columns than the others)?

Since there are a ton of Julia packages that implement DataFrame-like constructs, I'm open to solutions using packages other than DataFrames.jl.

Here's how I'd do it in R:

df1 = data.frame(name = c("a", "b", "c"),
                 id = c(1, 2, 3))

df2 = data.frame(name = c("d", "e", "f"),
                 id = c(4, 5, 6))

df3 = data.frame(name = c("x", "y", "z"),
                 id = c(7, 8, 9),
                 num = c(11, 22, 33))

dfs = list(df1, df2, df3)

library(dplyr)
dplyr::bind_rows(dfs)
```

<p>And Python 3.7:</p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd

df1 = pd.DataFrame({"name": ["a", "b", "c"],
                    "id": [1, 2, 3]})

df2 = pd.DataFrame({"name": ["d", "e", "f"],
                    "id": [4, 5, 6]})

df3 = pd.DataFrame({"name": ["x", "y", "z"],
                    "id": [7, 8, 9],
                    "num": [11, 22, 33]})

dfs = [df1, df2, df3]

pd.concat(dfs)
</code>```

答:
Just do:

```<code>julia> vcat(dfs..., cols=:union)
9×3 DataFrame
│ Row │ name │ id    │ num     │
│     │ Char │ Int64 │ Int64?  │
├─────┼──────┼───────┼─────────┤
│ 1   │ 'a'  │ 1     │ missing │
│ 2   │ 'b'  │ 2     │ missing │
│ 3   │ 'c'  │ 3     │ missing │
│ 4   │ 'd'  │ 4     │ missing │
│ 5   │ 'e'  │ 5     │ missing │
│ 6   │ 'f'  │ 6     │ missing │
│ 7   │ 'x'  │ 7     │ 11      │
│ 8   │ 'y'  │ 8     │ 22      │
│ 9   │ 'z'  │ 9     │ 33      │
</code>```

or

```<code>julia> reduce(vcat, dfs, cols=:union)
9×3 DataFrame
│ Row │ name │ id    │ num     │
│     │ Char │ Int64 │ Int64?  │
├─────┼──────┼───────┼─────────┤
│ 1   │ 'a'  │ 1     │ missing │
│ 2   │ 'b'  │ 2     │ missing │
│ 3   │ 'c'  │ 3     │ missing │
│ 4   │ 'd'  │ 4     │ missing │
│ 5   │ 'e'  │ 5     │ missing │
│ 6   │ 'f'  │ 6     │ missing │
│ 7   │ 'x'  │ 7     │ 11      │
│ 8   │ 'y'  │ 8     │ 22      │
│ 9   │ 'z'  │ 9     │ 33      │
</code>```

Body:
Suppose I have 3 DataFrames. One such DataFrame has a column name that's not in the other two.

using DataFrames

df1 = DataFrame([['a', 'b', 'c'], [1, 2, 3]], ["name", "id"])
df2 = DataFrame([['d', 'e', 'f'], [4, 5, 6]], ["name", "id"])
df3 = DataFrame([['x', 'y', 'z'], [7, 8, 9], [11, 22, 33]], ["name", "id", "num"])

And each DataFrame is an element of a Vector.

dfs = [df1, df2, df3]

I want to combine all of these DataFrames into one big DataFrame. Here's what I've tried:

df = reduce(x -> vcat(x, cols=:union), dfs)
# MethodError: no method matching (::var"#55#56")(::DataFrame, ::DataFrame)

So, how do I do it in Julia?

Bonus points: Can I do it in base Julia, without DataFrames.jl (note: df3 has more columns than the others)?

Since there are a ton of Julia packages that implement DataFrame-like constructs, I'm open to solutions using packages other than DataFrames.jl.

Here's how I'd do it in R:

df1 = data.frame(name = c("a", "b", "c"),
                 id = c(1, 2, 3))

df2 = data.frame(name = c("d", "e", "f"),
                 id = c(4, 5, 6))

df3 = data.frame(name = c("x", "y", "z"),
                 id = c(7, 8, 9),
                 num = c(11, 22, 33))

dfs = list(df1, df2, df3)

library(dplyr)
dplyr::bind_rows(dfs)

And Python 3.7:

import pandas as pd

df1 = pd.DataFrame({"name": ["a", "b", "c"],
                    "id": [1, 2, 3]})

df2 = pd.DataFrame({"name": ["d", "e", "f"],
                    "id": [4, 5, 6]})

df3 = pd.DataFrame({"name": ["x", "y", "z"],
                    "id": [7, 8, 9],
                    "num": [11, 22, 33]})

dfs = [df1, df2, df3]

pd.concat(dfs)

Body:
Just do:

julia> vcat(dfs..., cols=:union)
9×3 DataFrame
│ Row │ name │ id    │ num     │
│     │ Char │ Int64 │ Int64?  │
├─────┼──────┼───────┼─────────┤
│ 1   │ 'a'  │ 1     │ missing │
│ 2   │ 'b'  │ 2     │ missing │
│ 3   │ 'c'  │ 3     │ missing │
│ 4   │ 'd'  │ 4     │ missing │
│ 5   │ 'e'  │ 5     │ missing │
│ 6   │ 'f'  │ 6     │ missing │
│ 7   │ 'x'  │ 7     │ 11      │
│ 8   │ 'y'  │ 8     │ 22      │
│ 9   │ 'z'  │ 9     │ 33      │

or

julia> reduce(vcat, dfs, cols=:union)
9×3 DataFrame
│ Row │ name │ id    │ num     │
│     │ Char │ Int64 │ Int64?  │
├─────┼──────┼───────┼─────────┤
│ 1   │ 'a'  │ 1     │ missing │
│ 2   │ 'b'  │ 2     │ missing │
│ 3   │ 'c'  │ 3     │ missing │
│ 4   │ 'd'  │ 4     │ missing │
│ 5   │ 'e'  │ 5     │ missing │
│ 6   │ 'f'  │ 6     │ missing │
│ 7   │ 'x'  │ 7     │ 11      │
│ 8   │ 'y'  │ 8     │ 22      │
│ 9   │ 'z'  │ 9     │ 33      │


答:
If you want one record per day, you can use aggregation and window functions:

```<code>select
    date(entry_time) entry_day,
    sum(count(*)) over(order by date(entry_time)) total_num
from mytable
group by date(entry_time)
order by entry_day
</code>```

This assumes that your database supports the date(), that converts a datetime to a date (as in MySQL for example). If it does not, it sure has an alternative way to do this.

Title: Cumulative count on date data from datetime format

Body:
If you want one record per day, you can use aggregation and window functions:

select
    date(entry_time) entry_day,
    sum(count(*)) over(order by date(entry_time)) total_num
from mytable
group by date(entry_time)
order by entry_day

This assumes that your database supports the date(), that converts a datetime to a date (as in MySQL for example). If it does not, it sure has an alternative way to do this.


问:
Android Listener working in activity but not in fragment
I have an activity and two fragments. Im trying to get a clicked item from an arraylist. In my fragmentA I have a interface:

```<code>public interface GroupListener {
        public String onGroupSelected(String groupName);
}
</code>```

and

```<code>    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            groupListener = (GroupListener) context;
        } catch (ClassCastException e)
        {
            throw new ClassCastException(context.toString() + " must implement the interface" +
                    "called GroupListener!");
        }
    }
</code>```

This gets the postion from an item clicked in a list :

```<code>    public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
        groupListener.onGroupSelected((String) getListAdapter().getItem(position));
    }
</code>```

I then have the listner in my activity and in fragmentB which looks the same:

```<code>   @Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in Activity");
        return groupName;
    }
</code>```

```<code>   @Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in fragmentB");
        return groupName;
    }
</code>```

But when i click an item only the listener in my activity is activated, not the one in my fragment. What is it that im missing?

答:
The one in FragmentB will not fire, since you are only communicating with the activity from fragment A.

In your activity do something like this:

```<code>Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in Activity");
        FragmentB frag = //find your fragment using fragment manager
        frag.onGroupSelected(groupName);
        return groupName;
    }
</code>```

This is how you call methods inside fragment from an activity

Body:
I have an activity and two fragments. Im trying to get a clicked item from an arraylist. In my fragmentA I have a interface:

public interface GroupListener {
        public String onGroupSelected(String groupName);
}

and

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            groupListener = (GroupListener) context;
        } catch (ClassCastException e)
        {
            throw new ClassCastException(context.toString() + " must implement the interface" +
                    "called GroupListener!");
        }
    }

This gets the postion from an item clicked in a list :

    public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
        groupListener.onGroupSelected((String) getListAdapter().getItem(position));
    }

I then have the listner in my activity and in fragmentB which looks the same:

   @Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in Activity");
        return groupName;
    }

   @Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in fragmentB");
        return groupName;
    }

But when i click an item only the listener in my activity is activated, not the one in my fragment. What is it that im missing?

Body:
The one in FragmentB will not fire, since you are only communicating with the activity from fragment A.

In your activity do something like this:

Override
    public String onGroupSelected(String groupName) {
        System.out.println("in onGroup  in Activity");
        FragmentB frag = //find your fragment using fragment manager
        frag.onGroupSelected(groupName);
        return groupName;
    }

This is how you call methods inside fragment from an activity


问:
Searching through data frame columns in type string (containing numeric range), with user inputs that are in type float
Trying to only use python installed libraries and pandas library because I am a complete novice. I am wrapping up a 6 week python foundations course.

For a final project, I am making a plant buying guide. Based on a series of questions I am asking the user, I am parsing out a data frame containing 60 entries. To give you an idea, the first section of my question created a filtered data frame using this code

```<code>care_df = df.loc[
    lambda x:
    (x['sunlight'].str.lower().str.contains(user_sunlight_pref.lower()))
    & (x['watering_levels'].str.lower().str.contains(user_water_pref.lower()))
    & (x['humidity_preference'].str.lower().str.contains(user_humidity_pref.lower()))
    ]
</code>```

where user_sunlight_pref stored user input (ie maybe they chose 'Indirect light' as their sunlight preference).

NOW, I am on my second section of questions where I begin to ask about height and spread. The data frame columns I will be searching for have this format of entry: '1.00 to 2.00 feet'.

MY QUESTION/PROBLEM: For the user questions, I've tried to make descriptive ranges that I present to the user as possible options that they submit as their input:

```<code>"Desk range- plants that are appropriate for desks and surfaces, like short bookshelves or corner areas."
" These plants will not block eyesight."
</code>```

On the back end, I want to create a numeric range, like 'desk range' = anything between 0.25 to 1.50,that I could then use to search through my data frame. am having trouble thinking through what type(s) to use, how to create a range for my dataframe column values (like 1.00 to 2.00)feet......

***or the cop-out would be I manually categorize the plant entries into their appropriate descriptive range, but then I run into a similar issue: I could do something like:

```<code>if user_height_pref == 'Desk range'
   user_height_pref = [0.25 to 1.00 feet, 0.25 to 0.75 feet, 1.00 to 1.50 feet...]
</code>```

but then how do I search through through my dataframe height column? Unsure of how to search/match elements of this list to my dataframe column (using a similar code as care_df)

答:
You can filter with multiple criteria.

```<code>df1 = df[(df['Feet'] >=0.25) & (df['Feet'] <= 1.0)]
</code>```

You can also check out this post.

How to select rows in a DataFrame between two values, in Python Pandas?

Body:
Trying to only use python installed libraries and pandas library because I am a complete novice. I am wrapping up a 6 week python foundations course.

For a final project, I am making a plant buying guide. Based on a series of questions I am asking the user, I am parsing out a data frame containing 60 entries. To give you an idea, the first section of my question created a filtered data frame using this code

care_df = df.loc[
    lambda x:
    (x['sunlight'].str.lower().str.contains(user_sunlight_pref.lower()))
    & (x['watering_levels'].str.lower().str.contains(user_water_pref.lower()))
    & (x['humidity_preference'].str.lower().str.contains(user_humidity_pref.lower()))
    ]

where user_sunlight_pref stored user input (ie maybe they chose 'Indirect light' as their sunlight preference).

NOW, I am on my second section of questions where I begin to ask about height and spread. The data frame columns I will be searching for have this format of entry: '1.00 to 2.00 feet'.

MY QUESTION/PROBLEM: For the user questions, I've tried to make descriptive ranges that I present to the user as possible options that they submit as their input:

"Desk range- plants that are appropriate for desks and surfaces, like short bookshelves or corner areas."
" These plants will not block eyesight."

On the back end, I want to create a numeric range, like 'desk range' = anything between 0.25 to 1.50,that I could then use to search through my data frame. am having trouble thinking through what type(s) to use, how to create a range for my dataframe column values (like 1.00 to 2.00)feet......

***or the cop-out would be I manually categorize the plant entries into their appropriate descriptive range, but then I run into a similar issue: I could do something like:

if user_height_pref == 'Desk range'
   user_height_pref = [0.25 to 1.00 feet, 0.25 to 0.75 feet, 1.00 to 1.50 feet...]

but then how do I search through through my dataframe height column? Unsure of how to search/match elements of this list to my dataframe column (using a similar code as care_df)

Body:
You can filter with multiple criteria.

df1 = df[(df['Feet'] >=0.25) & (df['Feet'] <= 1.0)]

You can also check out this post.

How to select rows in a DataFrame between two values, in Python Pandas?


问:
Steps required to do multiple scans in a single pipeline
Can anyone help me to understand what's necessary to perform several sonar scans in a single pipeline?  I've read that sonarcloud doesn't support multiple project scans into a single project, so i separated them into different sonarcloud projects.

I am using the SonarCloud scanner extension from the marketplace, on hosted build agents.

I have a rather large .net ASP.NET MVC legacy framework application, which also includes a reactjs application in the Scripts folder. I don't want to include the reactjs files in the msbuild scan because this is constantly changing, and the developer uses vscode rather than visual studio.  Keeping the csproj up to date would be a nightmare.

So I want to scan the reactjs folder separately using the stand-alone scanner, and use the msbuild scanner with the .net app.

The scanner works fine for the .net app, but i'm unable to get any scan output from the stand-alone scanner.  It just shows an empty result.

I've got the following tasks...

Prepare Analysis (separate sonarcloud project)
npm install
npm build
Run Analysis

Prepare Analysis (for .net) (separate sonarcloud project)
nuget restore
visual studio build task
Run Analysis

Publish build gate
Upload artifacts

I've set the sonar.exclusions of the .net project (on the sonarcloud admin settings, not in a file in my scm) to exclude the reactjs folder (Scripts/react/**/*), and scanning of the .net project seems to work.

I've set the sonar.sources for the javascript scanner task to be the reactjs folder

However, the javascript scan is empty.

I'm at a loss...

Is it the fact that i'm running two scans in the same pipeline?  Do i need to run the build gate after the JS scan as well?  Is the second scan overwriting the first?  Does the Run Analysis actually publish the results or is the Publish build gate?

答:
So the problem was that i was using an includes parameter in my stand-alone scanner to scan only the subfolders.  The problem was that my assumption was that the includes was rooted on the sources folder, but in reality it's rooted on the project root folder (this can be configured).

So changing the paths to be absolute from the root fixed them problem.


问:
Wildcard SSL certificate on Google App Engine + Cloudflare
I have a domain, example.com and want to support wildcard subdomains such as *.example.com on SSL.

My app is running on Google App Engine and hoping to use Cloudflare to proxy all the requests to my domain on SSL. Please note I'm on the Free plan of Cloudflare.

My question is whether I need to purchase a separate wildcard subdomain certificate apart from using Cloudflare's.

I want to enable Full (strict) SSL method on Cloudflare. My understanding was that I could install the Origin certificate issued by Cloudflare on GAE (so that GAE <-> Cloudflare is secure), and then use the universal SSL certificate issued by Cloudflare so that Cloudflare
<-> browser is secure. Is there a need to ever purchase a separate wildcard subdomain cert, or can I make use of (universal + origin certificates) Cloudflare's SSL entirely?

If my understanding above isn't correct and I need to purchase a separate SSL wildcard subdomain cert - once I upload this to GAE, is my connection from GAE to the browser secure from end-to-end ? Will the SSL on GAE be validated by Cloudflare and then it is able to proxy the wildcard subdomain requests on SSL ?

If anyone versed and knowledgeable in this area could help understand the flow, that would be really appreciated.

答:
I'm familiar with Cloudflare but not GAE. For Full (Strict) you will have to have a cert that is valid for both example.com and *.example.com in both Cloudflare and your origin servers. Cloudflare will take care of the edge certificate that the browser/client will interact with.

As you assumed, the origin cert Cloudflare issues will work and will be free. When you ask Cloudflare to generate this, you can specify the domains, which should include example.com and *.example.com. Cloudflare will issue you a self signed cert for example.com with a SAN for *.example.com. The up side of this are that it's free and will have a long expiration time (if you want). The down side is that if you ever have to drop cloudflare or interact with the origin servers without cloudflare, the cert will not be signed by a root CA. These requests will generally fail in clients and browsers unless you specifically make client configuration changes to trust this cert, and certainly a random browser accessing this server will get a certificate error.

A root CA signed cert for example.com with a SAN for *.example.com will also work. The down sides of this is it will generally cost money unless you use a free service like letsencrypt. You will probably also have to renew this cert more often than a self signed cert and an expired cert will result in downtime in Full Strict mode. The up side of this is that generally any request you send directly to the origin servers will work, even in a random browser.

For me, I would go with root CA signed cert (even a free one if need be) so that if I absolutely had to drop cloudflare in an emergency, I could just switch DNS to the origin servers and still be okay. Only if I had some complete dependency on Cloudflare, like workers or DDoS protection would I go with the Cloudflare self signed cert.


问:
My react app in the gh-pages is only showing the read.me not the index.js;
My react app is not loading the index.js, you can see my repository at https://github.com/Vitorrrocha/Star-Wars-info and the gh-pages: https://vitorrrocha.github.io/Star-Wars-info/ .

package.json: https://github.com/Vitorrrocha/Star-Wars-info/blob/master/package.json

答:
Which branch are you trying to serve as a GitHub page? I see you have just a master branch.

You could make a branch called gh-pages and push your build there. I see you have gh-pages installed as a devDependency. You can use gh-pages -d build it will do everything for you. (build is the output folder of react-scripts build.)


问:
How to populate my Django Model 'updated_by' field with logged in User automatically using a formset?
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

```<code>class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()
</code>```

答: I think the problem lies in your views.py. Try getting request.user before saving the form. </p>

Body:
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()


问:
Google Play Store Security Alert Says that your app contains Vulnerable JavaScript libraries how to remove the security warning?
In Google Play Store am getting warning below like this,

Your app contains one or more libraries with known security issues. Please see this Google Help Center article for details.

Vulnerable JavaScript libraries:

Name --> jquery

Version --> 3.3.1

Known issues --> SNYK-JS-JQUERY-174006

Identified files --> res/raw/jquery_min.js

Note: when loading webview in my app i will InterceptRequest in webview url and load the local jquery_min.js file from raw folder resource which helps us to load the webpage faster due this function and i save 5 gb download from server per month.

Sample WebView Program

```<code>    LoadLocalScripts localScripts=new LoadLocalScripts(this);
    webView.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    return true;
                }

                //Show loader on url load
                public void onLoadResource(WebView view, String url) {

                }

                public void onPageFinished(WebView view, String url) {

                    }
                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                }

                @Override
                public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {

                    WebResourceResponse response= localScripts.getLocalSCripts(url);
                    if(response==null) {
                        return super.shouldInterceptRequest(view, url);
                    }else{
                        return response;
                    }
                }

            });

  webView.loadUrl(url);
</code>```

Class for Loading local scripts

```<code> public class LoadLocalScripts {
    private Context ctx;

    public LoadLocalScripts(Context context) {
        ctx=context;
    }

    public WebResourceResponse getLocalSCripts(String url)
    {
        //Log.e("url_raw",url);

        if (url.contains(".css")) {
            if(url.contains("bootstrap.min.css")) {
                return getCssWebResourceResponseFromRawResource("bootstrap_min.css");
            }else {
                return null;
            }
        }else  if (url.contains(".js")){
             if(url.contains("bootstrap.min.js")) {
                return getScriptWebResourceResponseFromRawResource("bootstrap_min.js");
            } else if(url.contains("jquery.lazyload.min.js")) {
                 return getScriptWebResourceResponseFromRawResource("lazyload_min.js");
             } else{
                 return null;
             }
        } else {
            return null;
        }
    }

    /**
     * Return WebResourceResponse with CSS markup from a raw resource (e.g. "raw/style.css").
     */
    private WebResourceResponse getCssWebResourceResponseFromRawResource(String url) {

        //Log.e("url_raw",url);
        if(url.equalsIgnoreCase("bootstrap_min.css")) {
            return getUtf8EncodedCssWebResourceResponse(ctx.getResources().openRawResource(R.raw.bootstrap_min));
        }else {
            return null;
        }
    }

    private WebResourceResponse getScriptWebResourceResponseFromRawResource(String url) {

        //Log.e("url_raw",url);
        if(url.equalsIgnoreCase("bootstrap_min.js")) {
            return getUtf8EncodedScriptWebResourceResponse(ctx.getResources().openRawResource(R.raw.bootstrap_min_js));
        }else if(url.equalsIgnoreCase("lazyload_min.js")) {
            return getUtf8EncodedScriptWebResourceResponse(ctx.getResources().openRawResource(R.raw.lazyload_min));
        }else {
            return null;
        }
    }

    private WebResourceResponse getUtf8EncodedCssWebResourceResponse(InputStream data) {
        return new WebResourceResponse("text/css", "UTF-8", data);
    }

    private WebResourceResponse getUtf8EncodedScriptWebResourceResponse(InputStream data) {
        return new WebResourceResponse("text/javascript", "UTF-8", data);
    }
}
</code>```

If i update new to Jquery script will google play remove Security
Alert (Vulnerable JavaScript libraries)?

If i place Jquery script somewhere else in my app will google play
remove Security Alert?

Let me know what is the efficient way of loading the script in
webview without loading everytime from the server.

答:
I have solved this using the jQuery from CDN.

I am using jQueryMobile in my apps which is not supported by jQuery v3+. So, I had no choice but to stick with jQuery v2. So, I have used Google's CDN instead of local .js file and it worked!

Body:
In Google Play Store am getting warning below like this,

Your app contains one or more libraries with known security issues. Please see this Google Help Center article for details.

Vulnerable JavaScript libraries:

Name --> jquery

Version --> 3.3.1

Known issues --> SNYK-JS-JQUERY-174006

Identified files --> res/raw/jquery_min.js

Note: when loading webview in my app i will InterceptRequest in webview url and load the local jquery_min.js file from raw folder resource which helps us to load the webpage faster due this function and i save 5 gb download from server per month.

Sample WebView Program

    LoadLocalScripts localScripts=new LoadLocalScripts(this);
    webView.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    return true;
                }

                //Show loader on url load
                public void onLoadResource(WebView view, String url) {

                }

                public void onPageFinished(WebView view, String url) {

                    }
                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                }

                @Override
                public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {

                    WebResourceResponse response= localScripts.getLocalSCripts(url);
                    if(response==null) {
                        return super.shouldInterceptRequest(view, url);
                    }else{
                        return response;
                    }
                }

            });

  webView.loadUrl(url);

Class for Loading local scripts

 public class LoadLocalScripts {
    private Context ctx;

    public LoadLocalScripts(Context context) {
        ctx=context;
    }

    public WebResourceResponse getLocalSCripts(String url)
    {
        //Log.e("url_raw",url);

        if (url.contains(".css")) {
            if(url.contains("bootstrap.min.css")) {
                return getCssWebResourceResponseFromRawResource("bootstrap_min.css");
            }else {
                return null;
            }
        }else  if (url.contains(".js")){
             if(url.contains("bootstrap.min.js")) {
                return getScriptWebResourceResponseFromRawResource("bootstrap_min.js");
            } else if(url.contains("jquery.lazyload.min.js")) {
                 return getScriptWebResourceResponseFromRawResource("lazyload_min.js");
             } else{
                 return null;
             }
        } else {
            return null;
        }
    }

    /**
     * Return WebResourceResponse with CSS markup from a raw resource (e.g. "raw/style.css").
     */
    private WebResourceResponse getCssWebResourceResponseFromRawResource(String url) {

        //Log.e("url_raw",url);
        if(url.equalsIgnoreCase("bootstrap_min.css")) {
            return getUtf8EncodedCssWebResourceResponse(ctx.getResources().openRawResource(R.raw.bootstrap_min));
        }else {
            return null;
        }
    }

    private WebResourceResponse getScriptWebResourceResponseFromRawResource(String url) {

        //Log.e("url_raw",url);
        if(url.equalsIgnoreCase("bootstrap_min.js")) {
            return getUtf8EncodedScriptWebResourceResponse(ctx.getResources().openRawResource(R.raw.bootstrap_min_js));
        }else if(url.equalsIgnoreCase("lazyload_min.js")) {
            return getUtf8EncodedScriptWebResourceResponse(ctx.getResources().openRawResource(R.raw.lazyload_min));
        }else {
            return null;
        }
    }

    private WebResourceResponse getUtf8EncodedCssWebResourceResponse(InputStream data) {
        return new WebResourceResponse("text/css", "UTF-8", data);
    }

    private WebResourceResponse getUtf8EncodedScriptWebResourceResponse(InputStream data) {
        return new WebResourceResponse("text/javascript", "UTF-8", data);
    }
}

If i update new to Jquery script will google play remove Security
Alert (Vulnerable JavaScript libraries)?

If i place Jquery script somewhere else in my app will google play
remove Security Alert?

Let me know what is the efficient way of loading the script in
webview without loading everytime from the server.


问:
How to tell my .NET application which IP address to request from?
If I have a Windows server with more than one IP address, how do I pro grammatically tell different instances of my application to use a different IP address when communicating with the internet?</p>

Body: Set ServicePoint.BindIPEndPointDelegate.


问:
How do I construct and return two values, one of which references the other
Say a B contains a reference to an A:

struct A;

struct B<'t> {
    a_ref: &'t A,
}
```

<p>My goal is to write a simple function <code>f</code> that makes the following two equivalent (though one may use the heap).</p>

<pre class="lang-rust prettyprint-override"><code>let (a, b) = f();
</code>```

let a = A { };
let b = B { a_ref: &a };
```

<p>How would I write <code>f</code>? Here's an attempt:</p>

<pre class="lang-rust prettyprint-override"><code>fn f<'t>() -> (A, B<'t>) {
    let a = A { };
    let b = B { a_ref: &a };
    (a, b)
}
</code>```

But it fails to compile with two errors, which I understand but am not sure how to avoid:

error[E0515]: cannot return value referencing local variable `a`

error[E0505]: cannot move out of `a` because it is borrowed

I have seen Why can't I store a value and a reference to that value in the same struct?. Above, I wrote two lines of code that create an A and a B. My question is not why my attempt to abstract those two lines fails. My question is how to abstract (something like) those two lines.

Yes, my attempt tries to store a value and a reference to that value in a struct, but whatever, that is not the goal. I know that does not and cannot work. That is not what I'm trying to accomplish. My goal is something unrelated and which may be possible regardless. For example, returning a closure or using a macro could work.

答:
So the problem here is that f is giving out ownership of a to its caller:

a is created inside f. a belongs to f.

f returns a, transferring ownership to its caller.

a is now moved from f to the caller.

The problem with moves is that they have the right to move the variable in memory. This would invalidate all references to that variable, and therefore no references are allowed to a variable whenever it is moved.

What you could do is have f receive a reference to a and return a new B with a reference to a: example.

Body:
Say a B contains a reference to an A:

struct A;

struct B<'t> {
    a_ref: &'t A,
}

My goal is to write a simple function f that makes the following two equivalent (though one may use the heap).

let (a, b) = f();

let a = A { };
let b = B { a_ref: &a };

How would I write f? Here's an attempt:

fn f<'t>() -> (A, B<'t>) {
    let a = A { };
    let b = B { a_ref: &a };
    (a, b)
}

But it fails to compile with two errors, which I understand but am not sure how to avoid:

error[E0515]: cannot return value referencing local variable `a`

error[E0505]: cannot move out of `a` because it is borrowed

I have seen Why can't I store a value and a reference to that value in the same struct?. Above, I wrote two lines of code that create an A and a B. My question is not why my attempt to abstract those two lines fails. My question is how to abstract (something like) those two lines.

Yes, my attempt tries to store a value and a reference to that value in a struct, but whatever, that is not the goal. I know that does not and cannot work. That is not what I'm trying to accomplish. My goal is something unrelated and which may be possible regardless. For example, returning a closure or using a macro could work.


问:
set image wallpaper to fit screen "
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code</p>

```<code>item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});
</code>```

答:
You can use this ImageView attributes

```<code>  android:scaleType="fitXY"
</code>```

more link

Title: set image wallpaper to fit screen "

Body:
I want to set the image to fit all screen when the user makes it as background for his device, I tried many codes but it does not work.
Here is my code

item_home_image = findViewById(R.id.item_home_image);
item_home_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (checkPermission()) {
            final Intent intent = getIntent();
            String url = intent.getStringExtra("imageUrl");
            Picasso.with(PicassoDisplayImageAdapter.this).load(url).into(new Target() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    WallpaperManager wallpaperManager = WallpaperManager.getInstance(PicassoDisplayImageAdapter.this);
                    try {
                        wallpaperManager.setBitmap(bitmap);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    Toasty.normal(PicassoDisplayImageAdapter.this, "تم تغيير الخلفية بنجاح", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onBitmapFailed(final Drawable errorDrawable) {
                    Toasty.error(PicassoDisplayImageAdapter.this, "فشل تحميل الصورة", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrepareLoad(final Drawable placeHolderDrawable) {
                    Toasty.normal(PicassoDisplayImageAdapter.this, "جاري التحميل", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
});

Body:
You can use this ImageView attributes

  android:scaleType="fitXY"

more link