问:
.NET array is slower than list in IronPython?
I did the following matrix multiplication benchmark in IronPython based on code here:

```<code>from System import Random
from System.Diagnostics import Stopwatch

def zero(m,n):
    # Create zero matrix
    new_matrix = [[0 for row in range(n)] for col in range(m)]
    return new_matrix

def rand(m,n):
    # Create random matrix
    rnd = Random(1)
    new_matrix = [[rnd.NextDouble() for row in range(n)] for col in range(m)]
    return new_matrix

def show(matrix):
    # Print out matrix
    for col in matrix:
        print col

def mult(matrix1,matrix2):
    # Matrix multiplication
    if len(matrix1[0]) != len(matrix2):
        # Check matrix dimensions
        print 'Matrices must be m*n and n*p to multiply!'
    else:
        # Multiply if correct dimensions
        watch = Stopwatch()
        print 'mult1 start....'
        watch.Start()
        new_matrix = zero(len(matrix1),len(matrix2[0]))
        for i in range(len(matrix1)):
            for j in range(len(matrix2[0])):
                for k in range(len(matrix2)):
                    new_matrix[i][j] += matrix1[i][k]*matrix2[k][j]
        watch.Stop()
        print 'mult1 end.'
        print watch.ElapsedMilliseconds
        return new_matrix

from System import Array

def ListToArray(matrix):
    n = len(matrix)
    m = len(matrix[0])
    a = Array.CreateInstance(float, n, m)
    for i in range(n):
        for j in range(m):
            a[i,j] = matrix[i][j]
    return a

def mult2(matrix1, matrix2):

    N = len(matrix1)
    K = len(matrix2)
    M = len(matrix2[0])

    m1 = ListToArray(matrix1)
    m2 = ListToArray(matrix2)
    res = ListToArray(rand(len(matrix1), len(matrix2[0])))

    watch = Stopwatch()
    print 'mult2 start...'
    watch.Start()
    for i in range(N):
        for j in range(M):
            for k in range(K):
                res[i,j] += m1[i,k]*m2[k,j]
    watch.Stop()
    print 'mult2 ends.'
    print watch.ElapsedMilliseconds
    return res

if __name__ == '__main__':
    #a = rand(280,10304)
    #b = rand(10304,280)

    a = rand(280,10)
    b = rand(10,280)

    c = mult2(a, b)
    d = mult(a, b)
</code>```

I want to try two big matrices (280 by 10304 and 10304 by 208), but both versions cannot produce a result within a short time.

Then I tried a much smaller one (as show in the code), I the result is following:

```<code>mult2 : 7902 ms
mult1 : 420 ms
</code>```

indicating that using .NET array in IronPython is much slower than the python List.

Also notice that C# uses about ~12 seconds for the two big matrices. IronPython already spends a lot of them on the 10K times smaller case. I am not sure whether the IronPython setting in my computer is wrong or not, if not, IronPython is really slow for numerical code.

答:
For your particular question, I think the problem is boxing - in IronPython, list items (and all other variables) are stored boxed, so only boxed values are operated on. CLR Array elements are not boxed, however, and thus IronPython will have to box them when they are extracted from the array, and then unbox them on the way back in. C# can operate on the unboxed values, and has a bunch of other optimizations to make arrays fast that IronPython doesn't have.

If you want fast numerical math, NumPy for IronPython might be a better bet.

Body:
I did the following matrix multiplication benchmark in IronPython based on code here:

from System import Random
from System.Diagnostics import Stopwatch

def zero(m,n):
    # Create zero matrix
    new_matrix = [[0 for row in range(n)] for col in range(m)]
    return new_matrix

def rand(m,n):
    # Create random matrix
    rnd = Random(1)
    new_matrix = [[rnd.NextDouble() for row in range(n)] for col in range(m)]
    return new_matrix

def show(matrix):
    # Print out matrix
    for col in matrix:
        print col

def mult(matrix1,matrix2):
    # Matrix multiplication
    if len(matrix1[0]) != len(matrix2):
        # Check matrix dimensions
        print 'Matrices must be m*n and n*p to multiply!'
    else:
        # Multiply if correct dimensions
        watch = Stopwatch()
        print 'mult1 start....'
        watch.Start()
        new_matrix = zero(len(matrix1),len(matrix2[0]))
        for i in range(len(matrix1)):
            for j in range(len(matrix2[0])):
                for k in range(len(matrix2)):
                    new_matrix[i][j] += matrix1[i][k]*matrix2[k][j]
        watch.Stop()
        print 'mult1 end.'
        print watch.ElapsedMilliseconds
        return new_matrix

from System import Array

def ListToArray(matrix):
    n = len(matrix)
    m = len(matrix[0])
    a = Array.CreateInstance(float, n, m)
    for i in range(n):
        for j in range(m):
            a[i,j] = matrix[i][j]
    return a

def mult2(matrix1, matrix2):

    N = len(matrix1)
    K = len(matrix2)
    M = len(matrix2[0])

    m1 = ListToArray(matrix1)
    m2 = ListToArray(matrix2)
    res = ListToArray(rand(len(matrix1), len(matrix2[0])))

    watch = Stopwatch()
    print 'mult2 start...'
    watch.Start()
    for i in range(N):
        for j in range(M):
            for k in range(K):
                res[i,j] += m1[i,k]*m2[k,j]
    watch.Stop()
    print 'mult2 ends.'
    print watch.ElapsedMilliseconds
    return res

if __name__ == '__main__':
    #a = rand(280,10304)
    #b = rand(10304,280)

    a = rand(280,10)
    b = rand(10,280)

    c = mult2(a, b)
    d = mult(a, b)

I want to try two big matrices (280 by 10304 and 10304 by 208), but both versions cannot produce a result within a short time.

Then I tried a much smaller one (as show in the code), I the result is following:

mult2 : 7902 ms
mult1 : 420 ms

indicating that using .NET array in IronPython is much slower than the python List.

Also notice that C# uses about ~12 seconds for the two big matrices. IronPython already spends a lot of them on the 10K times smaller case. I am not sure whether the IronPython setting in my computer is wrong or not, if not, IronPython is really slow for numerical code.


来源: stackexchange

问:
Coloring with a two color scale in HTML and JavaScript
I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.

I am planning on making a simple gradient:

When the number is 100, the element's background color is green #00ff00

When the number is 0, it is red #ff0000

When the number is 50, it displays a yellow color #ffff00

The in-between values should be colored according to the scale.

I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:

var x = 0;

function color() {
    x = document.getElementById("color").value;
    console.log(x);

    if (x > 50) {
        document.getElementById('color').style.backgroundColor = "#00ff00";
    }
    else if (x == 50) {
        document.getElementById('color').style.backgroundColor = "#ffff00";
    }
    else {
        document.getElementById('color').style.backgroundColor = "#ff0000";
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>
<!-- The input is not disabled for value debugging. --></code>```

Is there concise way to perform this task?

答:
You can use Html Range input for this purpose and Use javascript for getting its value. Like:

```<code><input id="myId" type="range" min="0" max="100">
</code>```

Use Javascript to get its value by using its ID. Use a Javascript function. Either call it using a button or add onchange event.

You are just missing a style property...
just do this

```<code>document.getElementById("color").style.background = "Any Color";
</code>```

or if you want to change text color then

```<code>document.getElementById("color").style.color = "Any Color";
</code>```

Here I wrote full code for your problem:-

```<code><input type="number" id="color" min="0" max="100" onkeyup="check()">
<script>
    function check(){
        c = document.getElementById("color");
        x = c.value;
        if(x==0)
            c.style.background="Red";
        else if(x==50)
            c.style.background = "Yellow";
        else
            c.style.background = "Green";
    }
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.

I am planning on making a simple gradient:

When the number is 100, the element's background color is green #00ff00

When the number is 0, it is red #ff0000

When the number is 50, it displays a yellow color #ffff00

The in-between values should be colored according to the scale.

I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:

var x = 0;

function color() {
    x = document.getElementById("color").value;
    console.log(x);

    if (x > 50) {
        document.getElementById('color').style.backgroundColor = "#00ff00";
    }
    else if (x == 50) {
        document.getElementById('color').style.backgroundColor = "#ffff00";
    }
    else {
        document.getElementById('color').style.backgroundColor = "#ff0000";
    }
}

<button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>

Is there concise way to perform this task?

Body:
You can use Html Range input for this purpose and Use javascript for getting its value. Like:

<input id="myId" type="range" min="0" max="100">

Use Javascript to get its value by using its ID. Use a Javascript function. Either call it using a button or add onchange event.

You are just missing a style property...
just do this

document.getElementById("color").style.background = "Any Color";

or if you want to change text color then

document.getElementById("color").style.color = "Any Color";

Here I wrote full code for your problem:-

<input type="number" id="color" min="0" max="100" onkeyup="check()">
<script>
    function check(){
        c = document.getElementById("color");
        x = c.value;
        if(x==0)
            c.style.background="Red";
        else if(x==50)
            c.style.background = "Yellow";
        else
            c.style.background = "Green";
    }
</script>


问:
How to maintain an aspect ratio of a div inside another div
So I have a div and which contains two divs one on top of the other. I want the one on top to have an aspect ratio of 4:5 with 100% width as it will contain an image of that ratio and then remaining height goes goes  to the second div.

This is as far I could go

You can find all the code here

note: I wish to maintain that aspect ratio as the user shrink the screen size, try to shrink the width on the sandbox example to see

```<code>&_product{
                    overflow: hidden;
                    padding-top: 800.34px / 591.44px * 100%;
                    background: rgb(207, 206, 206);
                    position: relative;
                    max-width: 232px;
                    // max-height: 317.313px;
                    &_inside {
                      display: grid;
                      // grid-template-columns: 1fr
                      // grid-template-rows: 1fr 80px;;
                      position: absolute;
                      top: 0;
                      left: 0;
                      width: 100%;
                      height: 100%;
                    }

                    border: 1px solid rgb(131, 72, 72);
                    position:relative;
                    width:100%;
                    height:fit-content;
                    box-shadow: 0 5px 15px rgba(0,0,0,.25);
                    overflow:hidden;
                    &_imgbox{
                      height: 100% ;
                      border: 1px solid red;
                      box-sizing:border-box;
                      position: relative;
                      // img{
                      //   width:100%;
                      //   display:block;
                      //   margin:0;
                      // }
                      &_aspect {
                        position: absolute;
                        width: 100%;
                        height: 5px/4px*100%;   // My attempted calculation
                        background: blue;
                        top: 0;
                        // left: 0;

                      }
                  }
                }
</code>```

html

```<code>    <div class="Recommendations_container_recomendation_box_product">
                            <div class="Recommendations_container_recomendation_box_product_inside">
                                <div class="Recommendations_container_recomendation_box_product_imgbox">
                                    <div class="Recommendations_container_recomendation_box_product_imgbox_aspect">

                                        {/* <img src="https://images.sportsdirect.com/images/products/62310640_l.jpg" /> */}
                                    </div>

                                </div>
                                <div class="Recommendations_container_recomendation_box_details">
                                    <div class="Recommendations_container_recomendation_box_details_price">$55.99</div>
                                    <h2>Brand Name<br /><span>Mens Designer T-shirt</span></h2>

                                </div>
                            </div>

                        </div>
</code>```

答:
Try this:</p>

```<code>.Recommendations_container_recomendation{

  display:flex;

}
</code>```

Body:
So I have a div and which contains two divs one on top of the other. I want the one on top to have an aspect ratio of 4:5 with 100% width as it will contain an image of that ratio and then remaining height goes goes  to the second div.

This is as far I could go

You can find all the code here

note: I wish to maintain that aspect ratio as the user shrink the screen size, try to shrink the width on the sandbox example to see

&_product{
                    overflow: hidden;
                    padding-top: 800.34px / 591.44px * 100%;
                    background: rgb(207, 206, 206);
                    position: relative;
                    max-width: 232px;
                    // max-height: 317.313px;
                    &_inside {
                      display: grid;
                      // grid-template-columns: 1fr
                      // grid-template-rows: 1fr 80px;;
                      position: absolute;
                      top: 0;
                      left: 0;
                      width: 100%;
                      height: 100%;
                    }

                    border: 1px solid rgb(131, 72, 72);
                    position:relative;
                    width:100%;
                    height:fit-content;
                    box-shadow: 0 5px 15px rgba(0,0,0,.25);
                    overflow:hidden;
                    &_imgbox{
                      height: 100% ;
                      border: 1px solid red;
                      box-sizing:border-box;
                      position: relative;
                      // img{
                      //   width:100%;
                      //   display:block;
                      //   margin:0;
                      // }
                      &_aspect {
                        position: absolute;
                        width: 100%;
                        height: 5px/4px*100%;   // My attempted calculation
                        background: blue;
                        top: 0;
                        // left: 0;

                      }
                  }
                }

html

                                        {/*  */}

$55.99

Brand Name
Mens Designer T-shirt

Body:
Try this:

.Recommendations_container_recomendation{

  display:flex;

}


问:
How to send a KSOAP2 request using Android?
I've already searched for similar questions but no answer has worked for me

I have this code inside a function that is called from an AsyncTask in android

```<code>SoapObject Request=new SoapObject(NAMESPACE, METHOD_NAME3);

Request.addProperty("mac",emac.getText().toString());
Request.addProperty("name",eusu.getText().toString());
Request.addProperty("status",usuData[0]);
Request.addProperty("cEmpSmarpa",usuData[1]);

SoapSerializationEnvelope envelope =  new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;

envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();

envelope.setOutputSoapObject(Request);

HttpTransportSE transpor = new HttpTransportSE(URL);
transpor.debug = true;
transpor.call(SOAP_ACTION3,envelope);

resultString=(SoapObject) envelope.getResponse();
</code>```

And with it, I'm sending this XML to my web service

```<code><soapenv:Body>
     <grup:Update>
           <grup:mac>MAC</grup:mac>

           <grup:name>NAME</grup:usuario>

           <grup:status>1</grup:estatus>

           <grup:cEmpSmarpa>0</grup:cEmpresasSmarpa>
     </grup:Update>
</soapenv:Body>
</code>```

but it is not working since I need to send it like this

```<code><soapenv:Body>
      <grup:Update>
         <grup:user>
            <grup:mac>MAC</grup:mac>

            <grup:name>NAME</grup:usuario>

            <grup:status>1</grup:estatus>

            <grup:cEmpSmarpa>0</grup:cEmpresasSmarpa>

         </grup:user>
      </grup:Update>
</soapenv:Body>
</code>```

How can I add that extra group called user that contains my properties?

答:
I did this:

```<code>SoapObject Request=new SoapObject(NAMESPACE, METHOD_NAME3);

SoapObject Soapusuario = new SoapObject(NAMESPACE, "user");

            PropertyInfo pi = new PropertyInfo();
            pi.setNamespace(NAMESPACE);
            pi.setType(PropertyInfo.OBJECT_CLASS);
            pi.setName("user");
            pi.setValue("");
            Soapusuario.addProperty(pi);

</code>```

but then I was getting some "i:type=user" field error, so I added

```<code>envelope.implicitTypes = true;
</code>```

and that solved it.

Body:
I've already searched for similar questions but no answer has worked for me

I have this code inside a function that is called from an AsyncTask in android

SoapObject Request=new SoapObject(NAMESPACE, METHOD_NAME3);

Request.addProperty("mac",emac.getText().toString());
Request.addProperty("name",eusu.getText().toString());
Request.addProperty("status",usuData[0]);
Request.addProperty("cEmpSmarpa",usuData[1]);

SoapSerializationEnvelope envelope =  new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;

envelope.headerOut = new Element[1];
envelope.headerOut[0] = buildAuthHeader();

envelope.setOutputSoapObject(Request);

HttpTransportSE transpor = new HttpTransportSE(URL);
transpor.debug = true;
transpor.call(SOAP_ACTION3,envelope);

resultString=(SoapObject) envelope.getResponse();

And with it, I'm sending this XML to my web service

<soapenv:Body>
     <grup:Update>
           <grup:mac>MAC</grup:mac>

           <grup:name>NAME</grup:usuario>

           <grup:status>1</grup:estatus>

           <grup:cEmpSmarpa>0</grup:cEmpresasSmarpa>
     </grup:Update>
</soapenv:Body>

but it is not working since I need to send it like this

<soapenv:Body>
      <grup:Update>
         <grup:user>
            <grup:mac>MAC</grup:mac>

            <grup:name>NAME</grup:usuario>

            <grup:status>1</grup:estatus>

            <grup:cEmpSmarpa>0</grup:cEmpresasSmarpa>

         </grup:user>
      </grup:Update>
</soapenv:Body>

How can I add that extra group called user that contains my properties?

Body:
I did this:

SoapObject Request=new SoapObject(NAMESPACE, METHOD_NAME3);

SoapObject Soapusuario = new SoapObject(NAMESPACE, "user");

            PropertyInfo pi = new PropertyInfo();
            pi.setNamespace(NAMESPACE);
            pi.setType(PropertyInfo.OBJECT_CLASS);
            pi.setName("user");
            pi.setValue("");
            Soapusuario.addProperty(pi);

but then I was getting some "i:type=user" field error, so I added

envelope.implicitTypes = true;

and that solved it.


问:
Iterate through specific column in pandas
I have a CSV file I need to process in a python script. I've chosen to use the pandas module.

My CSV file looks like this:

```<code>Name,Private IP
bastion001,10.238.2.166
logicmonitor001,10.238.2.52
logicmonitor002,10.238.2.53
</code>```

And I want to iterate through the Name column.

I am reading the file like this:

```<code>hosts_list = os.path.join('..', '..', 'source_files', 'aws_hosts_list', 'aws_hosts_list.csv')
fields = ['Name']
df = pd.read_csv(hosts_list, skipinitialspace=True, usecols=fields)
</code>```

When I print the entire data frame I see this:

print(f"This is the DF: \n{df}")

```<code>This is the DF:
                      Name
0               bastion001
1          logicmonitor001
2          logicmonitor002
</code>```

But when I try to iterate through the output this is what I see:

```<code>for i,j in df.iterrows():
    print(f"{i} {j}")
</code>```

```<code>0 Name    bastion001
Name: 0, dtype: object
1 Name    logicmonitor001
Name: 1, dtype: object
2 Name    logicmonitor02
</code>```

How can I just print the names from the Name column so that I can have a list that looks like this:

```<code>bastion001
logicmonitor001
logicmonitor0002
</code>```

答:
If you just want a list, you can do this:</p>

```<code>list_names = df['Name'].tolist()
print(list_names)

['bastion001', 'logicmonitor001', 'logicmonitor002']
</code>```

Body:
I have a CSV file I need to process in a python script. I've chosen to use the pandas module.

My CSV file looks like this:

Name,Private IP
bastion001,10.238.2.166
logicmonitor001,10.238.2.52
logicmonitor002,10.238.2.53

And I want to iterate through the Name column.

I am reading the file like this:

hosts_list = os.path.join('..', '..', 'source_files', 'aws_hosts_list', 'aws_hosts_list.csv')
fields = ['Name']
df = pd.read_csv(hosts_list, skipinitialspace=True, usecols=fields)

When I print the entire data frame I see this:

print(f"This is the DF: \n{df}")

This is the DF:
                      Name
0               bastion001
1          logicmonitor001
2          logicmonitor002

But when I try to iterate through the output this is what I see:

for i,j in df.iterrows():
    print(f"{i} {j}")

0 Name    bastion001
Name: 0, dtype: object
1 Name    logicmonitor001
Name: 1, dtype: object
2 Name    logicmonitor02

How can I just print the names from the Name column so that I can have a list that looks like this:

bastion001
logicmonitor001
logicmonitor0002

Body:
If you just want a list, you can do this:

list_names = df['Name'].tolist()
print(list_names)

['bastion001', 'logicmonitor001', 'logicmonitor002']


问:
R: Loop requires long run time, suggestions on better structure
I currently have a data set with quarterly returns for 10 indices. My dataset (compoundrates) is structured so that in the first column, we have "Scenario" and the second column is "Quarter", and the following 10 are the quarterly index return. The projection is 50 quarters, so lines 1-51 reflect quarters 0-50 for scenario 1, and lines 52-102 reflect quarter 0-50 for scenario 2, etc for 1000 scenarios.

To calculate cumulative compound rates, I need to multiply the current return by all previous returns from the projection. I set up a loop to do this in the code below:

```<code>for(i in 1:nrow(compoundrates)){
  if(compoundrates[i, "Quarter"] == 0){
    compoundrates[i, -c(1:2)] <- 1
  } else{
    compoundrates[i, -c(1:2)] <- compoundrates[i, -c(1:2)] * compoundrates[i - 1, -c(1:2)]
  }
}
</code>```

The loop is simple and works how I want. However, with 51000 rows, this takes about 13 minutes. Is there a way to speed up the code? I tried thinking of a vectorized solution, but could only think that I would need to loop through all rows of the dataset. While 13 minutes is not the end of the world, I have other datasets with longer projections, up to 200 quarters, which would take extremely long.

Possibly pivoting the dataset to be horizontal would require only 50 loops rather than 51000, but thought I'd see if anyone else had a more elegant solution.

Edit: Included here is a sample of the first couple of lines of my dataset:

```<code>> dput(head(compoundrates[, 1:4])) # First part of data, only 2 indices
structure(list(Scenario = c(1L, 1L, 1L, 1L, 1L, 1L), Quarter = c(0,
1, 2, 3, 4, 5), US = c(1, 1.06658609144463, 1.1022314574062,
1.1683883540847, 1.29134306037902, 1.28907212981088), MidCap = c(1,
1.10361590084936, 1.12966579678275, 1.21702573464001, 1.2674372889915,
1.37286942499386)), row.names = c(NA, -6L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), groups = structure(list(Scenario = 1L,
    .rows = list(1:6)), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
</code>```

答:
Try this out, it uses vectorized functions, basically exactly what you are trying to do with a for loop. It create new columns so you can see what is going on. Vectorized function usually run a lot faster than for loops

```<code>library(tidyverse)
compoundrates %>%
  group_by(Scenario) %>%
  arrange(Quarter) %>%
  mutate(US_lag = lag(US),
         MidCap_lag = lag(MidCap),
         US_cum = US *US_lag,
         MidCap_cum = MidCap *MidCap_lag) %>%
  mutate_all(~ifelse(is.na(.), 1, .))
</code>```

This should do the cumulative product you were asking for

```<code>compoundrates %>%
  group_by(Scenario) %>%
  arrange(Quarter) %>%
  mutate(US_cum = cumprod(US),
         MidCap_cum = cumprod(MidCap))
</code>```

Per @carl-witthoft suggestion here is the benchmarking. I made a dataframe of 60,000 rows grouped by the 6 quarters in the OP.

```<code>Unit: milliseconds
                                                                                expr
     big_data %>%
        group_by(Scenario) %>%
          mutate(US_cum = cumprod(US),
                 MidCap_cum = cumprod(MidCap))

         min      lq     mean   median      uq     max neval
 63.1487 70.0257 77.16906 73.72995 79.7645 147.167   100
</code>```

Body:
I currently have a data set with quarterly returns for 10 indices. My dataset (compoundrates) is structured so that in the first column, we have "Scenario" and the second column is "Quarter", and the following 10 are the quarterly index return. The projection is 50 quarters, so lines 1-51 reflect quarters 0-50 for scenario 1, and lines 52-102 reflect quarter 0-50 for scenario 2, etc for 1000 scenarios.

To calculate cumulative compound rates, I need to multiply the current return by all previous returns from the projection. I set up a loop to do this in the code below:

for(i in 1:nrow(compoundrates)){
  if(compoundrates[i, "Quarter"] == 0){
    compoundrates[i, -c(1:2)] <- 1
  } else{
    compoundrates[i, -c(1:2)] <- compoundrates[i, -c(1:2)] * compoundrates[i - 1, -c(1:2)]
  }
}

The loop is simple and works how I want. However, with 51000 rows, this takes about 13 minutes. Is there a way to speed up the code? I tried thinking of a vectorized solution, but could only think that I would need to loop through all rows of the dataset. While 13 minutes is not the end of the world, I have other datasets with longer projections, up to 200 quarters, which would take extremely long.

Possibly pivoting the dataset to be horizontal would require only 50 loops rather than 51000, but thought I'd see if anyone else had a more elegant solution.

Edit: Included here is a sample of the first couple of lines of my dataset:

> dput(head(compoundrates[, 1:4])) # First part of data, only 2 indices
structure(list(Scenario = c(1L, 1L, 1L, 1L, 1L, 1L), Quarter = c(0,
1, 2, 3, 4, 5), US = c(1, 1.06658609144463, 1.1022314574062,
1.1683883540847, 1.29134306037902, 1.28907212981088), MidCap = c(1,
1.10361590084936, 1.12966579678275, 1.21702573464001, 1.2674372889915,
1.37286942499386)), row.names = c(NA, -6L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), groups = structure(list(Scenario = 1L,
    .rows = list(1:6)), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))

Body:
Try this out, it uses vectorized functions, basically exactly what you are trying to do with a for loop. It create new columns so you can see what is going on. Vectorized function usually run a lot faster than for loops

library(tidyverse)
compoundrates %>%
  group_by(Scenario) %>%
  arrange(Quarter) %>%
  mutate(US_lag = lag(US),
         MidCap_lag = lag(MidCap),
         US_cum = US *US_lag,
         MidCap_cum = MidCap *MidCap_lag) %>%
  mutate_all(~ifelse(is.na(.), 1, .))

This should do the cumulative product you were asking for

compoundrates %>%
  group_by(Scenario) %>%
  arrange(Quarter) %>%
  mutate(US_cum = cumprod(US),
         MidCap_cum = cumprod(MidCap))

Per @carl-witthoft suggestion here is the benchmarking. I made a dataframe of 60,000 rows grouped by the 6 quarters in the OP.

Unit: milliseconds
                                                                                expr
     big_data %>%
        group_by(Scenario) %>%
          mutate(US_cum = cumprod(US),
                 MidCap_cum = cumprod(MidCap))

         min      lq     mean   median      uq     max neval
 63.1487 70.0257 77.16906 73.72995 79.7645 147.167   100


问:
:hover seems to not work and i have no idea why
I don't know why, but hover won't change the opacity of the image. I've even tried to make a separate HTML page and it has the same problem.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

OPACITY 0.2

OPACITY 0.5

OPACITY 1

```

答: instead of putting inline css first style each image through internal css then try it. it should work</p>


问:
Delete Last Row in Group
I have a workbook with information sorted by an UKey; I need to delete the last row in each group.

In this example, I need to remove row 524; ranges between UKeys are not fixed.

I've tried calculating a new column to reference the previous row with no luck, re-sorting the data and removing the first row, playing with index...

Help!

答: One way to do this would be to create a separate query where you Group By UKey and take the max as the aggregate for your timestamp column. This should give you a table with Ukey and its timestamp for the row you want to remove. Once you have that, you can do a left anti join on your original table (matching on both columns, not just UKey) to remove the rows that exist in the grouped table.

Title: Delete Last Row in Group


答:
Try this:

```<code>print(list(df['Name']))
</code>```

Output:

```<code>['bastion001', 'logicmonitor001', 'logicmonitor002']
</code>```

If you want them one per line, try this:

```<code>for val in list(df['Name']):
    print(val)
</code>```

Output:

```<code>bastion001
logicmonitor001
logicmonitor002
</code>```

Title: Iterate through specific column in pandas

Body:
Try this:

print(list(df['Name']))

Output:

['bastion001', 'logicmonitor001', 'logicmonitor002']

If you want them one per line, try this:

for val in list(df['Name']):
    print(val)

Output:

bastion001
logicmonitor001
logicmonitor002


问:
Property 'value' does not exist on type EventTarget in TypeScript
So the following code is in Angular 4 and I can't figure out why it doesn't work the way as expected.

Here is a snippet of my handler:

```<code>onUpdatingServerName(event: Event) {
  console.log(event);
  this.newserverName = event.target.value; //this wont work
}
</code>```

HTML element:

```<code><input type="text" class="form-control" (input)="onUpdatingServerName($event)">
</code>```

The code gives me the error:

Property 'value' does not exist on type 'EventTarget'.

But as it can be seen in the console.log that value does exist on the event.target.

答:
The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}
```
<p>This assumes you are only interested in the <code>target</code> property, which is the most common case. If you need to access the other properties of <code>event</code>, a more comprehensive solution involves using the <code>&</code> type intersection operator:</p>
<pre class="lang-js prettyprint-override"><code>event: Event & { target: HTMLInputElement }
</code>```

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

ContentLicense: CC BY-SA 3.0

Body:
So the following code is in Angular 4 and I can't figure out why it doesn't work the way as expected.

Here is a snippet of my handler:

onUpdatingServerName(event: Event) {
  console.log(event);
  this.newserverName = event.target.value; //this wont work
}

HTML element:

<input type="text" class="form-control" (input)="onUpdatingServerName($event)">

The code gives me the error:

Property 'value' does not exist on type 'EventTarget'.

But as it can be seen in the console.log that value does exist on the event.target.

Body:
The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.


问:
Parsing Google Analytics API XML Response
I cannot seem to parse out the metrics for an organic keyword. I am using simplexml_load_string to load the whole response string and then when I print_r the object I can see this:

```<code>[0] => SimpleXMLElement Object
                (
                    [id] => http://www.google.com/analytics/feeds/data?ids=ga:480&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24
                    [updated] => 2011-07-23T17:00:00.001-07:00
                    [title] => ga:keyword=cats
                    [link] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [rel] => alternate
                                    [type] => text/html
                                    [href] => http://www.google.com/analytics
                                )

                        )

                )
</code>```

But when I look at the actual (pre-formatted) response I see some extra data that didn't survive the format:

```<code><entry gd:etag="W/"hdSFEs."" gd:kind="analytics#datarow">
<id>http://www.google.com/analytics/feeds/data?ids=ga:430&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24</id>
<updated>2011-07-23T17:00:00.001-07:00</updated>
<title>ga:keyword=cats</title>
<link rel="alternate" type="text/html" href="http://www.google.com/analytics"/>
<dxp:dimension name="ga:keyword" value="cats"/>
<dxp:metric confidenceInterval="0.0" name="ga:organicSearches" type="integer" value="2"/>
</entry>
</code>```

I need that metric value at the bottom, in this case it's two. How can I get it?

Thanks!

答:
Edit: Arend is right, the problem is just SimpleXML handling the namespaces strangely.

You might need to pass the entire XML response to the SimpleXMLElement() constructor, not just the snippet you provided here. In particular you need the <feed> element because it has the namespace declarations:

```<code><feed xmlns='http://www.w3.org/2005/Atom' xmlns:dxp='http://schemas.google.com/analytics/2009' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"DUINSHcycSp7I2A9WxRWFEQ."' gd:kind='analytics#data'>
    <entry gd:etag="W/"hdSFEs."" gd:kind="analytics#datarow">
    <id>http://www.google.com/analytics/feeds/data?ids=ga:430&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24</id>
    <updated>2011-07-23T17:00:00.001-07:00</updated>
    <title>ga:keyword=cats</title>
    <link rel="alternate" type="text/html" href="http://www.google.com/analytics"/>
    <dxp:dimension name="ga:keyword" value="cats"/>
    <dxp:metric confidenceInterval="0.0" name="ga:organicSearches" type="integer" value="2"/>
    </entry>
</feed>
</code>```

Without these namespace declarations it looks like your XML library is dropping any namespaced attributes or elements (such as <dxp:metric>).

You might also get different results from a different version of the XML library. On my system your snippet produces a SimpleXMLElement with all of the attributes and elements, including <metric>, though I do get a bunch of PHP warnings complaining about the missing namespace declarations.

Body:
I cannot seem to parse out the metrics for an organic keyword. I am using simplexml_load_string to load the whole response string and then when I print_r the object I can see this:

[0] => SimpleXMLElement Object
                (
                    [id] => http://www.google.com/analytics/feeds/data?ids=ga:480&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24
                    [updated] => 2011-07-23T17:00:00.001-07:00
                    [title] => ga:keyword=cats
                    [link] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [rel] => alternate
                                    [type] => text/html
                                    [href] => http://www.google.com/analytics
                                )

                        )

                )

But when I look at the actual (pre-formatted) response I see some extra data that didn't survive the format:

<entry gd:etag="W/"hdSFEs."" gd:kind="analytics#datarow">
<id>http://www.google.com/analytics/feeds/data?ids=ga:430&ga:keyword=cats&start-date=2011-04-10&end-date=2011-07-24</id>
<updated>2011-07-23T17:00:00.001-07:00</updated>
<title>ga:keyword=cats</title>
<link rel="alternate" type="text/html" href="http://www.google.com/analytics"/>
<dxp:dimension name="ga:keyword" value="cats"/>
<dxp:metric confidenceInterval="0.0" name="ga:organicSearches" type="integer" value="2"/>
</entry>

I need that metric value at the bottom, in this case it's two. How can I get it?

Thanks!

Body:
Edit: Arend is right, the problem is just SimpleXML handling the namespaces strangely.

You might need to pass the entire XML response to the SimpleXMLElement() constructor, not just the snippet you provided here. In particular you need the <feed> element because it has the namespace declarations:

<feed xmlns='http://www.w3.org/2005/Atom' xmlns:dxp='http://schemas.google.com/analytics/2009' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;DUINSHcycSp7I2A9WxRWFEQ.&quot;' gd:kind='analytics#data'>
    <entry gd:etag="W/&quot;hdSFEs.&quot;" gd:kind="analytics#datarow">
    <id>http://www.google.com/analytics/feeds/data?ids=ga:430&amp;ga:keyword=cats&amp;start-date=2011-04-10&amp;end-date=2011-07-24</id>
    <updated>2011-07-23T17:00:00.001-07:00</updated>
    <title>ga:keyword=cats</title>
    <link rel="alternate" type="text/html" href="http://www.google.com/analytics"/>
    <dxp:dimension name="ga:keyword" value="cats"/>
    <dxp:metric confidenceInterval="0.0" name="ga:organicSearches" type="integer" value="2"/>
    </entry>
</feed>

Without these namespace declarations it looks like your XML library is dropping any namespaced attributes or elements (such as <dxp:metric>).

You might also get different results from a different version of the XML library. On my system your snippet produces a SimpleXMLElement with all of the attributes and elements, including <metric>, though I do get a bunch of PHP warnings complaining about the missing namespace declarations.


问:
Specify gradient background color and separete from line colors (ggplot2)
I am trying to create a line graph with a gradient color background based on another variable (very similar to this post 1). The difference is that I have multiple lines that are based on different factor levels. Here is my code:

```<code>ggplot(data=cl, aes(x=date, y=value)) +
  geom_rect(aes(xmin=date,xmax=date+1,ymin=min(value),ymax=max(value),
                fill=StringencyIndex2)) +
  geom_line(aes(colour=dominio), size=1)
</code>```

And this produces this graph

How can I change the background color to a blue gradient and use a different color palette for the lines?

Many thanks!

答:
```<code>###
# Generate data
###
set.seed(1)
date <- seq(as.Date("01Jan20", "%d%b%Y"),as.Date("28May20", "%d%b%Y"), by=1)
dts <- data.frame(date=date,
                  value=cumsum(rnorm(length(date))),
                  dominio=sample(LETTERS[1:5],length(date),replace=T),
                  StringencyIndex2=cut(runif(length(date)), breaks=seq(0,1,0.25)))
dts$dominio <- factor(dts$dominio, labels=c("Comercio y ocio","Alimentacion y farmacia",
                                            "Transporte publico","Trabajo","Residencial"))

#########
# Define colors for the background like in scale_fill_gradient
#########
pal <- colorRampPalette(c("#132B43","#56B1F7"))
cols <- pal(length(unique(dts$StringencyIndex2)))

ggplot(data=dts, aes(x=date, y=value)) +
  geom_rect(aes(xmin=date,xmax=date+1,ymin=min(value),ymax=max(value),
                fill=StringencyIndex2)) +
  geom_line(aes(colour=dominio), size=1) +
  scale_fill_manual(values=cols) +
  #########
  # Define line colors using scale_color_manual
  #########
  scale_color_manual(values=c("Comercio y ocio"="red",
                              "Alimentacion y farmacia"="white",
                              "Transporte publico"="yellow",
                              "Trabajo"="green",
                              "Residencial"="cyan")) +
  theme_bw()
</code>```

Body:
I am trying to create a line graph with a gradient color background based on another variable (very similar to this post 1). The difference is that I have multiple lines that are based on different factor levels. Here is my code:

ggplot(data=cl, aes(x=date, y=value)) +
  geom_rect(aes(xmin=date,xmax=date+1,ymin=min(value),ymax=max(value),
                fill=StringencyIndex2)) +
  geom_line(aes(colour=dominio), size=1)

And this produces this graph

How can I change the background color to a blue gradient and use a different color palette for the lines?

Many thanks!


问:
ValueError: invalid literal for int() with base 10: 'Mumbai to Dubai'
When i perform this command

```<code>valueReturned = int(request.form.get("name"))
</code>```

where this name is a select tag, i am getting a value error stating

ValueError: invalid literal for int() with base 10: 'Mumbai to Dubai'

This is my select code.

```<code><select name="name">
        {% for flight in flights %}
        <option id="{{flight.id}}">{{flight.origin}} to {{flight.destination}}</option>
        {% endfor %}
    </select>
</code>```

And what does the compiler selects from the  tag.

答:
error is caused because you parse to int string "Mumbai to Dubai". you request attribute 'name' from select and you dont have got any values in options. So you try to parse this:

```<code>{{flight.origin}} to {{flight.destination}}
</code>```

try to put values to option tags:

```<code><select name="name">
    {% for flight in flights %}
        <option value="{{flight.id}}">{{flight.origin}} to {{flight.destination}}</option>
    {% endfor %}
 </select>
</code>```

change a bit this statement:

```<code> valueReturned = int(request.form["name"])
</code>```

i suppose that flight.id is a number - string but number. And then you will have got int method working without errors

Body:
When i perform this command

valueReturned = int(request.form.get("name"))

where this name is a select tag, i am getting a value error stating

ValueError: invalid literal for int() with base 10: 'Mumbai to Dubai'

This is my select code.

<select name="name">
        {% for flight in flights %}
        <option id="{{flight.id}}">{{flight.origin}} to {{flight.destination}}</option>
        {% endfor %}
    </select>

And what does the compiler selects from the  tag.

Body:
error is caused because you parse to int string "Mumbai to Dubai". you request attribute 'name' from select and you dont have got any values in options. So you try to parse this:

{{flight.origin}} to {{flight.destination}}

try to put values to option tags:

<select name="name">
    {% for flight in flights %}
        <option value="{{flight.id}}">{{flight.origin}} to {{flight.destination}}</option>
    {% endfor %}
 </select>

change a bit this statement:

 valueReturned = int(request.form["name"])

i suppose that flight.id is a number - string but number. And then you will have got int method working without errors


问:
Usage of the ref function in ML
Considering the ref operator I'm having trouble to understand its application and the sense of the follow instructions:

1.

In this definition what am I defining?

```<code> - val ref x=ref 9;

 val x = 9 : int
</code>```

2.

and here what am I doing with ref x:= ref 12?

```<code> - val x= ref 8;

 val x = ref 8 : int ref

 - ref x := ref 12;

 val it = () : unit

 - x;

 val it = ref 8 : int ref
</code>```

答:
@newacct, @sepp2k I see this is from several years ago, but I found the discussion useful and wanted to contribute this output from Standard ML of New Jersey v110.79 [built: Tue Aug  8 16:57:33 2017]:

```<code>- val ref x = ref 9;
val x = 9 : int
</code>```

Title: Usage of the ref function in ML

Body:
Considering the ref operator I'm having trouble to understand its application and the sense of the follow instructions:

1.

In this definition what am I defining?

 - val ref x=ref 9;

 val x = 9 : int

2.

and here what am I doing with ref x:= ref 12?

 - val x= ref 8;

 val x = ref 8 : int ref

 - ref x := ref 12;

 val it = () : unit

 - x;

 val it = ref 8 : int ref

Body:
@newacct, @sepp2k I see this is from several years ago, but I found the discussion useful and wanted to contribute this output from Standard ML of New Jersey v110.79 [built: Tue Aug  8 16:57:33 2017]:

- val ref x = ref 9;
val x = 9 : int


问:
Ruby - Problem with HTTP Post
this is my code:

```<code>   @data = "somedata\r\nsomadata\r\nsomadata\r\n"
   uri = URI.parse(my_url)
   http = Net::HTTP.new(uri.host, uri.port)
   resp, body = http.post(uri.path, @data)
</code>```

When I try to run this, I get a 'sysread' error, saying that the end of file was reached (EOFError).
Note that if I remove the \r of @data, the error doesn't occur, but I really need it.

I'm using Ruby 1.8.7, but a similar problem accurred with 1.9.2.

I am trying to convert a PHP class to Ruby, Here is the PHP code:

```<code>$req = 'somedata\r\nsomadata\r\nsomadata\r\n';
$r = new HttpRequest($url, HttpRequest::METH_POST);
$r->addRawPostData($req);
$resp = $r->send()->getBody();
</code>```

Thanks!

答: This is a shot in the dark but the default ContentType for net/http post is "x-www-form-urlencoded". Try setting the ContentType in the header to "text/plain". Take a look at the net/http docs for how to set the header.</p>

Title: Ruby - Problem with HTTP Post

Body:
this is my code:

   @data = "somedata\r\nsomadata\r\nsomadata\r\n"
   uri = URI.parse(my_url)
   http = Net::HTTP.new(uri.host, uri.port)
   resp, body = http.post(uri.path, @data)

When I try to run this, I get a 'sysread' error, saying that the end of file was reached (EOFError).
Note that if I remove the \r of @data, the error doesn't occur, but I really need it.

I'm using Ruby 1.8.7, but a similar problem accurred with 1.9.2.

I am trying to convert a PHP class to Ruby, Here is the PHP code:

$req = 'somedata\r\nsomadata\r\nsomadata\r\n';
$r = new HttpRequest($url, HttpRequest::METH_POST);
$r->addRawPostData($req);
$resp = $r->send()->getBody();

Thanks!


问:
Sort data in state after getting json from api in React Redux
I have a question about sorting data in React. I have searched for a solution but I can't understand, how to do it. I have to sort the 'payments' by id DESC or by the date DESC. How could I do that?
I have the code with my list of payments (Payments.js) and the component (Payment.js).
Thanks

Payments.js

```<code>class Payments extends Component {
    componentDidMount() {
        this.props.getAllPayments();
    }
    render() {
        const { payments } = this.props.payments;

        return(
            <div className='dashboard container text-center'>
                <div className='row entry'>
                <div className='col-sm-1'>
                    <span><strong>ID</strong></span>
                </div>
                <div className='col-sm-2'>
                    <span><strong>Date</strong></span>
                </div>
                <div className='col-sm-4'>
                    <span><strong>Name</strong></span>
                </div>
                <div className='col-sm-5'>
                    <span><strong>Lastname</strong></span>
                </div>
                </div>
                { payments.map(payment => {
                    return (

                        <Payment payment={payment} key={payment.id} />
                    )
                })}
            </div>
        )

    }
}

Payments.propTypes = {
    getAllPayments: PropTypes.func.isRequired,
    payments: PropTypes.object.isRequired
};

const mapStateToProps = state => {
    return {
        payments: state.payment

    }
}

export default connect(mapStateToProps, {getAllPayments})(Payments);
</code>```

Payment.js

```<code>class Payment extends Component{

    componentDidMount() {
        this.props.getAllUsers();
    }

    render() {

        const { users } = this.props.users;
        const { payment } = this.props;
        return (

            <div className='row entry'>
                <div className='col-sm-1'>
                    <span>{payment.id}</span>
                </div>
                <div className='col-sm-2'>
                    <span >{payment.date}</span>
                </div>
                <div className='col-sm-4'>

                    <span>
                        { users.map(user => {
                        return (
                            (payment.userId === user.id)&&user.name

                        )
                    })}
                    </span>
                </div>
                <div className='col-sm-5'>
                    <span>
                        { users.map(user => {
                         return (
                             (payment.userId === user.id)&&user.lastname

                         )
                     })}
                    </span>
                </div>
            </div>
        )
    }

}

Payment.propTypes = {
    users: PropTypes.object.isRequired
};

const mapStateToProps = state => {
    return {
        users: state.user

    }
}

export default connect(
    mapStateToProps, {  getAllUsers }
)(Payment);
</code>```

答:
You can sort the information before it goes into your store by modifying your Payments Reducer before returning the new state.

If your IDs are incremental numbers the use a sort() function to sort by ID Number.

Note: if your IDs are randomly generated, then it would be almost imposible to sort them by that value.

Below is an example of a sort function:

```<code>arr.sort((a,b) => {
   const keyA = a.id,
   const keyB = b.id;
   // Compare the 2 ids
   if (keyA < keyB) return -1;
   if (keyA > keyB) return 1;
   return 0;
});
</code>```

If you want to sort them by date, then it could be something like this:

```<code>arr.sort((a, b) => {
   var keyA = new Date(a.date),
   keyB = new Date(b.date);
   // Compare the 2 dates
   if (keyA < keyB) return -1;
   if (keyA > keyB) return 1;
   return 0;
 });
</code>```

Body:
I have a question about sorting data in React. I have searched for a solution but I can't understand, how to do it. I have to sort the 'payments' by id DESC or by the date DESC. How could I do that?
I have the code with my list of payments (Payments.js) and the component (Payment.js).
Thanks

Payments.js

class Payments extends Component {
    componentDidMount() {
        this.props.getAllPayments();
    }
    render() {
        const { payments } = this.props.payments;

        return(

                    ID

                    Date

                    Name

                    Lastname

                { payments.map(payment => {
                    return (

                        <Payment payment={payment} key={payment.id} />
                    )
                })}

        )

    }
}

Payments.propTypes = {
    getAllPayments: PropTypes.func.isRequired,
    payments: PropTypes.object.isRequired
};

const mapStateToProps = state => {
    return {
        payments: state.payment

    }
}

export default connect(mapStateToProps, {getAllPayments})(Payments);

Payment.js

class Payment extends Component{

    componentDidMount() {
        this.props.getAllUsers();
    }

    render() {

        const { users } = this.props.users;
        const { payment } = this.props;
        return (

                    {payment.id}

                    {payment.date}

                        { users.map(user => {
                        return (
                            (payment.userId === user.id)&&user.name

                        )
                    })}

                        { users.map(user => {
                         return (
                             (payment.userId === user.id)&&user.lastname

                         )
                     })}

        )
    }

}

Payment.propTypes = {
    users: PropTypes.object.isRequired
};

const mapStateToProps = state => {
    return {
        users: state.user

    }
}

export default connect(
    mapStateToProps, {  getAllUsers }
)(Payment);

Body:
You can sort the information before it goes into your store by modifying your Payments Reducer before returning the new state.

If your IDs are incremental numbers the use a sort() function to sort by ID Number.

Note: if your IDs are randomly generated, then it would be almost imposible to sort them by that value.

Below is an example of a sort function:

arr.sort((a,b) => {
   const keyA = a.id,
   const keyB = b.id;
   // Compare the 2 ids
   if (keyA < keyB) return -1;
   if (keyA > keyB) return 1;
   return 0;
});

If you want to sort them by date, then it could be something like this:

arr.sort((a, b) => {
   var keyA = new Date(a.date),
   keyB = new Date(b.date);
   // Compare the 2 dates
   if (keyA < keyB) return -1;
   if (keyA > keyB) return 1;
   return 0;
 });


问:
How to handle a collection of a base class if subtype references are required, without saving things twice?
I have some base Class A and some (B, C, D, E) different subclasses. All instances of A come from an external data source (database) and I have to infer the actual type at runtime (with marker atttributes stored in the database) and I have no option to change this behaviour.

I end up with a List allAs. At runtime several algorithms have to be executed, that perform on subclasses of A, i.e. I have some algo(List bs), algo(List cs), ... functions and to call them I need to extract all B's, C's or whatever I need from the List.
On the other hand there are algorithms performing on collections of A's.

The following follows:

At some point I need to save references to instances of A's

At some point I need to save references to instances of subclasses

All this data has to be synchronized

The question is, what are best / bad practices to achieve this?
Following solutions come to my mind:

Stick to the List allAs and call as.stream().filter() to extract sublists of given subclasses
each time I have to call a subclass-algorithm

Create a seperate list for each subclass, and combine them all if I need to call an algorithm

that acts on instances of the base class

Do both, but then on update / add / delete actions I need to perform them on each of the lists

(which I need anyways for the second solution)

My intuition tells me that the cleanest way would be to stick to the first principle, but this gets performance critical since I have to handle much data such that filtering the whole collection each time is not viable.

答:
You can avoid duplicated storage if you copy the data into a list or array sorted by the element types. Then, since all elements of the same type are consecutive elements, you can use specific sub-sequences when sub-types are required:

```<code>Collection<A> data = externalSource();

// preparation step
class State<T> {
    final Class<T> type;
    int s, e;
    List<?> list;
    State(Class<T> c) {
        type = c;
    }
    @SuppressWarnings("unchecked") <U> List<U> as(Class<U> c) {
        if(c != type) throw new ClassCastException(c+" != "+type);
        return (List<U>)list;
    }
}
Map<Class<? extends A>,State<?>> tmp = new HashMap<>();
for(A a: data) tmp.computeIfAbsent(a.getClass(), State::new).s++;
int size = 0;
for(State<?> s: tmp.values()) {
    int next = s.s;
    s.s = s.e = size;
    size += next;
}
A[] all = new A[size];
for(A a: data) all[tmp.get(a.getClass()).e++] = a;
List<A> listOfAll = Arrays.asList(all);
for(State<?> s: tmp.values())
    s.list = listOfAll.subList(s.s, s.e);

// now, all lists are available, listOfAll for all As and:
List<B> listOfB = tmp.get(B.class).as(B.class);
List<C> listOfC = tmp.get(C.class).as(C.class);
List<D> listOfD = tmp.get(D.class).as(D.class);
List<E> listOfE = tmp.get(E.class).as(E.class);

System.out.println("B: "+listOfB+",\nC: "+listOfC+",\nD: "+listOfD+",\nE: "+listOfE);
</code>```

This performs counting sort into the A[] all array, then all lists are created as a view into the array, not having storage of their own. The original collection can be dropped, leaving it subject to garbage collection.

There is one unavoidable unchecked operation, but note that it has an explicit runtime check to ensure safety, assuming the initialization by the code shown above.

This code is easily applicable to a different number of subclasses.

Demo on Ideone

Body:
You can avoid duplicated storage if you copy the data into a list or array sorted by the element types. Then, since all elements of the same type are consecutive elements, you can use specific sub-sequences when sub-types are required:

Collection<A> data = externalSource();

// preparation step
class State<T> {
    final Class<T> type;
    int s, e;
    List<?> list;
    State(Class<T> c) {
        type = c;
    }
    @SuppressWarnings("unchecked") <U> List<U> as(Class<U> c) {
        if(c != type) throw new ClassCastException(c+" != "+type);
        return (List<U>)list;
    }
}
Map<Class<? extends A>,State<?>> tmp = new HashMap<>();
for(A a: data) tmp.computeIfAbsent(a.getClass(), State::new).s++;
int size = 0;
for(State<?> s: tmp.values()) {
    int next = s.s;
    s.s = s.e = size;
    size += next;
}
A[] all = new A[size];
for(A a: data) all[tmp.get(a.getClass()).e++] = a;
List<A> listOfAll = Arrays.asList(all);
for(State<?> s: tmp.values())
    s.list = listOfAll.subList(s.s, s.e);

// now, all lists are available, listOfAll for all As and:
List<B> listOfB = tmp.get(B.class).as(B.class);
List<C> listOfC = tmp.get(C.class).as(C.class);
List<D> listOfD = tmp.get(D.class).as(D.class);
List<E> listOfE = tmp.get(E.class).as(E.class);

System.out.println("B: "+listOfB+",\nC: "+listOfC+",\nD: "+listOfD+",\nE: "+listOfE);

This performs counting sort into the A[] all array, then all lists are created as a view into the array, not having storage of their own. The original collection can be dropped, leaving it subject to garbage collection.

There is one unavoidable unchecked operation, but note that it has an explicit runtime check to ensure safety, assuming the initialization by the code shown above.

This code is easily applicable to a different number of subclasses.

Demo on Ideone


问:
Need help joining dictionary items and remove newlines and multiple spaces and special characters
Dictionary with 2 urls and their text: Need to get rid of all multiple spaces, special characters and new lines

{'https://firsturl.com': ['\n\n',
  '\n      ',
  '\n    \n    \n    ',
  '\n    \n  ',
  '\n  \n  ',
  '\n\n  ',
  '\n',
  '\n',
  '\n  ',
  '\n  ',
  'Home | Sam ModelInc',
  '\n  \n\n\n',
  '\n\n\n\n',
  '\n\n',
  '\n  \n\n\n\n\n\n\n\n\n  \n  \n',
  '\n',
  '\n',
  '\n',
  '\n',
  '\n  ',
  '\n    ',
  'Skip to main content'],'https://secondurl.com#main-content': ['\n\n',
  '\n      ',
  '\n    \n    \n    ',
  '\n    \n  ',
  '\n  \n  ',
  '\n\n  ',
  '\n',
  '\n',
  '\n  ',
  '\n  ',
  'Home | Going to start inc',
  '\n  \n\n\n',
  '\n\n\n\n',
  '\n\n',
  '\n  \n\n\n\n\n\n\n\n\n  \n  \n',
  '\n',
  '\n',
  '\n',
  '\n',
  '\n  ',
  '\n    ',
  'Skip to main content',
  '\n  ',
  '\n    \n',
  '\n\n  ',
  '\n\n            ',
  '\n    \n    \n    \n    \n  ',
  '\n\n  ',
  '\n              ',
  '\n\n            \n              ',
  '\n    ',
  '\n\n      \n  ',
  '\n    ',
  'Brands',
  '\n',
  'About Us',
  '\n',
  'Syndication',
  '\n',
  'Direct Response']}

Expected Output:
{'https://firsturl.com': ['home sam modelInc skip to main content'], https://secondurl.com#main-content': ['home going to start inc skip to main content brands about us syndication direct response]}

Help would be much appreciated

答:
So let's try to walk through this instead of just throwing some code at you.

The first element we want to get rid of is the newline. So we could start with something like:

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]
    ex_dict[x] = new_list
```

<p>If you run that, you'll see that we now filter out all new lines.</p>

<p>Now we have the following cases:</p>

```Home | Sam ModelInc
Skip to main content
Home | Going to start inc
Brands
About Us
Syndication
Direct Response
```

<p>According to your expected output, you want to lowercase all words and remove non-alphabet characters.</p>

<p>Did a little research for how to do that.</p>

<p>In code, that looks like:</p>

<pre class="lang-py prettyprint-override"><code>import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]
    ex_dict[x] = new_list
</code>```

so now our final new_list looks something like: ['Home  Sam ModelInc', 'Skip to main content']

Next we want to lowercase everything.

import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]

    new_list = [e.lower() for e in new_list]
    ex_dict[x] = new_list
```

<p>and lastly we want to combine everything with only one space between each word.</p>

<pre class="lang-py prettyprint-override"><code>import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]

    new_list = [e.lower() for e in new_list]

    new_list = [" ".join((" ".join(new_list)).split())]
    ex_dict[x] = new_list
</code>```

Body:
So let's try to walk through this instead of just throwing some code at you.

The first element we want to get rid of is the newline. So we could start with something like:

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]
    ex_dict[x] = new_list

If you run that, you'll see that we now filter out all new lines.

Now we have the following cases:

Home | Sam ModelInc
Skip to main content
Home | Going to start inc
Brands
About Us
Syndication
Direct Response

According to your expected output, you want to lowercase all words and remove non-alphabet characters.

Did a little research for how to do that.

In code, that looks like:

import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]
    ex_dict[x] = new_list

so now our final new_list looks something like: ['Home  Sam ModelInc', 'Skip to main content']

Next we want to lowercase everything.

import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]

    new_list = [e.lower() for e in new_list]
    ex_dict[x] = new_list

and lastly we want to combine everything with only one space between each word.

import re

regex = re.compile('[^a-zA-Z ]') # had to tweak the linked solution to include spaces

ex_dict = {"a": ["\n\n", "\n"]}

for x in ex_dict:
    new_list = [e for e in ex_dict[x] if "\n" not in e]

    """
    >>> regex.sub("", "Home | Sam ModelInc")
    'Home  Sam ModelInc'
    """
    new_list = [regex.sub("", e) for e in new_list]

    new_list = [e.lower() for e in new_list]

    new_list = [" ".join((" ".join(new_list)).split())]
    ex_dict[x] = new_list


问:
How to return 0 incase of empty result in oracle select query?
I have a Query where there is number datatype column. In case of empty resultset O/P is blank. I want 0 in that case.

My query is

```<code>select nvl(infodata,0)
from table1
where group_id = 111
  and appid in (select max(id)
                from table1, table2
                where status = 'A');
</code>```

Now my inner query is returning null in that case. NVL seems to be not working on infodata column. Please help

答:
Outcome of such a query is no rows selected.

For example (based on Scott's EMP and DEPT tables as I don't have yours, and you didn't post test case), this query returns nothing:

```<code>SQL> select e.deptno
  2  from emp e
  3  where e.ename = 'Littlefoot';

no rows selected
</code>```

If it is used as a subquery, the result is equal to what you currently have:

```<code>SQL> select nvl(d.dname, 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

no rows selected
</code>```

But, if you apply aggregation (see line #1), then you'd get what you wanted:

```<code>SQL> select nvl(max(d.dname), 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

RESULT
--------------
x
</code>```

As I said: it works on my test case; might, or might not on yours. If you post sample data, we'd have something to work with.

Body:
I have a Query where there is number datatype column. In case of empty resultset O/P is blank. I want 0 in that case.

My query is

select nvl(infodata,0)
from table1
where group_id = 111
  and appid in (select max(id)
                from table1, table2
                where status = 'A');

Now my inner query is returning null in that case. NVL seems to be not working on infodata column. Please help

Body:
Outcome of such a query is no rows selected.

For example (based on Scott's EMP and DEPT tables as I don't have yours, and you didn't post test case), this query returns nothing:

SQL> select e.deptno
  2  from emp e
  3  where e.ename = 'Littlefoot';

no rows selected

If it is used as a subquery, the result is equal to what you currently have:

SQL> select nvl(d.dname, 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

no rows selected

But, if you apply aggregation (see line #1), then you'd get what you wanted:

SQL> select nvl(max(d.dname), 'x') result
  2  from dept d
  3  where d.deptno in (select e.deptno
  4                     from emp e
  5                     where e.ename = 'Littlefoot'
  6                    );

RESULT
--------------
x

As I said: it works on my test case; might, or might not on yours. If you post sample data, we'd have something to work with.


问:
How to create a hello world button in java
I am  trying to make a button that says hello world but it dose not work I tried multiple times but nothing i did made a difference

```<code>[![package com.company;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Main implements ActionListener {
        JButton b;
        JFrame f;
        public Main()
        {
            b=new JButton("hello");
            b.addActionListener(this);
            b.setBounds(100,100,95,30);
            f.setTitle("first");
            f.setSize(500,300);
            f.add(b);
            f.setVisible(true);
            f.setLayout(null);
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource()==b)
            {
                System.out.print("hello world");
            }
        }
        public static void main(String\[\] args) {
            // write your code here
            new Main();
        }

    }][1]][1]
</code>```

and this is he result it displays

答: You need to instantiate your JFrame in the constructor with f = new JFrame();.

Body:
I am  trying to make a button that says hello world but it dose not work I tried multiple times but nothing i did made a difference

[![package com.company;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Main implements ActionListener {
        JButton b;
        JFrame f;
        public Main()
        {
            b=new JButton("hello");
            b.addActionListener(this);
            b.setBounds(100,100,95,30);
            f.setTitle("first");
            f.setSize(500,300);
            f.add(b);
            f.setVisible(true);
            f.setLayout(null);
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource()==b)
            {
                System.out.print("hello world");
            }
        }
        public static void main(String\[\] args) {
            // write your code here
            new Main();
        }

    }][1]][1]

and this is he result it displays


问:
pd.to_datetime US to Europe datetime
I want to change my axis x where the value are 2019-01, 2019-02..
To 01-01-2019, 01-02-2019...
I find it's due to the pd.to_datetime US default.
I try different thing but nothing change...

```<code>ax1.plot(pd.to_datetime(DB['Date'], dayfirst=True), θPf2plot, color = 'gray', label = "Capacité au champ")
ax1.plot(pd.to_datetime(DB['Date'], format='%d/%m/%Y'), θPf2plot, color = 'gray', label = "Capacité au champ")
</code>```

If you have any ideas, thank you for your help :) !

答:
pd.to_datetime just converts a string to datetimes. But it does not change the format.

To change the format in matplotlib you have to use DateFormatter as explained in this SO post.

It is hard to tell from your code snippet, but the solution should look like this:

```<code>import matplotlib.dates as mdates

ax1.set_xticks(pd.to_datetime(DB['Date'])
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%Y"))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter("%d/%m/%Y"))
</code>```

Title: pd.to_datetime US to Europe datetime

Body:
I want to change my axis x where the value are 2019-01, 2019-02..
To 01-01-2019, 01-02-2019...
I find it's due to the pd.to_datetime US default.
I try different thing but nothing change...

ax1.plot(pd.to_datetime(DB['Date'], dayfirst=True), θPf2plot, color = 'gray', label = "Capacité au champ")
ax1.plot(pd.to_datetime(DB['Date'], format='%d/%m/%Y'), θPf2plot, color = 'gray', label = "Capacité au champ")

If you have any ideas, thank you for your help :) !

Body:
pd.to_datetime just converts a string to datetimes. But it does not change the format.

To change the format in matplotlib you have to use DateFormatter as explained in this SO post.

It is hard to tell from your code snippet, but the solution should look like this:

import matplotlib.dates as mdates

ax1.set_xticks(pd.to_datetime(DB['Date'])
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%Y"))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter("%d/%m/%Y"))


问:
Perl or sed: Regex replace with group capture
I cannot seem to make sed do a regex replace with group capture in this example:

Input: "DONE project 1"

Desired putput: "project 1 DONE"

What I tried with sed:

```<code>$ echo "DONE project 1" | sed -E 's/^DONE(.*)$/$1 DONE/g'
$1 DONE  # fail! no group capture in `sed`?
</code>```

Is there a way to do this in Perl?

Actually this is part of an AppleScript used by DEVONthink[^1], and I realized that sed was not able to do regex search/replace with group capture.

[^1]: DEVONthink's search/replace script with AppleScript usage

```<code>set transformedName to do shell script "echo " & quoted form of itemName & " | sed -E 's/" & sourcePattern & "/" & destPattern & "/g'"
set name of selectedItem to transformedName
</code>```

答:
The Perl version is very close to the sed version because Perl stole some of sed's features:

```<code>$ perl -pe 's/^DONE(.*)/\1 DONE/'
</code>```

The -p effectively wraps while(<>) { ...; print } around your argument to -e.

Note that the /g flag doesn't make much sense here. You're going to match the first DONE and everything after it. There's no second match to make.

Body:
I cannot seem to make sed do a regex replace with group capture in this example:

Input: "DONE project 1"

Desired putput: "project 1 DONE"

What I tried with sed:

$ echo "DONE project 1" | sed -E 's/^DONE(.*)$/$1 DONE/g'
$1 DONE  # fail! no group capture in `sed`?

Is there a way to do this in Perl?

Actually this is part of an AppleScript used by DEVONthink[^1], and I realized that sed was not able to do regex search/replace with group capture.

[^1]: DEVONthink's search/replace script with AppleScript usage

set transformedName to do shell script "echo " & quoted form of itemName & " | sed -E 's/" & sourcePattern & "/" & destPattern & "/g'"
set name of selectedItem to transformedName

Body:
The Perl version is very close to the sed version because Perl stole some of sed's features:

$ perl -pe 's/^DONE(.*)/\1 DONE/'

The -p effectively wraps while(<>) { ...; print } around your argument to -e.

Note that the /g flag doesn't make much sense here. You're going to match the first DONE and everything after it. There's no second match to make.


问:
How do I create an HTML button that acts like a link?
How do I create an HTML button that acts like a link? So that clicking the button redirects the user to a page.

I want it to be accessible, and with minimal extra characters or parameters in the URL.

答:
If you're using a CSS library or a theme, just apply the classes of a button to the anchor/link tag.

Below is an example with One UI:

```<code><a class="btn-block-option" href="">
    <i class="si si-reload"></i>
</a>
</code>```

Body:
If you're using a CSS library or a theme, just apply the classes of a button to the anchor/link tag.

Below is an example with One UI:

<a class="btn-block-option" href="">
    <i class="si si-reload"></i>
</a>


问:
How to Toggle Classname in ReactJS when button is Clicked?
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

```<code>constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}
</code>```

I am binding my toggleMenu function in this section here:

```<code><div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
<div className="hamburger-inner"></div>
</div>
</div>
</code>```

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

```<code>class NavMenu extends Component {
    render() {
        return (
            <nav className="isMobile">
                <ul>
                    <li><a href="#about">About Us</a></li>
                    <li><a href="#bottom2">Services</a></li>
                    <li><a href="/">Clients</a></li>
                    <li><a href="/">Contact</a></li>
                    <li><a href="/">Login</a></li>
                </ul>
             </nav>
        )
    }
}
</code>```

And here is my whole class component to fully understand the process.
Class Component Source Code

```<code>import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav
</code>```

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

答:
If you declare a menuOpen in the constructor, you should use menuOpen state in toggleMenu function instead of show state (show state has not declared yet).

You should use this.state.menuOpen instead of function this.toggleMenu for conditional operator.

```<code>import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {menuOpen} = this.state;
this.setState({menuOpen : !menuOpen});
}

render() {
console.log(this.state.menuOpen);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.state.menuOpen ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav
</code>```

Body:
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}

I am binding my toggleMenu function in this section here:

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

class NavMenu extends Component {
    render() {
        return (

About Us

Services

Clients

Contact

Login

        )
    }
}

And here is my whole class component to fully understand the process.
Class Component Source Code

import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (

About Us

Services

Clients

Contact

Login

{this.state.show && <NavMenu/>}

)
}
}

class NavMenu extends Component {
render() {
return (

About Us

Services

Clients

Contact

Login

)
}
}

export default nav

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

Body:
If you declare a menuOpen in the constructor, you should use menuOpen state in toggleMenu function instead of show state (show state has not declared yet).

You should use this.state.menuOpen instead of function this.toggleMenu for conditional operator.

import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {menuOpen} = this.state;
this.setState({menuOpen : !menuOpen});
}

render() {
console.log(this.state.menuOpen);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.state.menuOpen ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav


问:
Debug in VS as non-admin
I'm doing some WinForms development, running XP and VS 2005 (ancient, I know).  I'd like to make sure my application can run without admin rights, but I'm too lazy to try to run VS as a non-admin, and I don't want to log in and out to test my app.

Is there a way I can just debug as a non-admin?

Is there a set of code access security attributes I can add to my code that will force me to run in the same permission set as a non admin?

答:
Run VS as another user from your current logged in desktop session. See How to enable and use the "Run As" command when running programs in Windows. This means you won't have to log-in and out. </p>

<p>I would suggest that you just run your target application as another user, via RunAs, then attach the VS Debugger to the process (if needed), via the Debug > Attach To Process... menu item in Visual Studio. </p>

OwnerDisplayName: foson

ContentLicense: CC BY-SA 2.5

Title: Debug in VS as non-admin

Body:
Run VS as another user from your current logged in desktop session. See How to enable and use the "Run As" command when running programs in Windows. This means you won't have to log-in and out.

I would suggest that you just run your target application as another user, via RunAs, then attach the VS Debugger to the process (if needed), via the Debug > Attach To Process... menu item in Visual Studio.

OwnerDisplayName: Phil Price


问:
Python: Remove character only from end of string if character is ="/"
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

```<code>def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")
</code>```

Thank you

答:
Use endswith method to check if it ends with /

```<code>if vars_path_out.endswith('/')
</code>```

Or simply check the last character:

```<code>if vars_path_out[-1] == '/'
</code>```

Like this:

```<code>vars_path = vars_path_out[:-1] if vars_path_out.endswith('/') else vars_path_out
</code>```

Or like this:

```<code>if vars_path_out.endswith('\'):
  vars_path = vars_path_out[:-1]
else:
  vars_path = vars_path_out
</code>```

another way is rstrip method:

```<code>vars_path = vars_path_out.rstrip('/')
</code>```

Body:
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")

Thank you

Body:
Use endswith method to check if it ends with /

if vars_path_out.endswith('/')

Or simply check the last character:

if vars_path_out[-1] == '/'

Like this:

vars_path = vars_path_out[:-1] if vars_path_out.endswith('/') else vars_path_out

Or like this:

if vars_path_out.endswith('\'):
  vars_path = vars_path_out[:-1]
else:
  vars_path = vars_path_out

another way is rstrip method:

vars_path = vars_path_out.rstrip('/')


问:
.env file fails to pass string value
I am working in a react project and an API call completes successfully when the string value is directly entered. It fails when using the .env file

```<code>require('dotenv').load();

export default () => {

  const postToApi = (event) => {
    event.preventDefault();
    axios.post(process.env.API_POST_URL, {step : "3"})
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  };
</code>```

And here is my .env file in the root project folder:

```<code>NODE_PATH=./node_modules

API_POST_URL=http://localhost:4000/api/donate
</code>```

The browser console error when executing the above function:

```<code>isURLSameOrigin.js:51 Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
    at isURLSameOrigin (isURLSameOrigin.js:51)
    at dispatchXhrRequest (xhr.js:106)
    at new Promise (<anonymous>)
    at xhrAdapter (xhr.js:18)
    at dispatchRequest (dispatchRequest.js:49)
</code>```

package.json dependency object lists: "dotenv": "^6.1.0"

Does anyone know why the variable is not passing correctly?

答:
const path = require('path');

require('dotenv').config({path: path.join(__dirname, '../.env')});

Title: .env file fails to pass string value

Body:
I am working in a react project and an API call completes successfully when the string value is directly entered. It fails when using the .env file

require('dotenv').load();

export default () => {

  const postToApi = (event) => {
    event.preventDefault();
    axios.post(process.env.API_POST_URL, {step : "3"})
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  };

And here is my .env file in the root project folder:

NODE_PATH=./node_modules

API_POST_URL=http://localhost:4000/api/donate

The browser console error when executing the above function:

isURLSameOrigin.js:51 Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
    at isURLSameOrigin (isURLSameOrigin.js:51)
    at dispatchXhrRequest (xhr.js:106)
    at new Promise (<anonymous>)
    at xhrAdapter (xhr.js:18)
    at dispatchRequest (dispatchRequest.js:49)

package.json dependency object lists: "dotenv": "^6.1.0"

Does anyone know why the variable is not passing correctly?


问:
Save form data in modal class that contains an array [Angular]
How can I save form data that contains an array.so I faced an issue which is the adresses is null whereas other data like city region aren't null. someone here have an idea ?!

Iuser.interface

```<code> export interface UserData {
    id: string;
    email: string;
    adresses: string[];

  }
</code>```

Component.ts

```<code>onSubmit() {

    const {adresse1, ...rest} = this.form;

    const userData: UserData = {...rest, adresses: [adresse1]};

    this.userservice.updateProfile(userData, this.currentUser.id).subscribe(
      data => {
        console.log(data);
        this.isSuccessful = true;
      },
      err => {
        this.errorMessage = err.error.message;
      }
    );
  }
</code>```

component.html

```<code><div class="form-group">
        <label>Address</label>
    <input type="text" class="form-control" placeholder=""
            name="adresse"
            [(ngModel)]="form.adresse"
            required
            #adresse="ngModel">

  </div> <!-- form-group end.// -->
<div class="form-row">
        <div class="form-group col-md-6">
          <label>Region</label>
      <input type="text" class="form-control"
      name="region"
      [(ngModel)]="form.region"
      required
      #region="ngModel">
    </div> <!-- form-group end.// -->
</code>```

答:
You are reading adresse1 from this.form inside onSubmit() method which is not a part of your form object,your address is actually stored inadresse property.Please update your code within submit block as

```<code>const {adresse, ...rest} = this.form;
const userData: UserData = {...rest, adresses: [adresse]};
</code>```

Body:
How can I save form data that contains an array.so I faced an issue which is the adresses is null whereas other data like city region aren't null. someone here have an idea ?!

Iuser.interface

 export interface UserData {
    id: string;
    email: string;
    adresses: string[];

  }

Component.ts

onSubmit() {

    const {adresse1, ...rest} = this.form;

    const userData: UserData = {...rest, adresses: [adresse1]};

    this.userservice.updateProfile(userData, this.currentUser.id).subscribe(
      data => {
        console.log(data);
        this.isSuccessful = true;
      },
      err => {
        this.errorMessage = err.error.message;
      }
    );
  }

component.html

        Address
    <input type="text" class="form-control" placeholder=""
            name="adresse"
            [(ngModel)]="form.adresse"
            required
            #adresse="ngModel">

          Region
      <input type="text" class="form-control"
      name="region"
      [(ngModel)]="form.region"
      required
      #region="ngModel">

Body:
You are reading adresse1 from this.form inside onSubmit() method which is not a part of your form object,your address is actually stored inadresse property.Please update your code within submit block as

const {adresse, ...rest} = this.form;
const userData: UserData = {...rest, adresses: [adresse]};


问:
Prevent Bootstrap Menu going Behind Footer
I've designed a Page who has Top Navigation, Slider and Footer. it looks fine on Desktop but when we open/Expand the Menu on Mobile Device, the Menu is going behind the Footer.

Please note that we cannot add extra White Space between Slider and Footer to prevent this as described in this

Following is the Screenshot from Mobile Device:

How can we resolve this?
please help

Thanks

答:
Increase the z-index of your dropdown menu in css. Like if your dropdown menu is something like this:

```<code><div class="dropdown">
  <ul>
    <li><a>Home</a></li>
    <li><a>About Us</a></li>
  </ul>
</div>
</code>```

You just have to make sure the z-index of your dropdown is greater than your footer element. You can try increasing z-index of your dropdown element something like this:

```<code>.dropdown {
    z-index: 999
 }
</code>```

Make sure your dropdown has a position other than static for z-index to be effective, also the z-index value that you give it should be greater than the z-index value of your footer element.

Body:
Increase the z-index of your dropdown menu in css. Like if your dropdown menu is something like this:

<div class="dropdown">
  <ul>
    <li><a>Home</a></li>
    <li><a>About Us</a></li>
  </ul>
</div>

You just have to make sure the z-index of your dropdown is greater than your footer element. You can try increasing z-index of your dropdown element something like this:

.dropdown {
    z-index: 999
 }

Make sure your dropdown has a position other than static for z-index to be effective, also the z-index value that you give it should be greater than the z-index value of your footer element.


问:
Tomcat Java Servlet - Initialize Class on Application Startup
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

```<code>MyClass myClassInstance = new MyClass("arg1", "arg2");
</code>```

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

```<code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" +myResult +"</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
</code>```

Is this possible?

答:
If you want it to happen once for the whole app, and happen before any servlet is run, implement ServletContextListener and put your startup code in contextInitialized().  Then set up your web.xml to specify your class as a listener.

Otherwise, you can do what the other answer says and put it in the init() method of the servlet.

Body:
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

MyClass myClassInstance = new MyClass("arg1", "arg2");

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("<title>Test</title>");
        out.println("");
        out.println("");
        out.println("
" +myResult +"
");
        out.println("");
        out.println("");
    }
}

Is this possible?