问:
Rancher - How to expose my services publicly?
I have a running Rancher setup as the following:

Host machine (running rancher/rancher container) on a public IP;

Nodes in an exclusive network (10.1.1.0/24) not accessible from the Internet.

My goal is to serve a web application using the Rancher Load Balancing or whatever similar stuff.
For that, I've perfomed the following steps:

Deploy workload using the "rancher/hello-world" image on 3 pods mapping port 80/tcp as a NodePort (listening port is random) named "web-app";

Add Ingress named "hello" in same namespace selecting "Automatically generate a .xip.io hostname" and adding route "/" to the "web-app" on port 80.

This works on the local network, since I get an address like http://hello.gabriel-milan.10.1.1.14.xip.io/ that would resolve to 10.1.1.14, which is local.

I wanted to expose this service for one of my public IPs. How can I do that?

答:
Edit 2021-09-27: xip.io is gone, but I'm leaving those references in my response because the OP asked about xip.io. Alternatives are sslip.io and nip.io, which both function the same way. You can replace xip.io in my response with either of those to achieve the same results.

There are a couple ways of doing this. Based on your use of a private network that is not accessible from the Internet, the nodes don't have public IPs, and therefore Kubernetes doesn't know anything about whatever public IP is mapped to them. This is how it works in EC2, or anywhere that has a NAT happening off the nodes.

If those nodes are a Custom cluster (where you install Docker and then use the docker run command from Rancher to install RKE and join the cluster to Rancher), then before you install, you can click the Advanced Options link in the bottom right corner and set the public and private IPs for each node.

When you do this, the nodes receive a label that holds the public IP, and that address will be used with your xip.io hostname that you generate when setting up the Ingress.

Without that label, the xip.io hostname picks up the primary IP of the node, which in this case is on the private network.

If you do this, though, your traffic will only go to one node on the cluster, even if your ingress controller is listening on multiple nodes.

Instead, when running a multi-node cluster, I recommend that you put a Layer 4 load balancer in front of all worker nodes (or the nodes where the ingress controller is listening if it's not listening on every node). Punch through 80 and 443, and then use that as the target for your domain.

domain.com -> load balancer -> ingress controller (on all nodes) -> Service -> Pods

Your ingress controller is listening on 80/443 for HTTP traffic, which also means that your Service doesn't have to be NodePort. It can be ClusterIP because traffic goes through the ingress controller and then is routed inside the cluster.

NodePort services are used when you have an external load balancer and you need to direct traffic to a specific service. In that scenario, the external load balancer replaces the ingress controller. You create NodePort services for each of your apps, and then you tell the load balancer to send traffic for App A to each node on port 30547 or whatever the NodePort is for that service.

Incidentally, if you're in a cloud provider, you can combine these into a LoadBalancer Service. That will create a NodePort Service on the nodes and then reach out to the cloud provider's API and deploy a cloud load balancer and then program it with the nodes, the port for the Service, and maintain that configuration for the life of the Service.

To recap:

Your nodes don't know their public IP, so the xip.io hostname can't know it either

Put a Layer 4 load balancer in front of your nodes and send traffic to 80/443 on all nodes

Change your Service to be ClusterIP

Send traffic to the load balancer

Also, as a workaround if you don't want to deploy a load balancer, you can delete the Ingress and recreate it, but instead of creating an xip.io hostname automatically, choose "Set a hostname" and create it manually. If one node's public IP is 1.2.3.4, then you can set it to any.thing.you.want.1.2.3.4.xip.io and it'll return 1.2.3.4 to DNS queries.

You just can't edit an existing xip.io Ingress and change it to a different manual xip.io hostname. You have to recreate it.

In this workaround traffic is still coming in to the ingress controller, so you can still change your Service from NodePort to ClusterIP.

Disclosure: I work for Rancher.


来源: stackexchange

问:
How can I keep output shown in the IPython notebook?
I have a Jupyter notebook that runs correctly. I want to keep the output cell inside of the notebook to see output without running again. I noticed that when I run the notebook cell by cell, it doesn’t show out[] after each In[] cell.

How can I have an save my notebook in a way that all outputs show without re-running?

Thank You.

答:
If you want to get Out[], be sure to write a single variable at the bottom of the cell. The "Out[*]" variable equals to it.

Following is an example, Out[1] is the variable "v"

It's the same for figure, you can write code like this

do not write expression only, it won't output anything

ContentLicense: CC BY-SA 4.0


问:
Comparing iterators crashes program without errors in custom bubble sort implementation
I'm relatively new to C++. I have been trying to use iterators to sort a vector. I'm using bubble sort. I don't want to know if my bubble sort implementation works or not, I just want to know what's crashing my program.

```<code>template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter &j = end; j != start; j--) {
        for (iter &i = start; i != end; i++) {
            // std::cout << *i << std::endl;
            if (*i > *(i + 1)) { // this line is where it stops
                std::iter_swap(i, i + 1);
            }
        }
    }

    std::cout << "ended"; // this line never gets called
}
</code>```

When the program stops, though, it doesn't show any exceptions. I also try-catched the part where it stopped, but it didn't go in the try catch. Also, whenever I un-comment the first printing line:

```<code>std::cout << *i << std::endl;
</code>```

It prints 1168169449 forever. What is going wrong here?

I'm testing it like this:

```<code>std::vector<int> vector = {1, 2, 3, 6, 4, 5};
std::vector<int> temp = vector;
//std::sort(temp.begin(), temp.end());
bubbleSort(vector.begin(), vector.end());
for(auto& num : vector) {
    std::cout << num << std::endl;
}
</code>```

答:
You are dereferencing the end iterator which you cannot dereference.

In your loop you go through each iterator until the end. Problem is, you plus the iterator each time. When the iterator is equal to end - 1 and you add that one to it you will receive end which you then dereference. This is undefined behaviour, thus the random number.

You could try changing the loop condition to be != end - 1 which would mean i + 1 could never be end.

Body:
I'm relatively new to C++. I have been trying to use iterators to sort a vector. I'm using bubble sort. I don't want to know if my bubble sort implementation works or not, I just want to know what's crashing my program.

template<typename iter>
void bubbleSort(iter start, iter end) {
    for (iter &j = end; j != start; j--) {
        for (iter &i = start; i != end; i++) {
            // std::cout << *i << std::endl;
            if (*i > *(i + 1)) { // this line is where it stops
                std::iter_swap(i, i + 1);
            }
        }
    }

    std::cout << "ended"; // this line never gets called
}

When the program stops, though, it doesn't show any exceptions. I also try-catched the part where it stopped, but it didn't go in the try catch. Also, whenever I un-comment the first printing line:

std::cout << *i << std::endl;

It prints 1168169449 forever. What is going wrong here?

I'm testing it like this:

std::vector<int> vector = {1, 2, 3, 6, 4, 5};
std::vector<int> temp = vector;
//std::sort(temp.begin(), temp.end());
bubbleSort(vector.begin(), vector.end());
for(auto& num : vector) {
    std::cout << num << std::endl;
}


问:
Cannot assign reason to dependency
I try to add a reason to a dependency like:

```<code>implementation("foo:bar:0.1.0") { reason = "test" }
</code>```

But get an error, stating that "val cannot be reassigned".
I can't find the source I got this from, but from my memory this was the way. What am I doing wrong?

答:
Based on the example at https://docs.gradle.org/current/userguide/declaring_dependencies.html#sec:documenting-dependencies it looks like it should be</p>

```<code>implementation("foo:bar:0.1.0") { because("test") }
</code>```

Title: Cannot assign reason to dependency

Body:
I try to add a reason to a dependency like:

implementation("foo:bar:0.1.0") { reason = "test" }

But get an error, stating that "val cannot be reassigned".
I can't find the source I got this from, but from my memory this was the way. What am I doing wrong?

Body:
Based on the example at https://docs.gradle.org/current/userguide/declaring_dependencies.html#sec:documenting-dependencies it looks like it should be

implementation("foo:bar:0.1.0") { because("test") }


问:
Efficient way to create pairs of all combinations of column names as a rows in a data.frame
I have this data.frame in R:

```<code>df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))
</code>```

```<code>  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12
</code>```

and would like to turn it into a data frame with all possible combinations of colors (colnames to rows), maintaining the Letter and ID of each pair, like in here:

```<code>   Col_1    Col_2    C1  C2  Letter  ID
1  blue     yellow   0   0   A       23
2  blue     green    0   1   A       23
3  yellow   green    0   1   A       23
4  blue     yellow   1   0   B       57
5  blue     green    1   1   B       57
6  yellow   green    0   1   B       57
7  blue     yellow   1   1   C       48
8  blue     green    1   1   C       48
9  yellow   green    1   1   C       48
10 blue     yellow   0   1   D       3
11 blue     green    0   0   D       3
12 yellow   green    1   0   D       3
13 blue     yellow   1   1   E       12
14 blue     green    1   0   E       12
15 yellow   green    1   0   E       12
</code>```

Since my database is huge doing so with loops is taking too long. Any suggestions to do it more efficiently?

Thank you.

答:
Consider following base solution to dynamically fit any needed set of values:

Data

```<code>txt <- '  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12'

df <- read.table(text = txt, header=TRUE)
</code>```

Solution

```<code># DEFINE VECTOR OF VALUES
vals <- c("blue", "yellow", "green")

# RESHAPE DATA LONG
rdf <- reshape(df, idvar = c("Letter", "ID"),
               varying = vals, times = vals,
               v.names = "C", timevar = "Col1", ids = NULL,
               new.row.names = 1:1E4, direction = "long")

# HELPER DF FOR ALL POSSIBLE COMBNS (AVOID REVERSE DUPLICATES)
col_df <- subset(expand.grid(Col1 = vals, Col2 = vals,
                             stringsAsFactors = FALSE),
                 Col1 < Col2)

# MERGE TWICE FOR EACH SET OF COLs
mdf <- merge(merge(rdf, col_df, by.x="Col1", by.y="Col1"), rdf,
             by.x=c("Letter", "ID", "Col2"),
             by.y=c("Letter", "ID", "Col1"),
             suffixes = c(1, 2))

# RE-ORDER ROWS AND COLUMNS
mdf <- data.frame(with(mdf, mdf[order(Letter, ID),
                                c("Letter", "ID", "Col1", "Col2", "C1", "C2")]),
                  row.names = NULL)
</code>```

Output

```<code>mdf

#    Letter ID  Col1   Col2 C1 C2
# 1       A 23  blue  green  0  1
# 2       A 23  blue yellow  0  0
# 3       A 23 green yellow  1  0
# 4       B 57  blue  green  1  1
# 5       B 57 green yellow  1  0
# 6       B 57  blue yellow  1  0
# 7       C 48  blue  green  1  1
# 8       C 48 green yellow  1  1
# 9       C 48  blue yellow  1  1
# 10      D  3  blue  green  0  0
# 11      D  3 green yellow  0  0
# 12      D  3  blue yellow  0  0
# 13      E 12  blue  green  1  0
# 14      E 12  blue yellow  1  1
# 15      E 12 green yellow  0  1
</code>```

The known bottleneck is possibly the base::reshape for very large data frames. Here is a faster function using matrix manipulation:

```<code>matrix_melt <- function(df1, key, indName, valName) {
  value_cols <- names(df1)[ !(names(df1) %in% key)]
  mat_inds <- matrix(matrix(value_cols, nrow=nrow(df1), ncol=ncol(df1)-2, byrow=TRUE), ncol=1)
  mat_vals <- matrix(df1[value_cols], ncol= 1, byrow = TRUE)

  df2 <- setNames(data.frame(df1[key], unlist(mat_inds), unlist(mat_vals),
                             row.names = NULL, stringsAsFactors = FALSE),
                  c(key, indName, valName))
  return(df2)
}

rdf <- matrix_melt(df, c("Letter", "ID"), "Col1", "C")
rdf
</code>```

OwnerDisplayName: Bruna Amaral

Body:
I have this data.frame in R:

df = data.frame("blue" = c(0,1,1,0,1),
                "yellow" = c(0,0,1,0,1),
                "green" = c(1,1,1,0,0),
                "letter" = c("A","B","C","D","E"),
                "id" = c(23,57,48,3,12))

  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12

and would like to turn it into a data frame with all possible combinations of colors (colnames to rows), maintaining the Letter and ID of each pair, like in here:

   Col_1    Col_2    C1  C2  Letter  ID
1  blue     yellow   0   0   A       23
2  blue     green    0   1   A       23
3  yellow   green    0   1   A       23
4  blue     yellow   1   0   B       57
5  blue     green    1   1   B       57
6  yellow   green    0   1   B       57
7  blue     yellow   1   1   C       48
8  blue     green    1   1   C       48
9  yellow   green    1   1   C       48
10 blue     yellow   0   1   D       3
11 blue     green    0   0   D       3
12 yellow   green    1   0   D       3
13 blue     yellow   1   1   E       12
14 blue     green    1   0   E       12
15 yellow   green    1   0   E       12

Since my database is huge doing so with loops is taking too long. Any suggestions to do it more efficiently?

Thank you.

Body:
Consider following base solution to dynamically fit any needed set of values:

Data

txt <- '  blue yellow green Letter ID
1    0      0     1      A 23
2    1      0     1      B 57
3    1      1     1      C 48
4    0      0     0      D  3
5    1      1     0      E 12'

df <- read.table(text = txt, header=TRUE)

Solution

# DEFINE VECTOR OF VALUES
vals <- c("blue", "yellow", "green")

# RESHAPE DATA LONG
rdf <- reshape(df, idvar = c("Letter", "ID"),
               varying = vals, times = vals,
               v.names = "C", timevar = "Col1", ids = NULL,
               new.row.names = 1:1E4, direction = "long")

# HELPER DF FOR ALL POSSIBLE COMBNS (AVOID REVERSE DUPLICATES)
col_df <- subset(expand.grid(Col1 = vals, Col2 = vals,
                             stringsAsFactors = FALSE),
                 Col1 < Col2)

# MERGE TWICE FOR EACH SET OF COLs
mdf <- merge(merge(rdf, col_df, by.x="Col1", by.y="Col1"), rdf,
             by.x=c("Letter", "ID", "Col2"),
             by.y=c("Letter", "ID", "Col1"),
             suffixes = c(1, 2))

# RE-ORDER ROWS AND COLUMNS
mdf <- data.frame(with(mdf, mdf[order(Letter, ID),
                                c("Letter", "ID", "Col1", "Col2", "C1", "C2")]),
                  row.names = NULL)

Output

mdf

#    Letter ID  Col1   Col2 C1 C2
# 1       A 23  blue  green  0  1
# 2       A 23  blue yellow  0  0
# 3       A 23 green yellow  1  0
# 4       B 57  blue  green  1  1
# 5       B 57 green yellow  1  0
# 6       B 57  blue yellow  1  0
# 7       C 48  blue  green  1  1
# 8       C 48 green yellow  1  1
# 9       C 48  blue yellow  1  1
# 10      D  3  blue  green  0  0
# 11      D  3 green yellow  0  0
# 12      D  3  blue yellow  0  0
# 13      E 12  blue  green  1  0
# 14      E 12  blue yellow  1  1
# 15      E 12 green yellow  0  1

The known bottleneck is possibly the base::reshape for very large data frames. Here is a faster function using matrix manipulation:

matrix_melt <- function(df1, key, indName, valName) {
  value_cols <- names(df1)[ !(names(df1) %in% key)]
  mat_inds <- matrix(matrix(value_cols, nrow=nrow(df1), ncol=ncol(df1)-2, byrow=TRUE), ncol=1)
  mat_vals <- matrix(df1[value_cols], ncol= 1, byrow = TRUE)

  df2 <- setNames(data.frame(df1[key], unlist(mat_inds), unlist(mat_vals),
                             row.names = NULL, stringsAsFactors = FALSE),
                  c(key, indName, valName))
  return(df2)
}

rdf <- matrix_melt(df, c("Letter", "ID"), "Col1", "C")
rdf


问:
Graphical debugger for bash
Is it there any graphical debugger for bash on mac os x or linux? I mean something in the same fashion that the debugging mode of Visual Studio or Eclipse, where one can stop the program hover the mouse pointer over variables and get instantly values, modify them and go backwards and try modifications without the need to start the program fomr the beginning. I am talking about very long bash scripts</p>

答:
for debugging execute your script with:

```<code>bash -x <scriptname>
</code>```

gui debugger:
http://bashdb.sourceforge.net/

ContentLicense: CC BY-SA 3.0

Title: Graphical debugger for bash

Body:
for debugging execute your script with:

bash -x <scriptname>

gui debugger:
http://bashdb.sourceforge.net/


问:
how to I make my footer responsive without glitching?
So im pretty happy with my footer now and its fairly responsive. The Problem: its pretty glitchy. When resizing the window, the text and the links will stack on each other and so on. Can someone help me to fix this? I would love if the middle links would stay side by side and also the social media links to stay in a block.

thank you so much.

.footer {
 position: static;
 flex-shrink: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0px;
    width: 100%;
    background-color: #F9F9F9;
    text-align: center;
 box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
 z-index: 99;
    /*outline: 2px dashed orange;*/
}
.footerline {
 padding: 50px;
    display: flex;
    font-family: 'Source Code Pro', monospace;
    font-style: normal;
    font-weight: 400;
    font-size: 15px;
    color: #D5D5D5;
    justify-content: center;
    align-items: center;
    /*outline: 2px dashed orange;*/
}
#footerlineshadow {
 color: rgba(240,240,240, 0.9);
    text-shadow: 1px 1px 1px #fff, 0 0 0 #000, 1px 1px 1px #fff;
}
.subfooter {
    height: 40px;
    background-color: #E5E5E5;
    box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footercontent {
    display: flex;
    font-family: lato;
    color: #ABABAB;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    text-align: center;
    justify-content: center;
    height: 100%;
}
#footertext {
 text-align: center;
 margin-right: 20%;
 /*outline: 2px dashed orange;*/
}
#footerlinks {
 text-align: center;
 /*outline: 2px dashed orange;*/

}
#footerlinks a {
    margin: 0px 40px;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    color: #ABABAB;
    text-decoration: none; /*outline: 2px dashed orange;*/
}
#footerlinks a:hover {
 opacity: 0.7;
 font-style: normal;
    font-weight: 100;
    font-size: 12px;
 text-decoration: none;
 /*outline: 2px dashed orange;*/
}
#footersocialmedia {
 margin-left: 20%;
}
 /* Style all font awesome icons */
.fa {
  padding: 5px;
  font-size: 30px;
  width: 25px;
 height: 100%;
  text-align: center;
  text-decoration: none;
}

/* Add a hover effect if you want */
.fa:hover {
  opacity: 0.7;
}

/* Set a specific color for each brand */

/* Facebook */
.fa-facebook {
  background: #3B5998;
  color: white;
}

/* Twitter */
.fa-twitter {
  background: #55ACEE;
  color: white;
}
.fa-youtube {
  background: #bb0000;
  color: white;
}

.fa-instagram {
  background: #125688;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" id="applicationStylesheet" href="header_footer.css"/>
<link rel="stylesheet" type="text/css" id="mainStylesheet" href="kontakt.css"/>
<link href="http://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<footer class="footer">
   <div class="footerline">
     <p id="footerlineshadow">&ltp&gtThis is a Footer&lt/p&gt</p>
      </div>
 <div class="subfooter">
  <div class="footercontent">
   <div id="footertext">
    <p>Copyright © 2020 Henning Frenzel</p>
   </div>

   <div id="footerlinks">
    <p>
    Home
    Über Mich
         Portfolio
         Kontakt
    Impressum
    </p>
   </div>
   <div id="footersocialmedia">

   </div>
  </div>
 </div>
</footer>
</html></code>```

答:
And if you want to stay footer at the bottom use write these code to footer attribute in css

**position:absolute;

bottom:0;

left:0;

**

Body:
So im pretty happy with my footer now and its fairly responsive. The Problem: its pretty glitchy. When resizing the window, the text and the links will stack on each other and so on. Can someone help me to fix this? I would love if the middle links would stay side by side and also the social media links to stay in a block.

thank you so much.

.footer {
 position: static;
 flex-shrink: 0;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 0px;
    width: 100%;
    background-color: #F9F9F9;
    text-align: center;
 box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
 z-index: 99;
    /*outline: 2px dashed orange;*/
}
.footerline {
 padding: 50px;
    display: flex;
    font-family: 'Source Code Pro', monospace;
    font-style: normal;
    font-weight: 400;
    font-size: 15px;
    color: #D5D5D5;
    justify-content: center;
    align-items: center;
    /*outline: 2px dashed orange;*/
}
#footerlineshadow {
 color: rgba(240,240,240, 0.9);
    text-shadow: 1px 1px 1px #fff, 0 0 0 #000, 1px 1px 1px #fff;
}
.subfooter {
    height: 40px;
    background-color: #E5E5E5;
    box-shadow: inset 0 4px 5px 0 rgba(0, 0, 0, 0.2);
}
.footercontent {
    display: flex;
    font-family: lato;
    color: #ABABAB;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    text-align: center;
    justify-content: center;
    height: 100%;
}
#footertext {
 text-align: center;
 margin-right: 20%;
 /*outline: 2px dashed orange;*/
}
#footerlinks {
 text-align: center;
 /*outline: 2px dashed orange;*/

}
#footerlinks a {
    margin: 0px 40px;
    font-style: normal;
    font-weight: 100;
    font-size: 12px;
    color: #ABABAB;
    text-decoration: none; /*outline: 2px dashed orange;*/
}
#footerlinks a:hover {
 opacity: 0.7;
 font-style: normal;
    font-weight: 100;
    font-size: 12px;
 text-decoration: none;
 /*outline: 2px dashed orange;*/
}
#footersocialmedia {
 margin-left: 20%;
}
 /* Style all font awesome icons */
.fa {
  padding: 5px;
  font-size: 30px;
  width: 25px;
 height: 100%;
  text-align: center;
  text-decoration: none;
}

/* Add a hover effect if you want */
.fa:hover {
  opacity: 0.7;
}

/* Set a specific color for each brand */

/* Facebook */
.fa-facebook {
  background: #3B5998;
  color: white;
}

/* Twitter */
.fa-twitter {
  background: #55ACEE;
  color: white;
}
.fa-youtube {
  background: #bb0000;
  color: white;
}

.fa-instagram {
  background: #125688;
  color: white;
}

<link rel="stylesheet" type="text/css" id="applicationStylesheet" href="header_footer.css"/>
<link rel="stylesheet" type="text/css" id="mainStylesheet" href="kontakt.css"/>
<link href="http://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

&ltp&gtThis is a Footer&lt/p&gt

Copyright © 2020 Henning Frenzel

    Home
    Über Mich
         Portfolio
         Kontakt
    Impressum


问:
Remove first line from txt file using python3
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

```<code>file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)
</code>```

答:
You can do this:

```<code>F=open("file.text")
R=F.readlines()
Length=len(R)
New_file=R[1:Length-1]
for i in New_file:
    F.writelines(i)
F.close()
</code>```

Also visit This

Body:
So I have this code that writes the ping results to a txt file but its skipps the first line which means the file always gets an empty first line.

how can I remove it?
or even better, how can i print directly to the first line?

file = fr'c:/users/{os.getlogin()}/Desktop/default.txt'
with open(file, 'w+') as output:
    sub.call(['ping', f'{host}'], stdout=output)

Body:
You can do this:

F=open("file.text")
R=F.readlines()
Length=len(R)
New_file=R[1:Length-1]
for i in New_file:
    F.writelines(i)
F.close()

Also visit This


问:
Only take first value from loop GOLANG
Does anyone know why it took first value when I call variable inside the loop ? I want to make palindrome but the code just like this, can someone explain me. I'm new in GO</p>

```<code>    package main

    import "fmt"

    func main() {
        var kata, kosong, kebalikan, katanya string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata) - 1
    for i := panjang; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(kebalikan)
    }
    fmt.Print("\n")
    for i := 0; i <= panjang; i++ {
        katanya = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(katanya)
    }
    fmt.Println(katanya)
    fmt.Println(kebalikan)
    if fmt.Sprint(katanya) == fmt.Sprint(kebalikan) {
        fmt.Println(true)
    } else {
        fmt.Println(false)
    }

}
</code>```

答: You have your greater than and less than symbols the wrong way around. i >= 0 checks for when I is greater than or equal to 0, which it will be from the start because you're setting i to the length of that string.

Title: Only take first value from loop GOLANG

Body:
Does anyone know why it took first value when I call variable inside the loop ? I want to make palindrome but the code just like this, can someone explain me. I'm new in GO

    package main

    import "fmt"

    func main() {
        var kata, kosong, kebalikan, katanya string

    fmt.Print("Kata :")
    fmt.Scan(&kata)
    panjang := len(kata) - 1
    for i := panjang; i >= 0; i-- {
        kebalikan = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(kebalikan)
    }
    fmt.Print("\n")
    for i := 0; i <= panjang; i++ {
        katanya = kosong + fmt.Sprint(string(kata[i]))
        fmt.Print(katanya)
    }
    fmt.Println(katanya)
    fmt.Println(kebalikan)
    if fmt.Sprint(katanya) == fmt.Sprint(kebalikan) {
        fmt.Println(true)
    } else {
        fmt.Println(false)
    }

}


问:
Is there a function in R that splits a matrix along a margin using a factor or categorical vector?
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

```<code>m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)
</code>```

split doesn't seem to work with matrices so we could convert it into a data.frame:

```<code>split(data.frame(m), f = g)
</code>```

This works but I'd like to keep it as a matrix. The following loop works:

```<code>lapply(groups, function(x) m[g == x,])
</code>```

But is there a dedicated function, or a better way?

答:
Here is a way to split a matrix using lapply/split.

```<code>lapply(split(m, g), matrix, ncol = ncol(m))
</code>```

This can easily be written as a one-line function but I prefer a version with some error check.

```<code>mat_split <- function(x, f) {
  stopifnot(nrow(x) == length(f))
  lapply(split(x, f), matrix, ncol = ncol(x))
}
</code>```

Edit

The original question is (my emphasis):

But is there a dedicated function, or a better way?

Following this comment by user20650 there is a function or, better said, a method.

The split.data.frame method can solve the problem.

```<code>split.data.frame(m, g)
</code>```

And this is written in the documentation. From help('split') (my emphasis).

split and split<- are generic functions with default and data.frame
  methods. The data frame method can also be used to split a matrix into
  a list of matrices, and the replacement form likewise, provided they
  are invoked explicitly.

Body:
I am trying to split a matrix in the same way that you might split a data.frame using split. Is there a function that does that? For example, I have matrix m and I am trying to split it into a list of matrices using vector g.

m <- matrix(rnorm(50), ncol = 5)
groups <- c('A', 'B', 'C')
g <- sample(groups, 10, replace = T)

split doesn't seem to work with matrices so we could convert it into a data.frame:

split(data.frame(m), f = g)

This works but I'd like to keep it as a matrix. The following loop works:

lapply(groups, function(x) m[g == x,])

But is there a dedicated function, or a better way?

Body:
Here is a way to split a matrix using lapply/split.

lapply(split(m, g), matrix, ncol = ncol(m))

This can easily be written as a one-line function but I prefer a version with some error check.

mat_split <- function(x, f) {
  stopifnot(nrow(x) == length(f))
  lapply(split(x, f), matrix, ncol = ncol(x))
}

Edit

The original question is (my emphasis):

But is there a dedicated function, or a better way?

Following this comment by user20650 there is a function or, better said, a method.

The split.data.frame method can solve the problem.

split.data.frame(m, g)

And this is written in the documentation. From help('split') (my emphasis).

split and split<- are generic functions with default and data.frame
  methods. The data frame method can also be used to split a matrix into
  a list of matrices, and the replacement form likewise, provided they
  are invoked explicitly.


问:
Align Button To The center Of the window using pysimplegui
In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window.

The code am working with is

```<code>import PySimpleGUI as sg
from tkinter import *
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center')],
        [sg.Input(justification='center')],
        [sg.Button('Enter','center')]
     ]

  window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

 while True:
event, values = window.read()   # Read the event that happened and the values dictionary
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
    break
if event == 'Button':
  print('You pressed the button')
window.close()
</code>```

The above code outputs

How can i make the text,button and input to the center of the window?

答:
I think this is what you're looking for

window = sg.Window('My new window', layout, element_justification='c')
```
<hr />
<p>Edit - Centering vertically (SEE MARCH 2022 edit below for a BETTER solution)</p>
<p>Centering a layout vertically in a window is quite a bit bigger of a chore.  What's required are 2 elements that will expand when the window expands.  This is a demo program that is part of the Demos on the PySimpleGUI GitHub</p>
<pre class="lang-py prettyprint-override"><code>import PySimpleGUI as sg

"""
    Center a column in a window
    Solves a very specific kind of layout.
    If you want to have something centered in a Window, this is a good way to do it
    The "trick" here is:
        * the first row of the layout has a Text element that expands vertically
        * the row with the Column has a text element that expands horizontally

    This expanding Text element is what will cause the Column element to be centered

    Used with permission
"""

def main():
    column_to_be_centered = [  [sg.Text('My Window')],
                [sg.Input(key='-IN-')],
                [sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]  ]

    layout = [[sg.Text(key='-EXPAND-', font='ANY 1', pad=(0, 0))],  # the thing that expands from top
              [sg.Text('', pad=(0,0),key='-EXPAND2-'),              # the thing that expands from left
               sg.Column(column_to_be_centered, vertical_alignment='center', justification='center',  k='-C-')]]

    window = sg.Window('Window Title', layout, resizable=True,finalize=True)
    window['-C-'].expand(True, True, True)
    window['-EXPAND-'].expand(True, True, True)
    window['-EXPAND2-'].expand(True, False, True)

    while True:             # Event Loop
        event, values = window.read()
        print(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event == 'Go':
            window['-OUT-'].update(values['-IN-'])
    window.close()

if __name__ == '__main__':
    main()
</code>```

Edit 18-Mar-2022

Like so many things in PySimpleGUI, operations like element justification are continually evolving.  The problem, again, with StackOverflow is that these answers are not typically updated.  It's why I suggest always using the GitHub Issues to ask questions and to check the Cookbook, eCookbook and Demo Programs to get the latest techniques.

Last year two new elements were introduced that make both horizontal and vertical justification trivial.  These elements are Push and VPush.  You'll find a recipe in the eCookbook.

These elements "push" other elements around.  Push moves them horizontally and VPush moves them vertically.

If you put a push on both sides of elements/rows, then those elements/rows will be centered.

Here's the same layout in the above example except using these Push and VPush elements.  This solution is much shorter & much easier to understand.

import PySimpleGUI as sg

def main():
    column_to_be_centered = [  [sg.Text('My Window')],
                [sg.Input(key='-IN-')],
                [sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]]

    layout = [[sg.VPush()],
              [sg.Push(), sg.Column(column_to_be_centered,element_justification='c'), sg.Push()],
              [sg.VPush()]]

    window = sg.Window('Window Title', layout, size=(500,300))

    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Exit':
            break

    window.close()

if __name__ == '__main__':
    main()
```

Body:
In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window.

The code am working with is

import PySimpleGUI as sg
from tkinter import *
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center')],
        [sg.Input(justification='center')],
        [sg.Button('Enter','center')]
     ]

  window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

 while True:
event, values = window.read()   # Read the event that happened and the values dictionary
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
    break
if event == 'Button':
  print('You pressed the button')
window.close()

The above code outputs

How can i make the text,button and input to the center of the window?

Body:
I think this is what you're looking for

window = sg.Window('My new window', layout, element_justification='c')

Edit - Centering vertically (SEE MARCH 2022 edit below for a BETTER solution)

Centering a layout vertically in a window is quite a bit bigger of a chore.  What's required are 2 elements that will expand when the window expands.  This is a demo program that is part of the Demos on the PySimpleGUI GitHub

import PySimpleGUI as sg

"""
    Center a column in a window
    Solves a very specific kind of layout.
    If you want to have something centered in a Window, this is a good way to do it
    The "trick" here is:
        * the first row of the layout has a Text element that expands vertically
        * the row with the Column has a text element that expands horizontally

    This expanding Text element is what will cause the Column element to be centered

    Used with permission
"""

def main():
    column_to_be_centered = [  [sg.Text('My Window')],
                [sg.Input(key='-IN-')],
                [sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]  ]

    layout = [[sg.Text(key='-EXPAND-', font='ANY 1', pad=(0, 0))],  # the thing that expands from top
              [sg.Text('', pad=(0,0),key='-EXPAND2-'),              # the thing that expands from left
               sg.Column(column_to_be_centered, vertical_alignment='center', justification='center',  k='-C-')]]

    window = sg.Window('Window Title', layout, resizable=True,finalize=True)
    window['-C-'].expand(True, True, True)
    window['-EXPAND-'].expand(True, True, True)
    window['-EXPAND2-'].expand(True, False, True)

    while True:             # Event Loop
        event, values = window.read()
        print(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event == 'Go':
            window['-OUT-'].update(values['-IN-'])
    window.close()

if __name__ == '__main__':
    main()

Edit 18-Mar-2022

Like so many things in PySimpleGUI, operations like element justification are continually evolving.  The problem, again, with StackOverflow is that these answers are not typically updated.  It's why I suggest always using the GitHub Issues to ask questions and to check the Cookbook, eCookbook and Demo Programs to get the latest techniques.

Last year two new elements were introduced that make both horizontal and vertical justification trivial.  These elements are Push and VPush.  You'll find a recipe in the eCookbook.

These elements "push" other elements around.  Push moves them horizontally and VPush moves them vertically.

If you put a push on both sides of elements/rows, then those elements/rows will be centered.

Here's the same layout in the above example except using these Push and VPush elements.  This solution is much shorter & much easier to understand.

import PySimpleGUI as sg

def main():
    column_to_be_centered = [  [sg.Text('My Window')],
                [sg.Input(key='-IN-')],
                [sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]]

    layout = [[sg.VPush()],
              [sg.Push(), sg.Column(column_to_be_centered,element_justification='c'), sg.Push()],
              [sg.VPush()]]

    window = sg.Window('Window Title', layout, size=(500,300))

    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == 'Exit':
            break

    window.close()

if __name__ == '__main__':
    main()


问:
Why is NetworkStream.ReadAsync not timing out?
I am using NetworkStream with TcpClient.

First I setup my tcp client:

```<code>    tcp = new TcpClient(AddressFamily.InterNetwork)
    { NoDelay = true, ReceiveTimeout = 5000};
</code>```

My main data-receiving loop:

```<code>    while (true)
    {
        //read available data from the device
        int numBytesRead = await ReadAsync();
        Console.WriteLine($"{numBytesRead} bytes read"); //BP2
    }
</code>```

And the actual TCP data reading:

```<code>public Task<int> ReadAsync()
{
    var stream = tcp.GetStream();
    return stream.ReadAsync(InBuffer, 0, InBuffer.Length); //BP1
}
</code>```

I have this connected to a testbed which lets me send manual packets. Through setting breakpoints and debugging I have checked that stream.ReadTimeout takes the value 5000 from tcp.

If I send data frequently it all works as expected. But if I don't send any data, nothing appears to happen after 5s, no timeout. I see breakpoint BP1 being hit in the debugger but until I send data from my testbed, BP2 is not hit. I can leave it a minute or more and it just seems to sit waiting, but receives data sent after a minute, which appears to be incorrect behavior. After 5 seconds something should happen, surely (an exception as I understand it)?

It's late so I am expecting something really basic but can anyone see what my mistake is and a resolution?

Addendum

OK so when I RTFM for the actual .Net version I'm using (how may times have I been caught out by MS defaulting to .Net Core 3, I did say it was late) I see in the remarks sectio for ReadTimeout:

This property affects only synchronous reads performed by calling the
  Read method. This property does not affect asynchronous reads
  performed by calling the BeginRead method.

I'm unclear now if I can use modern awaitable calls at all to read socket data safely and with a timeout specifically. It's working except for the timeout but I'm not sure how given ReadAsync has no override in NetworkStream. Must I do some ugly hack or is there a simple solution?

In my case 5000 is the longest I can expect not to receive data before concluding there is a problem - the protocol has no ping mechanism so if nothing appears I assume the connection is dead. Hence thinking an Async read with a 5000ms timeout would be nice and neat.

答:
Timeout values for network objects apply only to synchronous operations. For example, from the documentation:

This option applies to synchronous Receive calls only.

For Socket.ReceiveTimeout, TcpClient.ReceiveTimeout, and NetworkStream.ReadTimeout, the implementations all ultimately result in a call to SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, ...) which in turn is effectively calling the native setsockopt() function. From that documentation:

SO_RCVTIMEO  DWORD Sets the timeout, in milliseconds, for blocking receive calls.

(emphasis mine)

It's this limitation in the underlying native API that is the reason for the same limitation in the managed API. Timeout values will not apply to asynchronous I/O on the network objects.

You will need to implement the timeout yourself, by closing the socket if and when the timeout should occur. For example:

async Task<int> ReadAsync(TcpClient client, byte[] buffer, int index, int length, TimeSpan timeout)
{
    Task<int> result = client.GetStream().ReadAsync(buffer, index, length);

    await Task.WhenAny(result, Task.Delay(timeout));

    if (!result.IsCompleted)
    {
        client.Close();
    }

    return await result;
}
```

Other variations on this theme can be found in other related questions:

NetworkStream.ReadAsync with a cancellation token never cancels

Cancel C# 4.5 TcpClient ReadAsync by timeout

Closing the socket is really all that you can do. Even for synchronous operations, if a timeout occurs the socket would no longer be usable. There is no reliable way to interrupt a read operation and expect the socket to remain consistent.

Of course, you do have the option of prompting the user before closing the socket. However, if you were to do that, you would implement the timeout at a higher level in your application architecture, such that the I/O operations themselves have no awareness of timeouts at all.

Body:
I am using NetworkStream with TcpClient.

First I setup my tcp client:

    tcp = new TcpClient(AddressFamily.InterNetwork)
    { NoDelay = true, ReceiveTimeout = 5000};

My main data-receiving loop:

    while (true)
    {
        //read available data from the device
        int numBytesRead = await ReadAsync();
        Console.WriteLine($"{numBytesRead} bytes read"); //BP2
    }

And the actual TCP data reading:

public Task<int> ReadAsync()
{
    var stream = tcp.GetStream();
    return stream.ReadAsync(InBuffer, 0, InBuffer.Length); //BP1
}

I have this connected to a testbed which lets me send manual packets. Through setting breakpoints and debugging I have checked that stream.ReadTimeout takes the value 5000 from tcp.

If I send data frequently it all works as expected. But if I don't send any data, nothing appears to happen after 5s, no timeout. I see breakpoint BP1 being hit in the debugger but until I send data from my testbed, BP2 is not hit. I can leave it a minute or more and it just seems to sit waiting, but receives data sent after a minute, which appears to be incorrect behavior. After 5 seconds something should happen, surely (an exception as I understand it)?

It's late so I am expecting something really basic but can anyone see what my mistake is and a resolution?

Addendum

OK so when I RTFM for the actual .Net version I'm using (how may times have I been caught out by MS defaulting to .Net Core 3, I did say it was late) I see in the remarks sectio for ReadTimeout:

This property affects only synchronous reads performed by calling the
  Read method. This property does not affect asynchronous reads
  performed by calling the BeginRead method.

I'm unclear now if I can use modern awaitable calls at all to read socket data safely and with a timeout specifically. It's working except for the timeout but I'm not sure how given ReadAsync has no override in NetworkStream. Must I do some ugly hack or is there a simple solution?

In my case 5000 is the longest I can expect not to receive data before concluding there is a problem - the protocol has no ping mechanism so if nothing appears I assume the connection is dead. Hence thinking an Async read with a 5000ms timeout would be nice and neat.

Body:
Timeout values for network objects apply only to synchronous operations. For example, from the documentation:

This option applies to synchronous Receive calls only.

For Socket.ReceiveTimeout, TcpClient.ReceiveTimeout, and NetworkStream.ReadTimeout, the implementations all ultimately result in a call to SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, ...) which in turn is effectively calling the native setsockopt() function. From that documentation:

SO_RCVTIMEO  DWORD Sets the timeout, in milliseconds, for blocking receive calls.

(emphasis mine)

It's this limitation in the underlying native API that is the reason for the same limitation in the managed API. Timeout values will not apply to asynchronous I/O on the network objects.

You will need to implement the timeout yourself, by closing the socket if and when the timeout should occur. For example:

async Task<int> ReadAsync(TcpClient client, byte[] buffer, int index, int length, TimeSpan timeout)
{
    Task<int> result = client.GetStream().ReadAsync(buffer, index, length);

    await Task.WhenAny(result, Task.Delay(timeout));

    if (!result.IsCompleted)
    {
        client.Close();
    }

    return await result;
}

Other variations on this theme can be found in other related questions:

NetworkStream.ReadAsync with a cancellation token never cancels

Cancel C# 4.5 TcpClient ReadAsync by timeout

Closing the socket is really all that you can do. Even for synchronous operations, if a timeout occurs the socket would no longer be usable. There is no reliable way to interrupt a read operation and expect the socket to remain consistent.

Of course, you do have the option of prompting the user before closing the socket. However, if you were to do that, you would implement the timeout at a higher level in your application architecture, such that the I/O operations themselves have no awareness of timeouts at all.


问:
SVM duality: set of hyperparameters not supported
I am trying to train a SVM model on the Iris dataset. The aim is to classify Iris virginica flowers from other types of flowers. Here is the code:

```<code>import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

iris = datasets.load_iris()
X = iris["data"][:, (2,3)] # petal length, petal width
y = (iris["target"]==2).astype(np.float64) # Iris virginica

svm_clf = Pipeline([
    ("scaler", StandardScaler()),
    ("linear_svc", LinearSVC(C=1, loss="hinge", dual=False))
])

svm_clf.fit(X,y)
</code>```

My book, which is Aurelien Geron's "Hands-On Machine Learning with Scikit-Learn , Keras and TensorFlow", 2nd edition, at page 156 says:

For better performance, you should set the dual hyperparameter to
  False, unless there are more features than training instances

But If I set the dual hyperparameter to False, I get the following error:

```<code>ValueError: Unsupported set of arguments: The combination of penalty='l2' and loss='hinge' are not supported when dual=False, Parameters: penalty='l2', loss='hinge', dual=False
</code>```

It instead works if I set the dual hyperparameter to True.

Why is this set of hyperparameters not supported?

答:
L2 SVM with L1 loss (hinge) cannot be solving in the primal form. Only its dual form can be solved effectively. This is due to the limitation of the LIBLINEAR library used by sklearn. If you want to solve the primal form of the L2 SVM you will have to use L2 loss (squared hinge) instead.

```<code>LinearSVC(C=1, loss='squared_hinge', dual=False).fit(X,y)
</code>```

For mode details: Link 1

Body:
I am trying to train a SVM model on the Iris dataset. The aim is to classify Iris virginica flowers from other types of flowers. Here is the code:

import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

iris = datasets.load_iris()
X = iris["data"][:, (2,3)] # petal length, petal width
y = (iris["target"]==2).astype(np.float64) # Iris virginica

svm_clf = Pipeline([
    ("scaler", StandardScaler()),
    ("linear_svc", LinearSVC(C=1, loss="hinge", dual=False))
])

svm_clf.fit(X,y)

My book, which is Aurelien Geron's "Hands-On Machine Learning with Scikit-Learn , Keras and TensorFlow", 2nd edition, at page 156 says:

For better performance, you should set the dual hyperparameter to
  False, unless there are more features than training instances

But If I set the dual hyperparameter to False, I get the following error:

ValueError: Unsupported set of arguments: The combination of penalty='l2' and loss='hinge' are not supported when dual=False, Parameters: penalty='l2', loss='hinge', dual=False

It instead works if I set the dual hyperparameter to True.

Why is this set of hyperparameters not supported?

Body:
L2 SVM with L1 loss (hinge) cannot be solving in the primal form. Only its dual form can be solved effectively. This is due to the limitation of the LIBLINEAR library used by sklearn. If you want to solve the primal form of the L2 SVM you will have to use L2 loss (squared hinge) instead.

LinearSVC(C=1, loss='squared_hinge', dual=False).fit(X,y)

For mode details: Link 1


问:
unset form submit button
```<code><body>

<?php

if(isset($_POST['vendor_add_submit'])){

//INSERT INTO DB

unset(  $_POST['vendor_add_submit'] );
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" >

<label>Email</label>
<input type="text" name="vendor_email" value="" />

<input type="submit" name="vendor_add_submit" value="SAVE" />

</form>
</body>
</code>```

unset(  $_POST['vendor_add_submit'] ); is used to prevent more than one time insertion into db on page refresh. I tested with print_r($_POST['vendor_add_submit'] ) before and after the unset and found that the unset() function does not work.

How can I achieve the purpose of the unset function, plz?

答:
The $_POST value will only be removed on the Server-Side Meaning that on that one request PHP will not be able to see or use it (You removed it).

But you are rendering the Submit button on the page's HTML so every time someone visits the page and submit the form they will submit the value again. And you will remove it again for PHP on that current request. So every request would insert the data into the database.

You might want to rather look into rather checking if the record already does exists (OR if the user has one already, not sure what you want) and then redirect them away from the page using header('Location: otherpage.php');.

Hope that helps...

Title: unset form submit button

Body:
<?php

if(isset($_POST['vendor_add_submit'])){

//INSERT INTO DB

unset(  $_POST['vendor_add_submit'] );
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" >

Email
<input type="text" name="vendor_email" value="" />

<input type="submit" name="vendor_add_submit" value="SAVE" />

</form>

unset(  $_POST['vendor_add_submit'] ); is used to prevent more than one time insertion into db on page refresh. I tested with print_r($_POST['vendor_add_submit'] ) before and after the unset and found that the unset() function does not work.

How can I achieve the purpose of the unset function, plz?


问:
How to center image horizontally within a div element?
How can I center align (horizontally) an image inside its container div?

Here's the HTML and CSS. I have also included the CSS for the other elements of the thumbnail. It runs in descending order so the highest element is the container of everything and the lowest is inside everything.

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}

#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}

#artiststhumbnail:hover {
      left: 50px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--link here-->

  <div id="thumbnailwrapper">

    href="NotByDesign">

      <!--name here-->
      <b>Not By Design</b>
      <br>

      <div id="artiststhumbnail">

        href="NotByDesign">

          <!--image here-->
          <img src="../files/noprofile.jpg" height="100%" alt="Not By Design" border="1" />

      </div>

      <div id="genre">Punk</div>

  </div></code>```

Okay, I have added the markup without the PHP in so should be easier to see. Neither solution seems to work in practice. The text at top and bottom cannot be centered and the image should be centered within its container div. The container has overflow hidden so I want to see the center of the image as that's normally where the focus is.

答:
A responsive way to center an image can be like this:</p>

```<code>.center {
    display: block;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
}
</code>```

Body:
How can I center align (horizontally) an image inside its container div?

Here's the HTML and CSS. I have also included the CSS for the other elements of the thumbnail. It runs in descending order so the highest element is the container of everything and the lowest is inside everything.

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}

#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}

#artiststhumbnail:hover {
      left: 50px
}

      Not By Design

Punk

Okay, I have added the markup without the PHP in so should be easier to see. Neither solution seems to work in practice. The text at top and bottom cannot be centered and the image should be centered within its container div. The container has overflow hidden so I want to see the center of the image as that's normally where the focus is.

Body:
A responsive way to center an image can be like this:

.center {
    display: block;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
}


问:
Change the position of button text and button icon
I have a button which contains an icon and some text.  I want this button to be reusable.  I also want to have the option of putting the icon left of the text or right of the text.  I am passing in a prop (either "right" or "left") which will then adjust the CSS.  Could anyone help me out with the CSS to swap the position of these two.

```<code>export const IconButton = ({icon,text, position}) => {
  return (
    <StyledIconButton className={position}>
      <img src={icon} />
      {text}
    </StyledIconButton>
  );
};
</code>```

The StyledIconButton has a few default styles, but nothing important.

I am trying to use float but haven't been successful.  Ideally I would avoid using flexbox as well.

```<code>.right {
   img {
    float: left;
    margin-right: 0.375rem;
  }
}
.left {
  img {
    float: right;
    margin-left: 1.5rem;
  }
}
</code>```

As requested I am adding in the styles for StyledIconButton:

```<code>.styledbutton {
  display: flex;
  font-size: 1rem;
  line-height: 2rem;
}
</code>```

The above code won't actually swap the position.

答:
I think using a flexbox and switching the direction would be the easiest way. You can learn about flexbox here.

But you can set left and right classes to decide on the direction of the flex.

```<code>.right {
   flex-direction: row-reverse;
}
.left {
  flex-direction: row;
}
</code>```

And you would have set spacing and all other required styles on text and img separately, but this should do the trick

Body:
I have a button which contains an icon and some text.  I want this button to be reusable.  I also want to have the option of putting the icon left of the text or right of the text.  I am passing in a prop (either "right" or "left") which will then adjust the CSS.  Could anyone help me out with the CSS to swap the position of these two.

export const IconButton = ({icon,text, position}) => {
  return (

  );
};

The StyledIconButton has a few default styles, but nothing important.

I am trying to use float but haven't been successful.  Ideally I would avoid using flexbox as well.

.right {
   img {
    float: left;
    margin-right: 0.375rem;
  }
}
.left {
  img {
    float: right;
    margin-left: 1.5rem;
  }
}

As requested I am adding in the styles for StyledIconButton:

.styledbutton {
  display: flex;
  font-size: 1rem;
  line-height: 2rem;
}

The above code won't actually swap the position.

Body:
I think using a flexbox and switching the direction would be the easiest way. You can learn about flexbox here.

But you can set left and right classes to decide on the direction of the flex.

.right {
   flex-direction: row-reverse;
}
.left {
  flex-direction: row;
}

And you would have set spacing and all other required styles on text and img separately, but this should do the trick


问:
Pass data from a Datagrid to a form and vice versa
I have a form called "FrmClientesEdicion" which has a postal code field, I am trying to open the postal code file and return to the first form the information selected in the second form from the datagrid. What happens is that with the code so far the info does not pass to me but rather it opens a new instance of the form "FrmClientesEdicion", help?

Open the postal code form "FrmCodigosPosAr" from a button in "FrmClientesEdicion" with this line:

```<code>    Dim f As New FrmCodigosPosAr
f.ShowDialog()
</code>```

Search in the form : "FrmCodigosPosAr" select a row and pass data (p.e Code, Name) again to the first one: "FrmClientesEdicion" with this lines:

```<code>Try
    Dim F As New FrmClienteEdicion
    With F
        .TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString ' The code
        .TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString ' The name city
        .TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString ' The state
    End With
Catch ex As Exception
    MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()
</code>```

This second point doesn't works open a new instance but don`t...
Thanks again
Note: The first form still open, never close it when I open the second one!
The pictures:

Open form 2
Then pass data from FORM2 to the FORM1 AGAIN

答:
I answer myself in case someone needs it

In form2 (FrmCodigosPosAr)

```<code>Public Class FrmCodigosPosAr
Inherits System.Windows.Forms.Form
Public myCaller As FrmClienteEdicion
</code>```

In form 1, (p.e in a Button to call form2 (FrmCodigosPosAr))

```<code>    Dim myform As FrmCodigosPosAr
Private Sub BtnBuscaCP_Click(sender As Object, e As EventArgs) Handles BtnBuscaCP.Click
If myform Is Nothing Then
    myform = New FrmCodigosPosAr
    myform.myCaller = Me
End If
myform.Show()
</code>```

End Sub

And in the form 2 (FrmCodigosPosAr) to pass data to Form1 (FrmClientesEdicion)

```<code>    Try
    If Not myCaller Is Nothing Then
        myCaller.Text = Now.ToLongTimeString
        myCaller.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString
        myCaller.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString
        myCaller.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString
    End If
Catch ex As Exception
    MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()
</code>```

Body:
I have a form called "FrmClientesEdicion" which has a postal code field, I am trying to open the postal code file and return to the first form the information selected in the second form from the datagrid. What happens is that with the code so far the info does not pass to me but rather it opens a new instance of the form "FrmClientesEdicion", help?

Open the postal code form "FrmCodigosPosAr" from a button in "FrmClientesEdicion" with this line:

    Dim f As New FrmCodigosPosAr
f.ShowDialog()

Search in the form : "FrmCodigosPosAr" select a row and pass data (p.e Code, Name) again to the first one: "FrmClientesEdicion" with this lines:

Try
    Dim F As New FrmClienteEdicion
    With F
        .TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString ' The code
        .TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString ' The name city
        .TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString ' The state
    End With
Catch ex As Exception
    MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()

This second point doesn't works open a new instance but don`t...
Thanks again
Note: The first form still open, never close it when I open the second one!
The pictures:

Open form 2
Then pass data from FORM2 to the FORM1 AGAIN

Body:
I answer myself in case someone needs it

In form2 (FrmCodigosPosAr)

Public Class FrmCodigosPosAr
Inherits System.Windows.Forms.Form
Public myCaller As FrmClienteEdicion

In form 1, (p.e in a Button to call form2 (FrmCodigosPosAr))

    Dim myform As FrmCodigosPosAr
Private Sub BtnBuscaCP_Click(sender As Object, e As EventArgs) Handles BtnBuscaCP.Click
If myform Is Nothing Then
    myform = New FrmCodigosPosAr
    myform.myCaller = Me
End If
myform.Show()

End Sub

And in the form 2 (FrmCodigosPosAr) to pass data to Form1 (FrmClientesEdicion)

    Try
    If Not myCaller Is Nothing Then
        myCaller.Text = Now.ToLongTimeString
        myCaller.TxtCPOCLI.Text = DG.CurrentRow.Cells(0).Value.ToString
        myCaller.TxtPOBCLI.Text = DG.CurrentRow.Cells(1).Value.ToString
        myCaller.TxtPROCLI.Text = DG.CurrentRow.Cells(2).Value.ToString
    End If
Catch ex As Exception
    MsgBox("Verifique: " & ex.Message.ToString, MsgBoxStyle.Critical)
End Try
Me.Close()


问:
Bitnami Ghost CMS aws instance Config file is not valid JSON issue
I am setting up ghost cms on aws for a client and hit a wall. I am using the bitnami image for setting this up. I haven't touched the config file that comes default in bitnami image. Ghost is not starting up and it's showing this error in the log</p>

```<code>Debug Information:
OS: Debian GNU/Linux, v10
Node Version: v10.20.1
Ghost-CLI Version: 1.14.0
Environment: production
Command: 'ghost log'
An error occurred.
Message: 'Cannot read property 'join' of undefined'

Stack: TypeError: Cannot read property 'join' of undefined
    at instance.isRunning.then (/opt/bitnami/apps/ghost/lib/node_modules/ghost-cli/lib/commands/log.js:34:88)
    at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

答: OK it literally wasted hours of my life. And the problem was found. The reason was that in the config file the url of the blog was given as an IP address. But Ghost has said in it's setup documentation that this is likely to cause issues. So when I changed this to a URL instead of the IP address it was fixed. Hurraaay!!</p>

Body:
I am setting up ghost cms on aws for a client and hit a wall. I am using the bitnami image for setting this up. I haven't touched the config file that comes default in bitnami image. Ghost is not starting up and it's showing this error in the log

Debug Information:
OS: Debian GNU/Linux, v10
Node Version: v10.20.1
Ghost-CLI Version: 1.14.0
Environment: production
Command: 'ghost log'
An error occurred.
Message: 'Cannot read property 'join' of undefined'

Stack: TypeError: Cannot read property 'join' of undefined
    at instance.isRunning.then (/opt/bitnami/apps/ghost/lib/node_modules/ghost-cli/lib/commands/log.js:34:88)
    at process._tickCallback (internal/process/next_tick.js:68:7)


问:
Find the average of similar dataframe columns
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58
```

<p>for the repeated samples, <code>sample2.1</code> and <code>sample2.2</code>, I want to remain with an average of the two, i.e</p>

<pre class="lang-py prettyprint-override"><code>   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58
</code>```

I am thinking of using regex but I have never used them on python dataframes

Body:
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58

for the repeated samples, sample2.1 and sample2.2, I want to remain with an average of the two, i.e

   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58

I am thinking of using regex but I have never used them on python dataframes

Body:
I would do:

(df.T.groupby(df.columns.str.extract('^([^\.]+)')[0].values)
   .mean().T
)

Output:

    sample1  sample2  sample3  sample4
0     89.0     50.5     34.0     32.0
1    788.0     40.0     65.0     55.0
2    588.0     40.5      8.0     55.0
3     25.0     29.5    123.0     58.0


问:
How to execute task in Google App Engine
I am trying to execute task in one of  Google App Engine project automatically using Java.

To create task , i did following steps.

Step 1) Created one servlet by extending HTTPServlet with url pattern in
        web.xml is /task.

```<code>     I written following code inside doGet() of this servlet to add task
     to default queue.

      Queue q = QueueFactory.getDefaultQueue();
 q.add(TaskOptions.Builder.withUrl("/test").param("key", "123"));
</code>```

Step 2) Created one more servlet by extending HTTPServlet with url pattern in
        web.xml is /test.

```<code>    I written sent email code when this servlet is exceuted.
</code>```

So now,  I added task to queue with url test.

When my task will execute.

When i execute servlet with url pattern /task it is adding task to queue. But task is not executing.

How my task will execute automatically by Google App Engine.

Thanks.

答:
the task should execute.
go to your google app engine administration console and check your logs and task queues. it's either exceptions or task completed. if completed, it may not show up on the task queue (unless it finished within the past 1 min).

to verify that your task has been submitted successfully, you can try the following:

use the administration console and pause the task queue

submit your task to the task queue (by accessing the url e.g. http://your.appspot.com/task)

go to the administration console and check the task queue. Under the 'Tasks in Queue' column, you should see that the task is still pending.

Body:
I am trying to execute task in one of  Google App Engine project automatically using Java.

To create task , i did following steps.

Step 1) Created one servlet by extending HTTPServlet with url pattern in
        web.xml is /task.

     I written following code inside doGet() of this servlet to add task
     to default queue.

      Queue q = QueueFactory.getDefaultQueue();
 q.add(TaskOptions.Builder.withUrl("/test").param("key", "123"));

Step 2) Created one more servlet by extending HTTPServlet with url pattern in
        web.xml is /test.

    I written sent email code when this servlet is exceuted.

So now,  I added task to queue with url test.

When my task will execute.

When i execute servlet with url pattern /task it is adding task to queue. But task is not executing.

How my task will execute automatically by Google App Engine.

Thanks.


问:
How can i resolve error cannot import name style?
When i run this piece of code:

```<code>import matplotlib.pyplot as plt
import numpy as np
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()
</code>```

I get the following error message:

cannot import name 'style' from 'matplotlib'

Where is the bug?

答:
It could be the way you installed matplotlib. In some cases pip install matplotlib does not work. You would try the Windows installer from https://pypi.python.org/pypi/matplotlib.

If this doesn't work or it is not the case, use:

sudo pip install --upgrade matplotlib

or

pip install --user    --upgrade matplotlib

Make sure that the code is from matplotlib import style

Body:
When i run this piece of code:

import matplotlib.pyplot as plt
import numpy as np
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

I get the following error message:

cannot import name 'style' from 'matplotlib'

Where is the bug?


问:
Initialize a new static variable every loop, C++
There is a way in C++ to create a new static variable (with a different memeory address) in a loop for every iteration?

Here it is an example:

```<code>static vector<int *> vec;
for(int i=0; i<n; i++){ //n is a generic number
    static int var=i; //var should be a new static variable every loop
    vec.pushback(&var);
}
</code>```

The vector "vec" should contain all the different addresses of the newly created variables.

Thanks in advance

Edit 1:
This was only a simple example to summarize my problem;
my goal is to have a function that creates a new static variable every time it is called, then this variable should be modified and finally its address stored in a vector of pointers.

答:
What is a static variable?

In most operating systems the global variables and all static variables are placed into the program image in their own data section. If they have complicated initialization then those are run on program start, or protected with locks and set on first use.

The only difference between global and static variables is that the compiler will not allow your program to use a static variable that is outside the current scope. From an assembly language viewpoint, statics and globals are identical.

Since all globals and statics are created from the program image at startup, you cannot add more of them later.

If you want to use dynamic amounts of memory that grows over time, you need to use the heap. C++ has new T, new T[], delete and delete[] in order to handle that. The C++ standard containers use allocators, which in turn call new in special ways. Normally you don't worry about allocators and just use the containers.

Some fun details!

I made a little C file which I compiled into a .o all on its own, so it wouldn't get optimized away when combined with main. All main does is call f().

```<code>#include <stdio.h>

int global_0;
int global_1 = 1;
int global_2 = 2;

static int static_0;
static int static_3 = 3;
static int static_4 = 4;

int f() {
  static int static_func_0;
  static int static_func_5 = 5;

  printf("%p\n", (void *)&global_0);
  printf("%p\n", (void *)&global_1);
  printf("%p\n", (void *)&global_2);

  printf("%p\n", (void *)&static_0);
  printf("%p\n", (void *)&static_3);
  printf("%p\n", (void *)&static_4);

  printf("%p\n", (void *)&static_func_0);
  printf("%p\n", (void *)&static_func_5);

  return 0;
}
</code>```

And then a few inspections of the resulting program:

```<code>$ objdump -t ./global-static-test
[...snipped a bunch of junk...]
000000001002002c l     O .data  0000000000000004              global_1
0000000010020030 l     O .data  0000000000000004              global_2
0000000010020034 l     O .data  0000000000000004              static_3
0000000010020038 l     O .data  0000000000000004              static_4
000000001002003c l     O .data  0000000000000004              static_func_5.0
0000000010020044 l     O .bss   0000000000000004              global_0
0000000010020048 l     O .bss   0000000000000004              static_0
000000001002004c l     O .bss   0000000000000004              static_func_0.1
</code>```

So you can see that the globals, the file scope statics and the function statics are all huddled together in .data and .bss sections.

The reason for .bss is it is for all zero-initialized things. The program loader does not actually load .bss. Instead it just allocates some number of zero-filled memory pages. A global array of a hundred megabytes wouldn't need to be read off of disk, as long as it contained only zeroes.

And the reason the "_func_" variables have numbers on the end is because you could have many functions with static variables, all with the same names. The compiler adds a number to make each one unique.

And here's the contents of .data

```<code>$ objdump -s -j .data ./global-static-test
./global-static-test:     file format elf64-powerpcle

Contents of section .data:
 10020028 00000000 01000000 02000000 03000000  ................
 10020038 04000000 05000000                    ........
</code>```

Body:
There is a way in C++ to create a new static variable (with a different memeory address) in a loop for every iteration?

Here it is an example:

static vector<int *> vec;
for(int i=0; i<n; i++){ //n is a generic number
    static int var=i; //var should be a new static variable every loop
    vec.pushback(&var);
}

The vector "vec" should contain all the different addresses of the newly created variables.

Thanks in advance

Edit 1:
This was only a simple example to summarize my problem;
my goal is to have a function that creates a new static variable every time it is called, then this variable should be modified and finally its address stored in a vector of pointers.

Body:
What is a static variable?

In most operating systems the global variables and all static variables are placed into the program image in their own data section. If they have complicated initialization then those are run on program start, or protected with locks and set on first use.

The only difference between global and static variables is that the compiler will not allow your program to use a static variable that is outside the current scope. From an assembly language viewpoint, statics and globals are identical.

Since all globals and statics are created from the program image at startup, you cannot add more of them later.

If you want to use dynamic amounts of memory that grows over time, you need to use the heap. C++ has new T, new T[], delete and delete[] in order to handle that. The C++ standard containers use allocators, which in turn call new in special ways. Normally you don't worry about allocators and just use the containers.

Some fun details!

I made a little C file which I compiled into a .o all on its own, so it wouldn't get optimized away when combined with main. All main does is call f().

#include <stdio.h>

int global_0;
int global_1 = 1;
int global_2 = 2;

static int static_0;
static int static_3 = 3;
static int static_4 = 4;

int f() {
  static int static_func_0;
  static int static_func_5 = 5;

  printf("%p\n", (void *)&global_0);
  printf("%p\n", (void *)&global_1);
  printf("%p\n", (void *)&global_2);

  printf("%p\n", (void *)&static_0);
  printf("%p\n", (void *)&static_3);
  printf("%p\n", (void *)&static_4);

  printf("%p\n", (void *)&static_func_0);
  printf("%p\n", (void *)&static_func_5);

  return 0;
}

And then a few inspections of the resulting program:

$ objdump -t ./global-static-test
[...snipped a bunch of junk...]
000000001002002c l     O .data  0000000000000004              global_1
0000000010020030 l     O .data  0000000000000004              global_2
0000000010020034 l     O .data  0000000000000004              static_3
0000000010020038 l     O .data  0000000000000004              static_4
000000001002003c l     O .data  0000000000000004              static_func_5.0
0000000010020044 l     O .bss   0000000000000004              global_0
0000000010020048 l     O .bss   0000000000000004              static_0
000000001002004c l     O .bss   0000000000000004              static_func_0.1

So you can see that the globals, the file scope statics and the function statics are all huddled together in .data and .bss sections.

The reason for .bss is it is for all zero-initialized things. The program loader does not actually load .bss. Instead it just allocates some number of zero-filled memory pages. A global array of a hundred megabytes wouldn't need to be read off of disk, as long as it contained only zeroes.

And the reason the "_func_" variables have numbers on the end is because you could have many functions with static variables, all with the same names. The compiler adds a number to make each one unique.

And here's the contents of .data

$ objdump -s -j .data ./global-static-test
./global-static-test:     file format elf64-powerpcle

Contents of section .data:
 10020028 00000000 01000000 02000000 03000000  ................
 10020038 04000000 05000000                    ........


问:
Heroku Maven github deploy
I have some issue in heroku deploy</p>

```<code>2020-05-29T00:59:40.015516+00:00 app[web.1]: Error: Unable to access jarfile target/barbershop-0.0.1-SNAPSHOT.jar
2020-05-29T00:59:40.082046+00:00 heroku[web.1]: Process exited with status 1
2020-05-29T00:59:40.135944+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-29T00:59:44.102979+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=powerful-taiga-48681.herokuapp.com request_id=759de18f-db81-47ca-8108-452945494b3d fwd="179.180.253.131" dyno= connect= service= status=503 bytes= protocol=https
</code>```

答:
I'm deploying by github, but when the deploy is finished is not generating my jar file, so I needed to create an sh file to menage that for me, like this:

start.sh

```<code>./mvnw clean package
./mvnw build
./mvnw package
java -Dserver.port=$PORT -jar target/barbershop-0.0.1-SNAPSHOT.jar
</code>```

Procfile

```<code>web: chmod a+x ./mvnw; chmod a+x ./start.sh; ./start.sh
</code>```

Title: Heroku Maven github deploy

Body:
I have some issue in heroku deploy

2020-05-29T00:59:40.015516+00:00 app[web.1]: Error: Unable to access jarfile target/barbershop-0.0.1-SNAPSHOT.jar
2020-05-29T00:59:40.082046+00:00 heroku[web.1]: Process exited with status 1
2020-05-29T00:59:40.135944+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-29T00:59:44.102979+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=powerful-taiga-48681.herokuapp.com request_id=759de18f-db81-47ca-8108-452945494b3d fwd="179.180.253.131" dyno= connect= service= status=503 bytes= protocol=https

Body:
I'm deploying by github, but when the deploy is finished is not generating my jar file, so I needed to create an sh file to menage that for me, like this:

start.sh

./mvnw clean package
./mvnw build
./mvnw package
java -Dserver.port=$PORT -jar target/barbershop-0.0.1-SNAPSHOT.jar

Procfile

web: chmod a+x ./mvnw; chmod a+x ./start.sh; ./start.sh


问:
Haskell- find element in a list
I want to write a function that takes a number i and a list of numbers xs and
returns the position of i in the list xs, counting the first position as 1. If i does
not occur in xs, then position returns 0.

So far I have this:

```<code>import Data.List
position :: Int -> [Int] -> Int
position i xs
   | i `elem` xs = i `elemIndex` xs
   | otherwise = 0
</code>```

But when I compile, it gives the following error:

Couldn't match expected type ‘Int’ with actual type ‘Maybe Int’

I know that elemIndex returns a Maybe Int type and I defined my function to return Int but I don't know how to change it. Any ideas?

答:
This works properly: </p>

```<code>=>> findK k l = l !! k
</code>```

Title: Haskell- find element in a list

Body:
I want to write a function that takes a number i and a list of numbers xs and
returns the position of i in the list xs, counting the first position as 1. If i does
not occur in xs, then position returns 0.

So far I have this:

import Data.List
position :: Int -> [Int] -> Int
position i xs
   | i `elem` xs = i `elemIndex` xs
   | otherwise = 0

But when I compile, it gives the following error:

Couldn't match expected type ‘Int’ with actual type ‘Maybe Int’

I know that elemIndex returns a Maybe Int type and I defined my function to return Int but I don't know how to change it. Any ideas?

Body:
This works properly:

=>> findK k l = l !! k


问:
Extracting from a Union Type when some have identical shapes / properties
I am trying to build an implementation of a CQRS-style command bus, where the interface to the command bus is a single function, dispatch:

const result = dispatch(message)
```

<p>The <code>dispatch</code> function's type signature is something like this:</p>

<pre class="lang-js prettyprint-override"><code>type Dispatch<Message, Result> = (message: Message) => Result
</code>```

Imagine, for example, that we want to provide an interface to a Git repo. Some of the messages might be:

class Clone {
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    constructor(public readonly branchName: string) { }
}

class RevParse {
    constructor(public readonly branchName: string) { }
}
```

<p>For each <code>Message</code>, there is a known type of <code>Result</code>. After some experimentation, I think the right way to express that "protocol" is like this:</p>

<pre class="lang-js prettyprint-override"><code>type Protocol = [Clone, void] | [Checkout, void] | [RevParse, string]
</code>```

The Protocol is a union of tuple types, each expressing the relationship between a Message and an expected type of Result. In the example, only RevParse should be expected to return anything interesting - the others just return void.

To be able to figure out the expected Result for a given Message, I had learned that I can use the Extract utility type, like this:

type Result<Message> = Extract<Protocol, [Message, any]>[1]
type Dispatch<Message extends Protocol[0]> = (message: Message) => Result<Message>
```

<p>However, I've discovered that this seems to fail when two of the Messages have the same properties. For example, I can return a <code>string</code> from the <code>Checkout</code> message. I'm assuming this is because <code>Extract</code> matches both <code>Checkout</code> and <code>RevParse</code> when given the <code>Checkout</code> type to look up the right <code>Result</code>, since both types look like <code>{ branchName: string}</code>.</p>

<pre class="lang-js prettyprint-override"><code>// should fail with type error because the protocol says Checkout should return void.
const checkoutResult: Result<Checkout> = 'string'
// const checkoutResult: string | void
</code>```

I have other questions about this problem but first I need to understand the right way to express the relationship between the Message and Result types. Are my assumptions about the Result lookup correct? Should I be doing completely something different than using the union of tuples? Do I need to add some property to each Message to uniquely identify it? Something else?

Playground Link

答:
I don't really know the use cases and the context of what you are trying to build, but I feel like dispatch returning different types is not a good practice here (there are some cases where it can be necessary : https://softwareengineering.stackexchange.com/questions/225682/is-it-a-bad-idea-to-return-different-data-types-from-a-single-function-in-a-dyna ). You could use Strategy Pattern.

Anyway, let's say this use case is legit :

As you mentionned it, Extract matches both Checkout and RevParse when Checkout is given to Result.
Indeed, Typescript doc says :

Extract<T,U>
  Constructs a type by extracting from T all properties that are assignable to U

In your case, [Checkout, void] and [RevParse, string] are assignable to [Checkout, any] (when you do Result)
It means Checkout and RevParse is assignable to Checkout, and void & string are assignable to any.

The reason is that for classes, Typescript uses structural typing as the following, according to the documentation :

they (classes) have both a static and an instance type. When comparing two
  objects of a class type, only members of the instance are compared.
  Static members and constructors do not affect compatibility.

On the contrary

Private and protected members in a class affect their compatibility.

Therefore, all that matters is the structure of a type, not the name of a type. If two types are structurally equivalent they are interchangeable.
If you don't want that to happen, you can use "nominal typing". There are several approaches, although I think it should be use exceptionally as for now it is not yet native in Typescript. There is a current PR so it might become native in TS soon, using "unique" keyword. For now :

You can add private property to your classes to make it different, even if they have a different name.

```<code>class Clone {
    private __nominal: void;
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    private __nominal: void;
    constructor(public readonly branchName: string) { }
}

class RevParse {
    private __nominal: void;
    constructor(public readonly branchName: string) { }
}
</code>```

You can use static property with different names, using "Brand" suffix, as proposed and used by Typescript team

```<code>class Clone {
    _cloneBrand: any;
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    _checkoutBrand: any;
    constructor(public readonly branchName: string) { }
}

class RevParse {
    _revParseBrand: any;
    constructor(public readonly branchName: string) { }
}
</code>```

This, will fix your second issue, it will become :

```<code>// const checkoutResult: void
</code>```

For the dispatch function, you should just do the following, using your Result type already defined :

```<code> const dispatch = <Message extends Protocol[0]>(message: Message): Result<Message> => {
    if (message instanceof Clone) {
        // do clone stuff
        return
    }
    if (message instanceof Checkout) {
        // do checkout stuff

        // should insist that I return void here
        return 'should not be allowed'
    }
    if (message instanceof RevParse) {
        const { branchName } = message
        // do revparse stuff
        return 'abcdef1234'
    }
    throw new Error(`What is this? ${message}`)
}
</code>```

This will fix your first issue, typescript will now consider the return of dispatch(new Clone('url')) as void

Body:
I am trying to build an implementation of a CQRS-style command bus, where the interface to the command bus is a single function, dispatch:

const result = dispatch(message)

The dispatch function's type signature is something like this:

type Dispatch<Message, Result> = (message: Message) => Result

Imagine, for example, that we want to provide an interface to a Git repo. Some of the messages might be:

class Clone {
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    constructor(public readonly branchName: string) { }
}

class RevParse {
    constructor(public readonly branchName: string) { }
}

For each Message, there is a known type of Result. After some experimentation, I think the right way to express that "protocol" is like this:

type Protocol = [Clone, void] | [Checkout, void] | [RevParse, string]

The Protocol is a union of tuple types, each expressing the relationship between a Message and an expected type of Result. In the example, only RevParse should be expected to return anything interesting - the others just return void.

To be able to figure out the expected Result for a given Message, I had learned that I can use the Extract utility type, like this:

type Result<Message> = Extract<Protocol, [Message, any]>[1]
type Dispatch<Message extends Protocol[0]> = (message: Message) => Result<Message>

However, I've discovered that this seems to fail when two of the Messages have the same properties. For example, I can return a string from the Checkout message. I'm assuming this is because Extract matches both Checkout and RevParse when given the Checkout type to look up the right Result, since both types look like { branchName: string}.

// should fail with type error because the protocol says Checkout should return void.
const checkoutResult: Result<Checkout> = 'string'
// const checkoutResult: string | void

I have other questions about this problem but first I need to understand the right way to express the relationship between the Message and Result types. Are my assumptions about the Result lookup correct? Should I be doing completely something different than using the union of tuples? Do I need to add some property to each Message to uniquely identify it? Something else?

<a href="https://www.typescriptlang.org/play/index.html#code/MYGwhgzhAEDCIHsB2BTaBvAsAKGn6wyEALgE4CuwxCpAFAA7kBGIAlsNKSmACbIgBPTigC2CYigCqpEAC5oJUqyQBzAJQZoAXxw7sOUJBiwAFimABrBOWIYc+AkTKVqdRi3bDe-IU1JgkYBMAOTARFHlFZXVNPT0DcChoACUUADcABTBSCDQsXHxCJEUXGgZmNg4ubyRBaD8AoNDwyLJojXRtXRwcYgF6NAzScQRCEGgAXmgAbXhkFAAaaDSEVh4AXWgAHxnTcysbJZW1zZ3p1Mzs3KWo1XWe7D6BlJQIchBiAB4AWVeIMBUKAAfJNoABRAAeZDAVE+QxGYyW01+UABi2gAQE6yB0wAjPd9I9+mgAGpgNg8FH-QGg+HUMbTAAMBN6xOgABFWBB6GBiEEfn80dAUFCUEgeDAyRSqWiQVNaOFUYD5DLARoJiDUm8PgKlcCHkUSNAeFyeXyTPJOdzefy6aMECAmdjQbrqWgRRJxTA7QzmUCFYLldBVSh1SD8g5WAAzaABvXQZQkRooBAxuaoDr2Bz4AD0OeNCAIiFQCmI5CjUaz2eEZdISCrXQKeGjscVboTxWIydTcDMlmsxEzTezeYLBD7B1sJHLlcJ1bwo4gJmsIB4HYgXNsxBMvOgAEka+Q68tVmuzFwGw4uLWkNAAORLldrpDiepocmIADuKB4d4bekjGM43bRMu0CFMYwuLIclDOxhwcQ1bE6BpAhCMI0C0UE2zRS9c3zPhhDSHkYNLGdcLwa8j1vO8wCYYAeBQKNcQAJgAZgAFj-YcAPwbdhk-aBUAEsFSGGOgAAMAHUd1sLloG3LkAH5oAAEnQbDAS0cS1G6QlRwUmAuG1WSYCeH8O0IUTzGIOpIBwUdEKLeYtXeYhWiUVRthPNYDCcJzUBcj5QRNa1zVoIS4GLFBaDvExiGIehZDzFRWG3ZgADpCBEHMRAEHMuHoBA7zUHS9PzR93jXKMwFYcZP1Skx5LZFBRJoXzO3HfYB0CtyXmMz49n7Gw5XvW4VDvIA" rel="nofollow noreferrer">Playground Link

Body:
I don't really know the use cases and the context of what you are trying to build, but I feel like dispatch returning different types is not a good practice here (there are some cases where it can be necessary : https://softwareengineering.stackexchange.com/questions/225682/is-it-a-bad-idea-to-return-different-data-types-from-a-single-function-in-a-dyna ). You could use Strategy Pattern.

Anyway, let's say this use case is legit :

As you mentionned it, Extract matches both Checkout and RevParse when Checkout is given to Result.
Indeed, Typescript doc says :

Extract<T,U>
  Constructs a type by extracting from T all properties that are assignable to U

In your case, [Checkout, void] and [RevParse, string] are assignable to [Checkout, any] (when you do Result)
It means Checkout and RevParse is assignable to Checkout, and void & string are assignable to any.

The reason is that for classes, Typescript uses structural typing as the following, according to the documentation :

they (classes) have both a static and an instance type. When comparing two
  objects of a class type, only members of the instance are compared.
  Static members and constructors do not affect compatibility.

On the contrary

Private and protected members in a class affect their compatibility.

Therefore, all that matters is the structure of a type, not the name of a type. If two types are structurally equivalent they are interchangeable.
If you don't want that to happen, you can use "nominal typing". There are several approaches, although I think it should be use exceptionally as for now it is not yet native in Typescript. There is a current PR so it might become native in TS soon, using "unique" keyword. For now :

You can add private property to your classes to make it different, even if they have a different name.

class Clone {
    private __nominal: void;
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    private __nominal: void;
    constructor(public readonly branchName: string) { }
}

class RevParse {
    private __nominal: void;
    constructor(public readonly branchName: string) { }
}

You can use static property with different names, using "Brand" suffix, as proposed and used by Typescript team

class Clone {
    _cloneBrand: any;
    constructor(public readonly remoteUrl: string) { }
}

class Checkout {
    _checkoutBrand: any;
    constructor(public readonly branchName: string) { }
}

class RevParse {
    _revParseBrand: any;
    constructor(public readonly branchName: string) { }
}

This, will fix your second issue, it will become :

// const checkoutResult: void

For the dispatch function, you should just do the following, using your Result type already defined :

 const dispatch = <Message extends Protocol[0]>(message: Message): Result<Message> => {
    if (message instanceof Clone) {
        // do clone stuff
        return
    }
    if (message instanceof Checkout) {
        // do checkout stuff

        // should insist that I return void here
        return 'should not be allowed'
    }
    if (message instanceof RevParse) {
        const { branchName } = message
        // do revparse stuff
        return 'abcdef1234'
    }
    throw new Error(`What is this? ${message}`)
}

This will fix your first issue, typescript will now consider the return of dispatch(new Clone('url')) as void


问:
How can i change FutureBuilder to streambuilder what do i need to do here?
After updating my profile with the edit page I have to refresh before I can see changes. Please can anyone help me change this code to a stream builder or at least tell me what to do??</p>

```<code>createProfileTopView() {
return FutureBuilder(
  future: usersReference.document(widget.userProfileId).get(),
  builder: (context, dataSnapshot) {
    if (!dataSnapshot.hasData) {
      return circularProgress();
    } else {
      User user = User.fromDocument(dataSnapshot.data);
      return Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
</code>```

答:
The change must be made on the service, it will no longer return a Future, but must be a Stream.

As for the widget you should use the following, it is very similar to the FutureBuilder.

return StreamBuilder
(
  stream: stream ,
  initialData: initialData ,
  builder: (BuildContext context, AsyncSnapshot snapshot){
    return Container(
      child: child,
    );
  },
);```

Good luck!

Body:
After updating my profile with the edit page I have to refresh before I can see changes. Please can anyone help me change this code to a stream builder or at least tell me what to do??

createProfileTopView() {
return FutureBuilder(
  future: usersReference.document(widget.userProfileId).get(),
  builder: (context, dataSnapshot) {
    if (!dataSnapshot.hasData) {
      return circularProgress();
    } else {
      User user = User.fromDocument(dataSnapshot.data);
      return Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(

Body:
The change must be made on the service, it will no longer return a Future, but must be a Stream.

As for the widget you should use the following, it is very similar to the FutureBuilder.

return StreamBuilder
(
  stream: stream ,
  initialData: initialData ,
  builder: (BuildContext context, AsyncSnapshot snapshot){
    return Container(
      child: child,
    );
  },
);

Good luck!