问:
CSS causing lag on scroll
The following CSS causes lagg when I want to scroll down on my page, the first time it loads:

```<code>.main.style2 {
    background-color: #333;
    color: rgba(255, 255, 255, 0.75);
    background-attachment: fixed, fixed;
    background-image: url(../images/overlay1.png), url(../images/header.jpg);
    background-size: auto, cover;
    height: auto;
}
</code>```

What would be the best way to fix this?

答:
If you are sure the problem is with arrow. then try :
hiding arrow with your pure css code.
then on document ready with jquery try changing css to show it.</p>

Title: CSS causing lag on scroll

Body:
The following CSS causes lagg when I want to scroll down on my page, the first time it loads:

.main.style2 {
    background-color: #333;
    color: rgba(255, 255, 255, 0.75);
    background-attachment: fixed, fixed;
    background-image: url(../images/overlay1.png), url(../images/header.jpg);
    background-size: auto, cover;
    height: auto;
}

What would be the best way to fix this?


来源: stackexchange

问:
Strange behavior form C# serial port
I'm getting strange behavior from simple program, which I'm using to learn how to use the serial port. The form have just one serial port control and one TextBox. Because it's just a test program I have disabled the thread call check.
I forgot to mention,that I'm using micro-controller to send 1000 bytes of data (read EEPROM).
The strange thing is that, when I read the data and just append it directly to the text box in the DataReceived event, everything is fine, but when I first pass the values to int[] array,and then use a loop to convert them to strings in HEX format and append them to the TextBox, there are some zeros, between the values.

Some code with results.

Case 1: read data and directly append to TextBox

```<code>private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (sp1.BytesToRead > 0)
        {
            textBox1.AppendText(sp1.ReadByte().ToString("X")+ " ");
        }

    }
</code>```

And the result is (well,part of it,as i said there are 1000 bytes to receive...)

```<code>0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C..... and so on
</code>```

Case 2: first store the values to int array,and than convert them to string, and append to TextBox

```<code> private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        int[] buffer = new int[1000];
        int i = 0;
        while (sp1.BytesToRead > 0)
        {
            //textBox1.AppendText(sp1.ReadByte().ToString("X")+ " ");
            buffer[i] = sp1.ReadByte();
            i++;
        }
        int j = 0;
        while (j < 1000)
        {
            textBox1.AppendText(buffer[j].ToString("X"));
            j++;
        }
</code>```

I get a lot of 0's at random places, and it reads 4-5 times more data, than the 1000 in the loop

```<code>0123456789ABCDEF101112131415161718191A1B1C1D1E1F00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
</code>```

What might be the reason for this strange behavior?
Thanks in advance

答:
sp1_DataReceived is typically not called only once. Typically your computer handles received data faster than received. This means at some point the loop

```<code>while (sp1.BytesToRead > 0)
</code>```

is left before all 1000 bytes are received. Just a short time later sp1_DataReceived is already called again because more of the 1000 bytes are now available. Since your first implementation only appends the bytes it doesen't matter. But your second implementation differs because you are always appending 1000 characters to your text. This could lead to a result of a multiple of 1000 characters with zeros appended.

To fix your problem you need to combine the bytes of multiple events. One solution could be to use a list like

```<code>private List<byte> buffer = new List<byte>();
private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while (sp1.BytesToRead > 0)
    {
        buffer.Add(sp1.ReadByte());
    }

    //Print if all bytes are available
    if (buffer.Count >= 1000)
    {
        //Join the bytes to a string using LINQ
        textBox1.Text = String.Join("", buffer.Select(b => b.ToString("X")));
        buffer.Clear();
    }
}
</code>```

or an array like

```<code>private byte[] buffer = new byte[1000];
private int bufferIndex = 0;
private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while (sp1.BytesToRead > 0 && bufferIndex  < 1000)
    {
        buffer[bufferIndex ] = sp1.ReadByte();
        bufferIndex ++;
    }

    //Print if all bytes are available
    if (bufferIndex  >= 1000)
    {
        //Join the bytes to a string using LINQ
        textBox1.Text = String.Join("", buffer.Select(b => b.ToString("X")));
        bufferIndex = 0;
    }
}
</code>```

Note that this are only some ideas and example implementations. Since I do not know if you are also receiving other messages at the port it is not possible to give a perfect suitable solution to solve your problem.

ContentLicense: CC BY-SA 3.0

Title: Strange behavior form C# serial port

Body:
I'm getting strange behavior from simple program, which I'm using to learn how to use the serial port. The form have just one serial port control and one TextBox. Because it's just a test program I have disabled the thread call check.
I forgot to mention,that I'm using micro-controller to send 1000 bytes of data (read EEPROM).
The strange thing is that, when I read the data and just append it directly to the text box in the DataReceived event, everything is fine, but when I first pass the values to int[] array,and then use a loop to convert them to strings in HEX format and append them to the TextBox, there are some zeros, between the values.

Some code with results.

Case 1: read data and directly append to TextBox

private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        while (sp1.BytesToRead > 0)
        {
            textBox1.AppendText(sp1.ReadByte().ToString("X")+ " ");
        }

    }

And the result is (well,part of it,as i said there are 1000 bytes to receive...)

0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C..... and so on

Case 2: first store the values to int array,and than convert them to string, and append to TextBox

 private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        int[] buffer = new int[1000];
        int i = 0;
        while (sp1.BytesToRead > 0)
        {
            //textBox1.AppendText(sp1.ReadByte().ToString("X")+ " ");
            buffer[i] = sp1.ReadByte();
            i++;
        }
        int j = 0;
        while (j < 1000)
        {
            textBox1.AppendText(buffer[j].ToString("X"));
            j++;
        }

I get a lot of 0's at random places, and it reads 4-5 times more data, than the 1000 in the loop

0123456789ABCDEF101112131415161718191A1B1C1D1E1F00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF0123456789ABCDEF101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

What might be the reason for this strange behavior?
Thanks in advance

Body:
sp1_DataReceived is typically not called only once. Typically your computer handles received data faster than received. This means at some point the loop

while (sp1.BytesToRead > 0)

is left before all 1000 bytes are received. Just a short time later sp1_DataReceived is already called again because more of the 1000 bytes are now available. Since your first implementation only appends the bytes it doesen't matter. But your second implementation differs because you are always appending 1000 characters to your text. This could lead to a result of a multiple of 1000 characters with zeros appended.

To fix your problem you need to combine the bytes of multiple events. One solution could be to use a list like

private List<byte> buffer = new List<byte>();
private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while (sp1.BytesToRead > 0)
    {
        buffer.Add(sp1.ReadByte());
    }

    //Print if all bytes are available
    if (buffer.Count >= 1000)
    {
        //Join the bytes to a string using LINQ
        textBox1.Text = String.Join("", buffer.Select(b => b.ToString("X")));
        buffer.Clear();
    }
}

or an array like

private byte[] buffer = new byte[1000];
private int bufferIndex = 0;
private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while (sp1.BytesToRead > 0 && bufferIndex  < 1000)
    {
        buffer[bufferIndex ] = sp1.ReadByte();
        bufferIndex ++;
    }

    //Print if all bytes are available
    if (bufferIndex  >= 1000)
    {
        //Join the bytes to a string using LINQ
        textBox1.Text = String.Join("", buffer.Select(b => b.ToString("X")));
        bufferIndex = 0;
    }
}

Note that this are only some ideas and example implementations. Since I do not know if you are also receiving other messages at the port it is not possible to give a perfect suitable solution to solve your problem.


问:
How to select multiple non-contigous columns from a list into another dataframe in python
I am working on Ipython and Spark and I have a RDD from which I form a list. Now from this list I want to form a dataframe which has multiple columns from parent list but these columns are not contiguous. I wrote this but it seems to be working wrong:

```<code>list1 = rdd.collect()
columns_num = [1,8,11,17,21,24]
df2 = [list[i] for i in columns_num]
</code>```

The above code only selects 6 rows, with only column 1 data, from parent list and forms the new dataframe with those 6 columns 1 data.

How can I form a new dataframe with multiple not contiguous columns from another list

答:
With Optimus this is really easy. You just need to install it with:

```<code> pip install optimuspyspark
</code>```

Then you import it (it will start Spark for you):

```<code>import optimus as op
</code>```

Let's create the DF:

```<code>rdd = sc.parallelize([("a", 1, 2, 4.0, "foo"), ("b", 3, 4, 5.0, "bar")])
df = rdd.toDF()
</code>```

And start the transformer:

```<code>transformer = op.DataFrameTransformer(df)
</code>```

And select your columns

```<code>df_new = transformer.select_idx([0,2]).df
</code>```

And you have it now:

```<code>df_new.show()

+---+---+
| _1| _3|
+---+---+
|  a|  2|
|  b|  4|
+---+---+
</code>```

Body:
I am working on Ipython and Spark and I have a RDD from which I form a list. Now from this list I want to form a dataframe which has multiple columns from parent list but these columns are not contiguous. I wrote this but it seems to be working wrong:

list1 = rdd.collect()
columns_num = [1,8,11,17,21,24]
df2 = [list[i] for i in columns_num]

The above code only selects 6 rows, with only column 1 data, from parent list and forms the new dataframe with those 6 columns 1 data.

How can I form a new dataframe with multiple not contiguous columns from another list

Body:
With Optimus this is really easy. You just need to install it with:

 pip install optimuspyspark

Then you import it (it will start Spark for you):

import optimus as op

Let's create the DF:

rdd = sc.parallelize([("a", 1, 2, 4.0, "foo"), ("b", 3, 4, 5.0, "bar")])
df = rdd.toDF()

And start the transformer:

transformer = op.DataFrameTransformer(df)

And select your columns

df_new = transformer.select_idx([0,2]).df

And you have it now:

df_new.show()

+---+---+
| _1| _3|
+---+---+
|  a|  2|
|  b|  4|
+---+---+


问:
Route is not matched
I can't figure out why this is not matching my route for the CompanyDetailContainer.  The route for Interview container works fine

```<code>      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
      <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
</code>```

so http://localhost:8080/interviews/companies/10 hits the interview route fine but http://localhost:8080/interviews/companies/501/details does not hit the companydetail route

UPDATE:

I'm using:

```<code>"react-router": "^3.0.0",
"react-router-dom": "^4.2.2",
</code>```

original code:

```<code>import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Switch>
        <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
        <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      </Switch>
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
  </Router>
</code>```

adding just exact to what I had didn't work:

```<code>import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>

  </Router>
</code>```

Then I tried to add switch around it:

```<code>import { Router, Route, Switch, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Switch>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>
    </Switch>
  </Router>
</code>```

And now I get this error: Cannot read property 'createRouteFromReactElement' of undefined.  I noticed my import for Switch is not resolving but that's how you import Switch right?

Also not sure if all those routes should be sub routes of <Route path="/" component={HomePageContainer}>?  Note that I removed the <IndexRoute /> per suggestions too.

答:
React Router V4 is split out into two packages. One for Web (DOM) and one for Native.

Therefore, you don’t need the react-router dependency, just react-router-dom.

So import the components from react-router-dom instead:

```<code>import { BrowserRouter, Route, Switch } from 'react-router-dom'
</code>```

You can then wrap your routes in a Switch so that only one route is matched.

If you put your details route above the other then it should match first:

```<code><BrowserRouter>
  <Switch>
    <Route exact path="/" component={HomePageContainer} />
    <Route path="/interviews/companies/:companyId/details" component={CompanyDetailContainer} />
    <Route path="/interviews/companies/:companyId" component={InterviewContainer} />
    <Route path="/about" component={About} />
    <Route path="/jobs" component={JobList} />
    <Route component={NotFound} />
  </Switch>
</BrowserRouter>
</code>```

Also note that with React Router V4, you don’t nest routes. Instead you can add additional routes within your components.

Title: Route is not matched

Body:
I can't figure out why this is not matching my route for the CompanyDetailContainer.  The route for Interview container works fine

      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
      <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />

so http://localhost:8080/interviews/companies/10 hits the interview route fine but http://localhost:8080/interviews/companies/501/details does not hit the companydetail route

UPDATE:

I'm using:

"react-router": "^3.0.0",
"react-router-dom": "^4.2.2",

original code:

import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Switch>
        <Route exact component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
        <Route exact component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      </Switch>
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
  </Router>

adding just exact to what I had didn't work:

import { IndexRoute, Router, Route, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>

  </Router>

Then I tried to add switch around it:

import { Router, Route, Switch, browserHistory } from 'react-router';

  <Router history={browserHistory} onUpdate={onUpdate}>
    <Switch>
      <Route path="/" component={HomePageContainer}>
        <Route component={InterviewContainer} exact name="interview" path="interviews/companies/:companyId" />
        <Route component={CompanyDetailContainer} exact name="companydetail" path="interviews/companies/:companyId/details" />
        <Route component={About} name="about" path="about" />
        <Route component={JobList} name="jobs" path="jobs" />
        <Route component={Container} path="/"  />
        <Route component={NotFound} path="*"  />
      </Route>
    </Switch>
  </Router>

And now I get this error: Cannot read property 'createRouteFromReactElement' of undefined.  I noticed my import for Switch is not resolving but that's how you import Switch right?

Also not sure if all those routes should be sub routes of <Route path="/" component={HomePageContainer}>?  Note that I removed the <IndexRoute /> per suggestions too.

Body:
React Router V4 is split out into two packages. One for Web (DOM) and one for Native.

Therefore, you don’t need the react-router dependency, just react-router-dom.

So import the components from react-router-dom instead:

import { BrowserRouter, Route, Switch } from 'react-router-dom'

You can then wrap your routes in a Switch so that only one route is matched.

If you put your details route above the other then it should match first:

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={HomePageContainer} />
    <Route path="/interviews/companies/:companyId/details" component={CompanyDetailContainer} />
    <Route path="/interviews/companies/:companyId" component={InterviewContainer} />
    <Route path="/about" component={About} />
    <Route path="/jobs" component={JobList} />
    <Route component={NotFound} />
  </Switch>
</BrowserRouter>

Also note that with React Router V4, you don’t nest routes. Instead you can add additional routes within your components.


问:
Azure / R-server - rxKmeans write file with no header
I'm doing a kmeans clustering in Azure / R-server and need to be able to write a file that does not have a header.

So far I've tried:

```<code>k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('CUST_ID'), overwrite = T
                , outColName = F
)
</code>```

And I get this error :

```<code>Error in rxuHandleClusterJobTryFailure(retObject, hpcServerJob, autoCleanup) :
  Error completing job on cluster:
Error : rxIsCharacterScalarNonEmpty(outColName) is not TRUE
</code>```

I've also tried:

```<code>k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('CUST_ID'), overwrite = T
                , header = F
)
</code>```

Which returns:

```<code>Error in rxuHandleClusterJobTryFailure(retObject, hpcServerJob, autoCleanup) :
  Error completing job on cluster:
Error in rxKmeansBase(formula = formula, data = data, outDataSource = outDataSource,  :
  unused argument (header = FALSE)
</code>```

Any other suggestions?

答:
The problem was that I was giving conflicting instructions in the file definition and the rxKmeans function.

I fixed it by omitting the header argument from the rxKmeans function and set firstRowIsColNames to FALSE.

```<code>kmeansFile <- paste('~/clusters/ClusterOutput.tsv', sep = '')
dfOut <- RxTextData(kmeansFile, fileSystem = hdfsFS, firstRowIsColNames = F)

k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('id_num'), overwrite = T
               # , outColName = F
               # , header = F
)
</code>```

Body:
I'm doing a kmeans clustering in Azure / R-server and need to be able to write a file that does not have a header.

So far I've tried:

k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('CUST_ID'), overwrite = T
                , outColName = F
)

And I get this error :

Error in rxuHandleClusterJobTryFailure(retObject, hpcServerJob, autoCleanup) :
  Error completing job on cluster:
Error : rxIsCharacterScalarNonEmpty(outColName) is not TRUE

I've also tried:

k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('CUST_ID'), overwrite = T
                , header = F
)

Which returns:

Error in rxuHandleClusterJobTryFailure(retObject, hpcServerJob, autoCleanup) :
  Error completing job on cluster:
Error in rxKmeansBase(formula = formula, data = data, outDataSource = outDataSource,  :
  unused argument (header = FALSE)

Any other suggestions?

Body:
The problem was that I was giving conflicting instructions in the file definition and the rxKmeans function.

I fixed it by omitting the header argument from the rxKmeans function and set firstRowIsColNames to FALSE.

kmeansFile <- paste('~/clusters/ClusterOutput.tsv', sep = '')
dfOut <- RxTextData(kmeansFile, fileSystem = hdfsFS, firstRowIsColNames = F)

k1 <- rxKmeans(formula = ~ var1 + var2 + var3, data = df, seed = 10, numClusters = 5
               , outFile = dfOut, extraVarsToWrite = c('id_num'), overwrite = T
               # , outColName = F
               # , header = F
)


问:
Possible bug in Boost 1.65.1. while running bootstrap.bat gcc
While running bootstrap.bat gcc after extracting it I got the next error in bootstrap.log:

```<code>...
 \boost_1_65_1\tools\build\src\engine>.\bootstrap\jam0 -f build.jam
 --toolset=gcc "--toolset-root= "
 ...found 161 targets...
 ...updating 3 targets...
 [MKDIR] bin.ntx86_64
 [COMPILE] bin.ntx86_64\b2.exe
 debugger.c: In function 'debug_start_child':
 debugger.c:1128:5: error:
 'for' loop initial declarations are only allowed in C99 mode
      for ( int i = 1; i < argc; ++i )
      ^
 debugger.c:1128:5: note: use option -std=c99 or -std=gnu99 to compile your code
 strings.c: In function 'string_rtrim':
 strings.c:195:5: warning: ISO C90 forbids mixed declarations and code
 [-Wpedantic]
      char * p = self->value + self->size - 1;
      ^
 ...
</code>```

Modifying boost_1_65_1\tools\build\src\engine\debugger.c:1128 I get a proper build.

I track the compilation command to boost_1_65_1\tools\build\src\engine\config_toolset.bat:204. So by adding --std=c99 I can also solve it (although I get warnings and compilation fails).

I didn't find a report at https://svn.boost.org/trac10/search?ticket=on.

Can someone with more experience confirm this? And report it, if necessary.

Windows 10 - 64bits.
Mingw-w64 (gcc 4.8.3).
Boost 1.65.1.

答:
There is a bug report for this problem: https://svn.boost.org/trac10/ticket/13252

I didn't file it, but now if anyone comes across this question and wonders if it has been reported, it has.

In the meantime while it's being addressed, I think that the easiest way to get past it is as Black Arrow suggested above, to go to the file: boost_1_65_1\tools\build\src\engine\debugger.c, line 1128, and change:

```<code>for ( int i = 1; i < argc; ++i )
</code>```

to:

```<code>int i;
for ( i = 1; i < argc; ++i )
</code>```

save it, then run bootsrtap gcc

Body:
While running bootstrap.bat gcc after extracting it I got the next error in bootstrap.log:

...
 \boost_1_65_1\tools\build\src\engine>.\bootstrap\jam0 -f build.jam
 --toolset=gcc "--toolset-root= "
 ...found 161 targets...
 ...updating 3 targets...
 [MKDIR] bin.ntx86_64
 [COMPILE] bin.ntx86_64\b2.exe
 debugger.c: In function 'debug_start_child':
 debugger.c:1128:5: error:
 'for' loop initial declarations are only allowed in C99 mode
      for ( int i = 1; i < argc; ++i )
      ^
 debugger.c:1128:5: note: use option -std=c99 or -std=gnu99 to compile your code
 strings.c: In function 'string_rtrim':
 strings.c:195:5: warning: ISO C90 forbids mixed declarations and code
 [-Wpedantic]
      char * p = self->value + self->size - 1;
      ^
 ...

Modifying boost_1_65_1\tools\build\src\engine\debugger.c:1128 I get a proper build.

I track the compilation command to boost_1_65_1\tools\build\src\engine\config_toolset.bat:204. So by adding --std=c99 I can also solve it (although I get warnings and compilation fails).

I didn't find a report at https://svn.boost.org/trac10/search?ticket=on.

Can someone with more experience confirm this? And report it, if necessary.

Windows 10 - 64bits.
Mingw-w64 (gcc 4.8.3).
Boost 1.65.1.

Body:
There is a bug report for this problem: https://svn.boost.org/trac10/ticket/13252

I didn't file it, but now if anyone comes across this question and wonders if it has been reported, it has.

In the meantime while it's being addressed, I think that the easiest way to get past it is as Black Arrow suggested above, to go to the file: boost_1_65_1\tools\build\src\engine\debugger.c, line 1128, and change:

for ( int i = 1; i < argc; ++i )

to:

int i;
for ( i = 1; i < argc; ++i )

save it, then run bootsrtap gcc


问:
Django multi host url configuration per app
I searched around here on SO for how I would setup different domains for apps within a single django project. e.g.: news.io, jobs.io, etc for a news, job, etc app within the main project.

The app will also have authentication where the user will need to remain signed in across the domains if this matters. e.g. - billing platforms, etc.

The recommendation was to use a MultiHostMiddleware found here which is obviously outdated.

Similarly, the other recommendation was to use django-multihost which is also really old.

I'm on Django 1.11 and Python 3.6. Is there anything more recent or better yet how would I roll my own?

答: I'm just getting into this myself, and from what I can tell django-tenant-schemas seems to be the best option.</p>


问:
jQuery Syntax Help
I'm looking for some help explaining exactly what this line of code does in jQuery;

```<code>myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
</code>```

I'm unfamiliar with the syntax and some of the operators used.

答:
settings.mySelector value hypothetically contains a Jquery selector (see http://api.jquery.com/category/selectors/, this part is fundamental in JQuery)

$(settings.mySelector, this) function (yes, $ is a function) searches for the element specified in settings.mySelector selector, given the current selection context this (see http://api.jquery.com/jQuery, this part is fundamental in JQuery)

$(settings.mySelector,this).css('display') gets the CSS 'display' property value of the selected element

$[...].css('display') === 'none' ? 'closed' : 'not-closed'; is what is called ternary operation: if css('display') === 'none' is true, it returns 'closed', otherwise returns 'not-closed'.

Finally, myString is concatenated (+=) with either 'closed' (if the element described in settings.mySelector is not displayed) or 'not-closed'

ContentLicense: CC BY-SA 2.5

Title: jQuery Syntax Help

Body:
I'm looking for some help explaining exactly what this line of code does in jQuery;

myString += $(settings.mySelector,this).css('display') === 'none' ? 'closed' : 'not-closed';

I'm unfamiliar with the syntax and some of the operators used.


问:
What's the best way of generating a random number in a discontinuous range?
Is there a better way than:

```<code>#define BOUND 7

int r;
int e = 1;

r = rand() % BOUND;

while (r == e){

    r = rand() % BOUND;
}
</code>```

for generating numbers in a range except for a value e?

答:
What you're asking for is generating a random number in the range [0, BOUND) excluding the value e

The algorithm explained here seems to be the best way to do it without using a loop.

Here is the C code:

```<code>#define BOUND 7

int r;
int e = 1;

r = rand() % (BOUND-1);

if (r >= e){
    r = r+1;
}
</code>```

So, you basically generate a value in the range [0, BOUND-1), and if the value is greater than or equal to the excluded value e, you increment the random number by one.

Keep in mind that using rand with % does not guarantee a strict uniform distribution across the generated numbers. For more info, check out this question/answers.

Body:
Is there a better way than:

#define BOUND 7

int r;
int e = 1;

r = rand() % BOUND;

while (r == e){

    r = rand() % BOUND;
}

for generating numbers in a range except for a value e?

Body:
What you're asking for is generating a random number in the range [0, BOUND) excluding the value e

The algorithm explained here seems to be the best way to do it without using a loop.

Here is the C code:

#define BOUND 7

int r;
int e = 1;

r = rand() % (BOUND-1);

if (r >= e){
    r = r+1;
}

So, you basically generate a value in the range [0, BOUND-1), and if the value is greater than or equal to the excluded value e, you increment the random number by one.

Keep in mind that using rand with % does not guarantee a strict uniform distribution across the generated numbers. For more info, check out this question/answers.


问:
Webhooks with Python and Django
I have a subscription model:

```<code>class Subscription(models.Model):

STATUS_CURRENT = ["trialing", "active"]

plan_amount = models.CharField(max_length=120, null=True, blank=True)
plan_id = models.CharField(max_length=120, null=True, blank=True)
subscription_id = models.CharField(max_length=120)
subscription_owner = models.OneToOneField(Provider, related_name='subscription')
cancel_at_period_end = models.BooleanField(default=False)
canceled_at = models.DateTimeField(blank=True, null=True)
current_period_end = models.DateTimeField(blank=True, null=True)
current_period_start = models.DateTimeField(blank=True, null=True)
ended_at = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=25)# trialing, active, past_due, canceled, or unpaid

def status_display(self):
    return self.status.replace("_", " ").title()

def __str__(self):
    return self.subscription_id
</code>```

I also have the following stripe webhook set up and have no problems with that:

```<code>@require_POST
@csrf_exempt
def subscription_cancelled_callback(request):
# Process webhook data in `request.body and parse it as JSON`
stripe_payload = json.loads(request.body)

print('cancelled')

return HttpResponse(status=200)
</code>```

What I am trying to achieve is update my subscription object for example update the status of the subscription in my backend with the json returned through the webhook, i.e "active" or "cancelled"

New to using webhooks but not sure how to update the object from the webhook json. Any pointers would be a great help.

This is an example of the webhook json on a test webhook:
    {
  "created": 1326853478,
  "livemode": false,
  "id": "evt_00000000000000",
  "type": "customer.subscription.deleted",
  "object": "event",
  "request": null,
  "pending_webhooks": 1,
  "api_version": "2017-02-14",
  "data": {
    "object": {
      "id": "sub_00000000000000",
      "object": "subscription",
      "application_fee_percent": null,
      "billing": "charge_automatically",
      "cancel_at_period_end": false,
      "canceled_at": null,
      "created": 1510580811,
      "current_period_end": 1513172811,
      "current_period_start": 1510580811,
      "customer": "cus_00000000000000",
      "discount": null,
      "ended_at": 1510598517,
      "items": {
        "object": "list",
        "data": [
          {
            "id": "si_BlEkx6XqXqAgh1",
            "object": "subscription_item",
            "created": 1510580811,
            "metadata": {
            },
            "plan": {
              "id": "pro-monthly",
              "object": "plan",
              "amount": 9999,
              "created": 1509374183,
              "currency": "usd",
              "interval": "month",
              "interval_count": 1,
              "livemode": false,
              "metadata": {
              },
              "name": "Pro Plan",
              "statement_descriptor": null,
              "trial_period_days": null
            },
            "quantity": 1
          }
        ],
        "has_more": false,
        "total_count": 1,
        "url": "/v1/subscription_items?subscription=sub_BlEk5E9CBuFdTJ"
      },
      "livemode": false,
      "metadata": {
      },
      "plan": {
        "id": "pro-monthly_00000000000000",
        "object": "plan",
        "amount": 9999,
        "created": 1509374183,
        "currency": "usd",
        "interval": "month",
        "interval_count": 1,
        "livemode": false,
        "metadata": {
        },
        "name": "Pro Plan",
        "statement_descriptor": null,
        "trial_period_days": null
      },
      "quantity": 1,
      "start": 1510580811,
      "status": "canceled",
      "tax_percent": null,
      "trial_end": null,
      "trial_start": null
    }
  }
}

答:
I assume stripe_json has the "id" fields which will be mapped to your model let say it is mapped to subscription_id and it also has status that you want to update on subscription model

```<code>stripe_payload = {"id": "some-id", "status": "cancelled"}
</code>```

then all you need to do is:

```<code>status = stripe_payload['status']
sub_id = stripr_payload['id']
Subscription.objects.filter(id=sub_id).update(**{"status": status})
</code>```

Title: Webhooks with Python and Django

Body:
I have a subscription model:

class Subscription(models.Model):

STATUS_CURRENT = ["trialing", "active"]

plan_amount = models.CharField(max_length=120, null=True, blank=True)
plan_id = models.CharField(max_length=120, null=True, blank=True)
subscription_id = models.CharField(max_length=120)
subscription_owner = models.OneToOneField(Provider, related_name='subscription')
cancel_at_period_end = models.BooleanField(default=False)
canceled_at = models.DateTimeField(blank=True, null=True)
current_period_end = models.DateTimeField(blank=True, null=True)
current_period_start = models.DateTimeField(blank=True, null=True)
ended_at = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=25)# trialing, active, past_due, canceled, or unpaid

def status_display(self):
    return self.status.replace("_", " ").title()

def __str__(self):
    return self.subscription_id

I also have the following stripe webhook set up and have no problems with that:

@require_POST
@csrf_exempt
def subscription_cancelled_callback(request):
# Process webhook data in `request.body and parse it as JSON`
stripe_payload = json.loads(request.body)

print('cancelled')

return HttpResponse(status=200)

What I am trying to achieve is update my subscription object for example update the status of the subscription in my backend with the json returned through the webhook, i.e "active" or "cancelled"

New to using webhooks but not sure how to update the object from the webhook json. Any pointers would be a great help.

This is an example of the webhook json on a test webhook:
    {
  "created": 1326853478,
  "livemode": false,
  "id": "evt_00000000000000",
  "type": "customer.subscription.deleted",
  "object": "event",
  "request": null,
  "pending_webhooks": 1,
  "api_version": "2017-02-14",
  "data": {
    "object": {
      "id": "sub_00000000000000",
      "object": "subscription",
      "application_fee_percent": null,
      "billing": "charge_automatically",
      "cancel_at_period_end": false,
      "canceled_at": null,
      "created": 1510580811,
      "current_period_end": 1513172811,
      "current_period_start": 1510580811,
      "customer": "cus_00000000000000",
      "discount": null,
      "ended_at": 1510598517,
      "items": {
        "object": "list",
        "data": [
          {
            "id": "si_BlEkx6XqXqAgh1",
            "object": "subscription_item",
            "created": 1510580811,
            "metadata": {
            },
            "plan": {
              "id": "pro-monthly",
              "object": "plan",
              "amount": 9999,
              "created": 1509374183,
              "currency": "usd",
              "interval": "month",
              "interval_count": 1,
              "livemode": false,
              "metadata": {
              },
              "name": "Pro Plan",
              "statement_descriptor": null,
              "trial_period_days": null
            },
            "quantity": 1
          }
        ],
        "has_more": false,
        "total_count": 1,
        "url": "/v1/subscription_items?subscription=sub_BlEk5E9CBuFdTJ"
      },
      "livemode": false,
      "metadata": {
      },
      "plan": {
        "id": "pro-monthly_00000000000000",
        "object": "plan",
        "amount": 9999,
        "created": 1509374183,
        "currency": "usd",
        "interval": "month",
        "interval_count": 1,
        "livemode": false,
        "metadata": {
        },
        "name": "Pro Plan",
        "statement_descriptor": null,
        "trial_period_days": null
      },
      "quantity": 1,
      "start": 1510580811,
      "status": "canceled",
      "tax_percent": null,
      "trial_end": null,
      "trial_start": null
    }
  }
}

Body:
I assume stripe_json has the "id" fields which will be mapped to your model let say it is mapped to subscription_id and it also has status that you want to update on subscription model

stripe_payload = {"id": "some-id", "status": "cancelled"}

then all you need to do is:

status = stripe_payload['status']
sub_id = stripr_payload['id']
Subscription.objects.filter(id=sub_id).update(**{"status": status})


问:
How to use rails ActiveRecord to perform a left join of a Model with a subquery
I am using rails 5.  When I perform the following straight SQL query in the rails console, I get the following expected result:

```<code>    2.3.5 :053 >   w = ActiveRecord::Base.connection.exec_query("SELECT * FROM students s LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = s.id")
   (0.5ms)  SELECT * FROM students s LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = s.id
 => #<ActiveRecord::Result:0x00000000051e1518 @columns=["id", "name", "cwid", "email", "phone", "company", "role", "advisor", "advisor_email", "mentor", "created_at", "updated_at", "student_id", "has_urgent", "last_contact"], @rows=[[1, "Johnny Smith", "71419940", "jsmith@gmail.com", "8435550001", "foxtrot", "mentor", "John I. Moore, Jr.", "john.moore@citadel.edu", "", "2017-11-13 14:58:50.128114", "2017-11-13 14:58:50.128168", nil, nil, nil], [2, "Shelly", "12345678", "shelly@gmail.com", "8435550002", "bravo", "mentee", "Michael P. Verdicchio", "mv@citadel.edu", "Johnny Smith", "2017-11-13 14:58:50.160195", "2017-11-13 14:58:50.160243", "2", "t", "2017-11-13 14:58:50.210105"], [3, "Max", "87654321", "max@gmail.com", "8435550003", "palmetto", "unassigned", "Mei-Qin Chen", "mei.chen@citadel.edu", "", "2017-11-13 14:58:50.179220", "2017-11-13 14:58:50.179258", nil, nil, nil], [4, "George", "87654325", "george@gmail.com", "8435550004", "palmetto", "mentee", "Deepti Joshi", "djoshi@citadel.edu", "Johnny Smith", "2017-11-13 14:58:50.189733", "2017-11-13 14:58:50.189762", "4", "f", "2017-11-03 14:58:50.260914"]], @hash_rows=nil, @column_types={}>
</code>```

However, this returns an ActiveRecord::Result type, but I really want is to use the Rails ActiveRecord to do the same query but return an ActiveRecord::Relation instead, I thought like so:

```<code>2.3.5 :054 > w = Student.joins("LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = students.id")
  Student Load (0.5ms)  SELECT  "students".* FROM "students" LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = students.id LIMIT ?  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Student id: 1, name: "Johnny Smith", cwid: "71419940", email: "jsmith@gmail.com", phone: "8435550001", company: "foxtrot", role: "mentor", advisor: "John I. Moore, Jr.", advisor_email: "john.moore@citadel.edu", mentor: "", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 2, name: "Shelly", cwid: "12345678", email: "shelly@gmail.com", phone: "8435550002", company: "bravo", role: "mentee", advisor: "Michael P. Verdicchio", advisor_email: "mv@citadel.edu", mentor: "Johnny Smith", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 3, name: "Max", cwid: "87654321", email: "max@gmail.com", phone: "8435550003", company: "palmetto", role: "unassigned", advisor: "Mei-Qin Chen", advisor_email: "mei.chen@citadel.edu", mentor: "", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 4, name: "George", cwid: "87654325", email: "george@gmail.com", phone: "8435550004", company: "palmetto", role: "mentee", advisor: "Deepti Joshi", advisor_email: "djoshi@citadel.edu", mentor: "Johnny Smith", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">]>
</code>```

For this second approach, the Right table columns do not appear in the result, even though the generated SQL looks very similar.  I am new to Rails and ActiveRecord, so if someone can help me understand why these two results are different and what I should do to make the second ActiveRecord query work like the straight SQL query I would appreciate it.

答:
If you are using rails 5 then use left_joins or left_outer_joins.
Try this and let me know if it work for you.

Student.left_outer_joins(:reports).select("student.*,  MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact").group("student.id").

If you want to go with your first approach then these methods may helpful for you.

result.columns #Get the column names of the result.

result.rows #Get the record values of the result.

result.to_hash #Get an array of hashes representing the result (column => value)

#ActiveRecord::Result also includes Enumerable.

Body:
I am using rails 5.  When I perform the following straight SQL query in the rails console, I get the following expected result:

    2.3.5 :053 >   w = ActiveRecord::Base.connection.exec_query("SELECT * FROM students s LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = s.id")
   (0.5ms)  SELECT * FROM students s LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = s.id
 => #<ActiveRecord::Result:0x00000000051e1518 @columns=["id", "name", "cwid", "email", "phone", "company", "role", "advisor", "advisor_email", "mentor", "created_at", "updated_at", "student_id", "has_urgent", "last_contact"], @rows=[[1, "Johnny Smith", "71419940", "jsmith@gmail.com", "8435550001", "foxtrot", "mentor", "John I. Moore, Jr.", "john.moore@citadel.edu", "", "2017-11-13 14:58:50.128114", "2017-11-13 14:58:50.128168", nil, nil, nil], [2, "Shelly", "12345678", "shelly@gmail.com", "8435550002", "bravo", "mentee", "Michael P. Verdicchio", "mv@citadel.edu", "Johnny Smith", "2017-11-13 14:58:50.160195", "2017-11-13 14:58:50.160243", "2", "t", "2017-11-13 14:58:50.210105"], [3, "Max", "87654321", "max@gmail.com", "8435550003", "palmetto", "unassigned", "Mei-Qin Chen", "mei.chen@citadel.edu", "", "2017-11-13 14:58:50.179220", "2017-11-13 14:58:50.179258", nil, nil, nil], [4, "George", "87654325", "george@gmail.com", "8435550004", "palmetto", "mentee", "Deepti Joshi", "djoshi@citadel.edu", "Johnny Smith", "2017-11-13 14:58:50.189733", "2017-11-13 14:58:50.189762", "4", "f", "2017-11-03 14:58:50.260914"]], @hash_rows=nil, @column_types={}>

However, this returns an ActiveRecord::Result type, but I really want is to use the Rails ActiveRecord to do the same query but return an ActiveRecord::Relation instead, I thought like so:

2.3.5 :054 > w = Student.joins("LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = students.id")
  Student Load (0.5ms)  SELECT  "students".* FROM "students" LEFT JOIN (SELECT student_id, MAX(urgent) AS has_urgent,MAX(created_at) AS last_contact FROM reports GROUP BY student_id) r ON r.student_id = students.id LIMIT ?  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Student id: 1, name: "Johnny Smith", cwid: "71419940", email: "jsmith@gmail.com", phone: "8435550001", company: "foxtrot", role: "mentor", advisor: "John I. Moore, Jr.", advisor_email: "john.moore@citadel.edu", mentor: "", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 2, name: "Shelly", cwid: "12345678", email: "shelly@gmail.com", phone: "8435550002", company: "bravo", role: "mentee", advisor: "Michael P. Verdicchio", advisor_email: "mv@citadel.edu", mentor: "Johnny Smith", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 3, name: "Max", cwid: "87654321", email: "max@gmail.com", phone: "8435550003", company: "palmetto", role: "unassigned", advisor: "Mei-Qin Chen", advisor_email: "mei.chen@citadel.edu", mentor: "", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">, #<Student id: 4, name: "George", cwid: "87654325", email: "george@gmail.com", phone: "8435550004", company: "palmetto", role: "mentee", advisor: "Deepti Joshi", advisor_email: "djoshi@citadel.edu", mentor: "Johnny Smith", created_at: "2017-11-13 14:58:50", updated_at: "2017-11-13 14:58:50">]>

For this second approach, the Right table columns do not appear in the result, even though the generated SQL looks very similar.  I am new to Rails and ActiveRecord, so if someone can help me understand why these two results are different and what I should do to make the second ActiveRecord query work like the straight SQL query I would appreciate it.


问:
Wrap enum variants in IntoFuture?
I'm trying to compile something like the following code. It seems like I need to help it understand that I want all of the match arms to be taken as futures::future::IntoFuture, since that's what the outer and_then is expecting from the callback/closure/delegate.

For now all of the arms are stubbed with the simplest enum variant, NothingUseful(), but my goal is ultimately to take various actions depending on the returned HTTP status code and/or body contents when applicable.

```<code>extern crate futures;
extern crate hyper;
extern crate tokio_core;

use futures::{future, Future, Stream};
use hyper::{Client, Error as HyperError, Response, StatusCode, Uri};
use tokio_core::reactor::Core;

struct RecurseUrl {
    uri: Uri,
    remaining_attempts: u8,
}

enum FetchResult {
    SimpleData(u16),
    RecurseUrls(Vec<RecurseUrl>),
    NothingUseful(),
}

fn handle_redirect(res: &Response) -> future::FutureResult<FetchResult, HyperError> {
    future::ok(FetchResult::NothingUseful())
}

fn main() {
    let url = "http://someurl.com"
        .parse()
        .expect("Unable to parse URL");

    let mut core = Core::new().expect("Unable to instantiate Tokio Core");
    let client = Client::new(&core.handle());

    let work = client.get(url).and_then(|res| {

        match res.status() {
            StatusCode::TemporaryRedirect => handle_redirect(&res),
            StatusCode::PermanentRedirect => handle_redirect(&res),
            StatusCode::Ok => {
                res.body().concat2().and_then(move |body| {
                    Ok(FetchResult::NothingUseful())
                })
            },
            _ => {
                Ok(FetchResult::NothingUseful())
            }
        }
    });

    core.run(work).expect("Problem running work");
}
</code>```

    error[E0308]: match arms have incompatible types
  --> main.rs:34:13
   |
34 | /             match res.status() {
35 | |                 StatusCode::TemporaryRedirect => handle_redirect(&res),
36 | |                 StatusCode::PermanentRedirect => handle_redirect(&res),
37 | |                 StatusCode::Ok => {
...  |
44 | |                 }
45 | |             }
   | |_____________^ expected struct `futures::FutureResult`, found struct `futures::AndThen`
   |
   = note: expected type `futures::FutureResult<FetchResult, hyper::Error>`
              found type `futures::AndThen<futures::stream::Concat2<hyper::Body>, std::result::Result<FetchResult, hyper::Error>, [closure@main.rs:38:51: 40:22]>`
note: match arm with an incompatible type
  --> main.rs:37:35
   |
37 |                   StatusCode::Ok => {
   |  ___________________________________^
38 | |                     res.body().concat2().and_then(move |body| {
39 | |                         Ok(FetchResult::NothingUseful())
40 | |                     })
41 | |                 },
   | |_________________^
```

答:
I want all of the match arms to be taken as futures::future::IntoFuture, since that's what the outer and_then is expecting from the callback/closure/delegate.

and_then expects that the return type of the closure to be a single concrete type that implements the trait IntoFuture. Your match returns multiple concrete types — this is not allowed in Rust as the compiler wouldn't know how much stack space to allocate.

You need to convert all the various types into a single unified type. The easiest is to box them all, creating a trait object (Box<Future<Item = FetchResult, Error = hyper::Error>>):

```<code>let work = client.get(url).and_then(|res| -> Box<Future<Item = FetchResult, Error = hyper::Error>> {
        match res.status() {
            StatusCode::TemporaryRedirect => Box::new(handle_redirect(&res)),
            StatusCode::PermanentRedirect => Box::new(handle_redirect(&res)),
            StatusCode::Ok => Box::new(
                res.body()
                    .concat2()
                    .map(move |body| FetchResult::NothingUseful()),
            ),
            _ => Box::new(future::ok(FetchResult::NothingUseful())),
        }
    },
);
</code>```

You could also create your own type and implement Future for that. This allows you to avoid any allocation:

```<code>#[macro_use]
extern crate futures;
extern crate hyper;
extern crate tokio_core;

use futures::{Async, Future, Poll};
use hyper::client::{FutureResponse, HttpConnector};
use hyper::{Client, Response, StatusCode, Uri};
use tokio_core::reactor::Core;

struct RecurseUrl {
    client: Client<HttpConnector>,
    future: FutureResponse,
    remaining_attempts: u8,
}

impl RecurseUrl {
    fn new(client: Client<HttpConnector>, uri: Uri) -> Self {
        let future = client.get(uri);
        Self {
            client,
            future,
            remaining_attempts: 3,
        }
    }
}

impl Future for RecurseUrl {
    type Item = hyper::Response;
    type Error = hyper::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let response = try_ready!(self.future.poll());

        match response.status() {
            StatusCode::TemporaryRedirect | StatusCode::PermanentRedirect => {
                if self.remaining_attempts == 0 {
                    panic!("return a real error")
                }

                let next_uri = get_redirect_uri_from_response(&response);
                let next_future = self.client.get(next_uri);
                self.future = next_future;
                self.remaining_attempts -= 1;

                Ok(Async::NotReady)
            }
            StatusCode::Ok => Ok(Async::Ready(response)),
            _ => panic!("return a real error"),
        }
    }
}

fn get_redirect_uri_from_response(_response: &Response) -> Uri {
    unimplemented!()
}

fn main() {
    let uri = "http://someurl.com".parse().expect("Unable to parse URL");

    let mut core = Core::new().expect("Unable to instantiate Tokio Core");
    let client = Client::new(&core.handle());

    let work = RecurseUrl::new(client, uri);
    core.run(work).expect("Problem running work");
}
</code>```

You could then handle reading URIs out of the bodies of the responses with something like this:

```<code>use futures::stream::{Stream, FuturesUnordered, Concat2};

struct WebCrawler {
    client: Client<HttpConnector>,
    to_fetch: FuturesUnordered<FutureResponse>,
    fetching: FuturesUnordered<Concat2<hyper::Body>>,
}

impl WebCrawler {
    fn new(client: Client<HttpConnector>, uri: Uri) -> Self {
        let future = client.get(uri);
        let to_fetch: FuturesUnordered<_> = Some(future).into_iter().collect();

        Self {
            client,
            to_fetch,
            fetching: FuturesUnordered::new(),
        }
    }
}

impl Stream for WebCrawler {
    type Item = hyper::Chunk;
    type Error = hyper::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        loop {
            match self.to_fetch.poll()? {
                Async::Ready(Some(s)) => {
                    self.fetching.push(s.body().concat2())
                },
                Async::Ready(None) | Async::NotReady => break,
            }
        }

        loop {
            match self.fetching.poll()? {
                Async::Ready(Some(body)) => {
                    for uri in get_uris_from_body(&body) {
                        self.to_fetch.push(self.client.get(uri));
                    }
                    return Ok(Async::Ready(Some(body)));
                },
                Async::Ready(None) | Async::NotReady => break,
            }
        }

        if self.to_fetch.is_empty() && self.fetching.is_empty() {
            Ok(Async::Ready(None))
        } else {
            Ok(Async::NotReady)
        }
    }
}

fn get_uris_from_body(_body: &hyper::Chunk) -> Vec<Uri> {
    unimplemented!()
}
</code>```

This implementation was cribbed from that of BufferUnordered. You'd need to enhance it to pass the depth of the crawl around and manage it, but I think this is a good sketch of what is possible.

Title: Wrap enum variants in IntoFuture?

Body:
I'm trying to compile something like the following code. It seems like I need to help it understand that I want all of the match arms to be taken as futures::future::IntoFuture, since that's what the outer and_then is expecting from the callback/closure/delegate.

For now all of the arms are stubbed with the simplest enum variant, NothingUseful(), but my goal is ultimately to take various actions depending on the returned HTTP status code and/or body contents when applicable.

extern crate futures;
extern crate hyper;
extern crate tokio_core;

use futures::{future, Future, Stream};
use hyper::{Client, Error as HyperError, Response, StatusCode, Uri};
use tokio_core::reactor::Core;

struct RecurseUrl {
    uri: Uri,
    remaining_attempts: u8,
}

enum FetchResult {
    SimpleData(u16),
    RecurseUrls(Vec<RecurseUrl>),
    NothingUseful(),
}

fn handle_redirect(res: &Response) -> future::FutureResult<FetchResult, HyperError> {
    future::ok(FetchResult::NothingUseful())
}

fn main() {
    let url = "http://someurl.com"
        .parse()
        .expect("Unable to parse URL");

    let mut core = Core::new().expect("Unable to instantiate Tokio Core");
    let client = Client::new(&core.handle());

    let work = client.get(url).and_then(|res| {

        match res.status() {
            StatusCode::TemporaryRedirect => handle_redirect(&res),
            StatusCode::PermanentRedirect => handle_redirect(&res),
            StatusCode::Ok => {
                res.body().concat2().and_then(move |body| {
                    Ok(FetchResult::NothingUseful())
                })
            },
            _ => {
                Ok(FetchResult::NothingUseful())
            }
        }
    });

    core.run(work).expect("Problem running work");
}

    error[E0308]: match arms have incompatible types
  --> main.rs:34:13
   |
34 | /             match res.status() {
35 | |                 StatusCode::TemporaryRedirect => handle_redirect(&res),
36 | |                 StatusCode::PermanentRedirect => handle_redirect(&res),
37 | |                 StatusCode::Ok => {
...  |
44 | |                 }
45 | |             }
   | |_____________^ expected struct `futures::FutureResult`, found struct `futures::AndThen`
   |
   = note: expected type `futures::FutureResult<FetchResult, hyper::Error>`
              found type `futures::AndThen<futures::stream::Concat2<hyper::Body>, std::result::Result<FetchResult, hyper::Error>, [closure@main.rs:38:51: 40:22]>`
note: match arm with an incompatible type
  --> main.rs:37:35
   |
37 |                   StatusCode::Ok => {
   |  ___________________________________^
38 | |                     res.body().concat2().and_then(move |body| {
39 | |                         Ok(FetchResult::NothingUseful())
40 | |                     })
41 | |                 },
   | |_________________^

Body:
I want all of the match arms to be taken as futures::future::IntoFuture, since that's what the outer and_then is expecting from the callback/closure/delegate.

and_then expects that the return type of the closure to be a single concrete type that implements the trait IntoFuture. Your match returns multiple concrete types — this is not allowed in Rust as the compiler wouldn't know how much stack space to allocate.

You need to convert all the various types into a single unified type. The easiest is to box them all, creating a trait object (Box<Future<Item = FetchResult, Error = hyper::Error>>):

let work = client.get(url).and_then(|res| -> Box<Future<Item = FetchResult, Error = hyper::Error>> {
        match res.status() {
            StatusCode::TemporaryRedirect => Box::new(handle_redirect(&res)),
            StatusCode::PermanentRedirect => Box::new(handle_redirect(&res)),
            StatusCode::Ok => Box::new(
                res.body()
                    .concat2()
                    .map(move |body| FetchResult::NothingUseful()),
            ),
            _ => Box::new(future::ok(FetchResult::NothingUseful())),
        }
    },
);

You could also create your own type and implement Future for that. This allows you to avoid any allocation:

#[macro_use]
extern crate futures;
extern crate hyper;
extern crate tokio_core;

use futures::{Async, Future, Poll};
use hyper::client::{FutureResponse, HttpConnector};
use hyper::{Client, Response, StatusCode, Uri};
use tokio_core::reactor::Core;

struct RecurseUrl {
    client: Client<HttpConnector>,
    future: FutureResponse,
    remaining_attempts: u8,
}

impl RecurseUrl {
    fn new(client: Client<HttpConnector>, uri: Uri) -> Self {
        let future = client.get(uri);
        Self {
            client,
            future,
            remaining_attempts: 3,
        }
    }
}

impl Future for RecurseUrl {
    type Item = hyper::Response;
    type Error = hyper::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let response = try_ready!(self.future.poll());

        match response.status() {
            StatusCode::TemporaryRedirect | StatusCode::PermanentRedirect => {
                if self.remaining_attempts == 0 {
                    panic!("return a real error")
                }

                let next_uri = get_redirect_uri_from_response(&response);
                let next_future = self.client.get(next_uri);
                self.future = next_future;
                self.remaining_attempts -= 1;

                Ok(Async::NotReady)
            }
            StatusCode::Ok => Ok(Async::Ready(response)),
            _ => panic!("return a real error"),
        }
    }
}

fn get_redirect_uri_from_response(_response: &Response) -> Uri {
    unimplemented!()
}

fn main() {
    let uri = "http://someurl.com".parse().expect("Unable to parse URL");

    let mut core = Core::new().expect("Unable to instantiate Tokio Core");
    let client = Client::new(&core.handle());

    let work = RecurseUrl::new(client, uri);
    core.run(work).expect("Problem running work");
}

You could then handle reading URIs out of the bodies of the responses with something like this:

use futures::stream::{Stream, FuturesUnordered, Concat2};

struct WebCrawler {
    client: Client<HttpConnector>,
    to_fetch: FuturesUnordered<FutureResponse>,
    fetching: FuturesUnordered<Concat2<hyper::Body>>,
}

impl WebCrawler {
    fn new(client: Client<HttpConnector>, uri: Uri) -> Self {
        let future = client.get(uri);
        let to_fetch: FuturesUnordered<_> = Some(future).into_iter().collect();

        Self {
            client,
            to_fetch,
            fetching: FuturesUnordered::new(),
        }
    }
}

impl Stream for WebCrawler {
    type Item = hyper::Chunk;
    type Error = hyper::Error;

    fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
        loop {
            match self.to_fetch.poll()? {
                Async::Ready(Some(s)) => {
                    self.fetching.push(s.body().concat2())
                },
                Async::Ready(None) | Async::NotReady => break,
            }
        }

        loop {
            match self.fetching.poll()? {
                Async::Ready(Some(body)) => {
                    for uri in get_uris_from_body(&body) {
                        self.to_fetch.push(self.client.get(uri));
                    }
                    return Ok(Async::Ready(Some(body)));
                },
                Async::Ready(None) | Async::NotReady => break,
            }
        }

        if self.to_fetch.is_empty() && self.fetching.is_empty() {
            Ok(Async::Ready(None))
        } else {
            Ok(Async::NotReady)
        }
    }
}

fn get_uris_from_body(_body: &hyper::Chunk) -> Vec<Uri> {
    unimplemented!()
}

This implementation was cribbed from that of BufferUnordered. You'd need to enhance it to pass the depth of the crawl around and manage it, but I think this is a good sketch of what is possible.


问:
Passing imageView to new activity imageView
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?</p>

```<code>    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);
</code>```

答:
Possibly you miss the knowledge of how getting results from another Activity, please see the official documentation.
The second Activity that have to receive the information, needs to be called by a method called onActivityResult(example from the link)

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }
    }
}
</code>```

Usually in real life scenarios developers use  EventBus or Otto or RxJava (steep learning curve this last one)

Body:
Currently, my app allows the user to click on a "default avatar pic" and then select from a group of images. This image is then returned to the first activity via "startActivityForResult". My next task is to take the image that is now set in the first activity and send it to a third activity when the user presses the "submit button". Right now, I'm trying the below code, but it's not working as I don't know which image is going to be selected by the user until it's selected. Can anyone help me out here?

    findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.select_avatar);
            intent.putExtra("IMAGE", bitmap);
            startActivity(intent);
        }
    });

             //second activity
             Bitmap bitmap = intent.getParcelableExtra("Bitmap");
             imageViewAvatar.findViewById(R.id.imageViewFinalAvatar);
             imageViewAvatar.setImageBitmap(bitmap);

Body:
Possibly you miss the knowledge of how getting results from another Activity, please see the official documentation.
The second Activity that have to receive the information, needs to be called by a method called onActivityResult(example from the link)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == PICK_CONTACT_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // The user picked a contact.
            // The Intent's data Uri identifies which contact was selected.

            // Do something with the contact here (bigger example below)
        }
    }
}

Usually in real life scenarios developers use  EventBus or Otto or RxJava (steep learning curve this last one)


问:
Simple 3D Array C++
I am a novice in C++ and I am trying to create a simple static 3 Dimensional Array and then print it out in console.

Here is my current code:

```<code>#include <iostream>
using namespace std;

int main()
{
  const int MAX_ROW = 2;
  const int MAX_COL = 2;
  const int MAX_HEIGHT = 2;

  int MyArray[MAX_ROW][MAX_COL][MAX_HEIGHT] = { {1,1},
                           {2,10},
                           {3,15},
                           {4,20},
                           {5,25},
                           {6,30},
                           {7,35},
                           {8,40} };

  for(int Row = 0; Row < MAX_ROW; ++Row)
  {
   for(int Col =0; Col < MAX_COL; ++Col)
   {
    for(int Height = 0; Height < MAX_HEIGHT; ++Height)
     {
      cout << "Integer["<< Row << "][" << Col << "][" << Height << "] = " << MyArray[MAX_ROW][MAX_COL][MAX_HEIGHT] << endl;
     }
    }
   }

  return 0;
}
</code>```

When I compile the compiler notifies me stating "error: too many initializers for ‘int [2][2][2]"

Other questions have used pointers which I am not familiar with.

Thank you in advance!

Edit: The syntax is wrong so I have corrected it with the correct corresponding code as answered below. Now in the output of the program each array space is 32767. A full integer space instead of the assigned values. Can anybody address this in their answer? I have not changed any code except my initialisation of the array.

答:
Apart from wrong array initialization as others have pointed out you also have an error in printing. You always print the same element that doesn't even exist (which is undefined behaviour).</p>

```<code>cout << "Integer["<< Row << "][" << Col << "][" << Height << "] = " << MyArray[Row][Col][Height] << endl;
</code>```

Title: Simple 3D Array C++

Body:
I am a novice in C++ and I am trying to create a simple static 3 Dimensional Array and then print it out in console.

Here is my current code:

#include <iostream>
using namespace std;

int main()
{
  const int MAX_ROW = 2;
  const int MAX_COL = 2;
  const int MAX_HEIGHT = 2;

  int MyArray[MAX_ROW][MAX_COL][MAX_HEIGHT] = { {1,1},
                           {2,10},
                           {3,15},
                           {4,20},
                           {5,25},
                           {6,30},
                           {7,35},
                           {8,40} };

  for(int Row = 0; Row < MAX_ROW; ++Row)
  {
   for(int Col =0; Col < MAX_COL; ++Col)
   {
    for(int Height = 0; Height < MAX_HEIGHT; ++Height)
     {
      cout << "Integer["<< Row << "][" << Col << "][" << Height << "] = " << MyArray[MAX_ROW][MAX_COL][MAX_HEIGHT] << endl;
     }
    }
   }

  return 0;
}

When I compile the compiler notifies me stating "error: too many initializers for ‘int [2][2][2]"

Other questions have used pointers which I am not familiar with.

Thank you in advance!

Edit: The syntax is wrong so I have corrected it with the correct corresponding code as answered below. Now in the output of the program each array space is 32767. A full integer space instead of the assigned values. Can anybody address this in their answer? I have not changed any code except my initialisation of the array.

Body:
Apart from wrong array initialization as others have pointed out you also have an error in printing. You always print the same element that doesn't even exist (which is undefined behaviour).

cout << "Integer["<< Row << "][" << Col << "][" << Height << "] = " << MyArray[Row][Col][Height] << endl;


问:
Why not volatile on System.Double and System.Long?
A question like mine has been asked, but mine is a bit different.  The question is, "Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

On first blush, I answered my colleague, "Well, on a 32-bit machine, those types take at least two ticks to even enter the processor, and the .Net framework has the intention of abstracting away processor-specific details like that."  To which he responds, "It's not abstracting anything if it's preventing you from using a feature because of a processor-specific problem!"

He's implying that a processor-specific detail should not show up to a person using a framework that "abstracts" details like that away from the programmer.  So, the framework (or C#) should abstract away those and do what it needs to do to offer the same guarantees for System.Double, etc. (whether that's a Semaphore, memory barrier, or whatever).  I argued that the framework shouldn't add the overhead of a Semaphore on volatile, because the programmer isn't expecting such overhead with such a keyword, because a Semaphore isn't necessary for the 32-bit types.  The greater overhead for the 64-bit types might come as a surprise, so, better for the .Net framework to just not allow it, and make you do your own Semaphore on larger types if the overhead is acceptable.

That led to our investigating what the volatile keyword is all about.  (see this page).  That page states, in the notes:

In C#, using the volatile modifier on a field guarantees that all access to that field uses VolatileRead or VolatileWrite.

Hmmm.....VolatileRead and VolatileWrite both support our 64-bit types!! My question, then, is,

"Why is the volatile keyword not allowed in C# on types System.Double and System.Int64, etc.?"

答:
Yes. Reason is that you even can't read double or long in one operation. I agree that it is poor abstraction. I have a feeling that reason was that reading them atomically requires effort and it would be too smart for compiler. So they let you choose the best solution: locking, Interlocked, etc.

Interesting thing is that they can actually be read atomically on 32 bit using MMX registers. This is what java JIT compiler does. And they can be read atomically on 64 bit machine. So I think it is serious flaw in design.


问:
Search only those XMLs when a particular element occurs multiple times in Marklogic
I am trying to search for document XMLs in Marklogic which have the elements <document> more than once. Following is the structure of one such document XML i want to retrieve:

<root>
    <documents>
        <document>
            <id>1</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
        <document>
            <id>2</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
        ....
        ...
        ..
        .
        <document>
            <id>3</id>
            <name>roy</name>
            <otherData></otherData>
        </document>

    </documents>
</root>
```

<p>I do not want to retrieve the XMLs which are of the following structure:</p>

```<root>
    <documents>
        <document>
            <id>3</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
    </documents>
</root>
```

I can search for existence or minimum one using element-query with xs:QName("document"), but not sure how to go about searching with more than one.

Any help would be much appreciated.

答:
There is no real simple way of doing this that scales well in MarkLogic. The easiest way out is by enriching the documents, adding a count attribute to the <documents> element, and keeping it up to date each time you touch the document. You can then do a straight-forward range index on the count attribute, and directly get what you are after.

HTH!

Body:
I am trying to search for document XMLs in Marklogic which have the elements <document> more than once. Following is the structure of one such document XML i want to retrieve:

<root>
    <documents>
        <document>
            <id>1</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
        <document>
            <id>2</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
        ....
        ...
        ..
        .
        <document>
            <id>3</id>
            <name>roy</name>
            <otherData></otherData>
        </document>

    </documents>
</root>

I do not want to retrieve the XMLs which are of the following structure:

<root>
    <documents>
        <document>
            <id>3</id>
            <name>roy</name>
            <otherData></otherData>
        </document>
    </documents>
</root>

I can search for existence or minimum one using element-query with xs:QName("document"), but not sure how to go about searching with more than one.

Any help would be much appreciated.


问:
Using linked Resources in Custom REST Controller with Spring REST JPA
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

```<code>@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}
</code>```

and users Own Projects:

```<code>@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}
</code>```

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

```<code>@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}
</code>```

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

```<code>{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}
</code>```

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

答:
I would suggest that what you should really be doing is:

```<code>http://localhost:9999/api/users/1/projects?formField1=data1&formField2=Otherdata
</code>```

By enable Spring Data's web support you can have the path variable automatically bound to the entity instance.

```<code>@RequestMapping(value = "users/{id}/projects", method = RequestMethod.POST)
        public HttpEntity<Project> createProject(
                            @PathVariable("id") User user,
                            @RequestParam String formField1,
                            @RequestParam String formfield2)
{

}
</code>```

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web

Body:
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}

and users Own Projects:

@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

Body:
I would suggest that what you should really be doing is:

http://localhost:9999/api/users/1/projects?formField1=data1&formField2=Otherdata

By enable Spring Data's web support you can have the path variable automatically bound to the entity instance.

@RequestMapping(value = "users/{id}/projects", method = RequestMethod.POST)
        public HttpEntity<Project> createProject(
                            @PathVariable("id") User user,
                            @RequestParam String formField1,
                            @RequestParam String formfield2)
{

}

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web


问:
Hide with jquery Qty field if the table row contains text
So I know this is a weird thing to do but I am trying to search for a phrase in a table's row "Product Name".
When it finds it I want to hide the field with the title="Qty" ( id can be different every time)

Here is what I tried:

```<code>var thebook = $("tr:contains('Product Name')");
jQuery(thebook).children(input[title='Qty']).hide();
</code>```

What am I doing wrong?

答:
input[title='Qty'] should be in quotes, like "input[title='Qty']"

Without seeing your full code, I can't be sure there aren't other problems, but here's an example of this working in which I used .find() rather than .children() to search all the way down the descendent chain:

$("tr:contains('Product B')").find("input[title='Qty']").hide();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Product A</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
  <tr>
    <td>Product B</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
  <tr>
    <td>Product C</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
</table></code>```

Body:
So I know this is a weird thing to do but I am trying to search for a phrase in a table's row "Product Name".
When it finds it I want to hide the field with the title="Qty" ( id can be different every time)

Here is what I tried:

var thebook = $("tr:contains('Product Name')");
jQuery(thebook).children(input[title='Qty']).hide();

What am I doing wrong?

Body:
input[title='Qty'] should be in quotes, like "input[title='Qty']"

Without seeing your full code, I can't be sure there aren't other problems, but here's an example of this working in which I used .find() rather than .children() to search all the way down the descendent chain:

$("tr:contains('Product B')").find("input[title='Qty']").hide();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Product A</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
  <tr>
    <td>Product B</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
  <tr>
    <td>Product C</td>
    <td>Quantity: <input title='Qty'></td>
  </tr>
</table>


问:
c - function pointer - why pass a struct as an argument?
I'm reading the source code below for a program and trying to understand function pointers. Taking lwm2m_read_callback_t as an example, this is a function pointer correct? Is there an obvious reason why the 4th argument takes a pointer to the lwm2m_object_t struct itself?

```<code>/*
 * LWM2M Objects
 *
 * For the read callback, if *numDataP is not zero, *dataArrayP is pre-allocated
 * and contains the list of resources to read.
 *
 */

typedef struct _lwm2m_object_t lwm2m_object_t;

typedef uint8_t (*lwm2m_read_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_discover_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_write_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_execute_callback_t) (uint16_t instanceId, uint16_t resourceId, uint8_t * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_create_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_delete_callback_t) (uint16_t instanceId, lwm2m_object_t * objectP);

struct _lwm2m_object_t
{
    struct _lwm2m_object_t * next;           // for internal use only.
    uint16_t       objID;
    lwm2m_list_t * instanceList;
    lwm2m_read_callback_t     readFunc;
    lwm2m_write_callback_t    writeFunc;
    lwm2m_execute_callback_t  executeFunc;
    lwm2m_create_callback_t   createFunc;
    lwm2m_delete_callback_t   deleteFunc;
    lwm2m_discover_callback_t discoverFunc;
    void * userData;
};

typedef struct _lwm2m_list_t
{
    struct _lwm2m_list_t * next;
    uint16_t    id;
} lwm2m_list_t;
</code>```

答:
It is a way to modify the struct in a different function from the function where the struct is initialized.  This way you can modify the struct by reference.
In C you can only return one variable and passing variables by reference is a way to still be able to modify multiple variables in a function.

Say you want to modify 2 integers in a function:

```<code>void myfunc(int *a, int *b) {
    *a = *b + 3;
    *b = *a;
}

int main() {
    int a = 10;
    int b =  5;
    myfunc(&a, &b);

    return 0;
}
</code>```

As you can see, this allows you to change the variables my reference.

The same can be done with structures.

Body:
I'm reading the source code below for a program and trying to understand function pointers. Taking lwm2m_read_callback_t as an example, this is a function pointer correct? Is there an obvious reason why the 4th argument takes a pointer to the lwm2m_object_t struct itself?

/*
 * LWM2M Objects
 *
 * For the read callback, if *numDataP is not zero, *dataArrayP is pre-allocated
 * and contains the list of resources to read.
 *
 */

typedef struct _lwm2m_object_t lwm2m_object_t;

typedef uint8_t (*lwm2m_read_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_discover_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_write_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_execute_callback_t) (uint16_t instanceId, uint16_t resourceId, uint8_t * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_create_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_delete_callback_t) (uint16_t instanceId, lwm2m_object_t * objectP);

struct _lwm2m_object_t
{
    struct _lwm2m_object_t * next;           // for internal use only.
    uint16_t       objID;
    lwm2m_list_t * instanceList;
    lwm2m_read_callback_t     readFunc;
    lwm2m_write_callback_t    writeFunc;
    lwm2m_execute_callback_t  executeFunc;
    lwm2m_create_callback_t   createFunc;
    lwm2m_delete_callback_t   deleteFunc;
    lwm2m_discover_callback_t discoverFunc;
    void * userData;
};

typedef struct _lwm2m_list_t
{
    struct _lwm2m_list_t * next;
    uint16_t    id;
} lwm2m_list_t;

Body:
It is a way to modify the struct in a different function from the function where the struct is initialized.  This way you can modify the struct by reference.
In C you can only return one variable and passing variables by reference is a way to still be able to modify multiple variables in a function.

Say you want to modify 2 integers in a function:

void myfunc(int *a, int *b) {
    *a = *b + 3;
    *b = *a;
}

int main() {
    int a = 10;
    int b =  5;
    myfunc(&a, &b);

    return 0;
}

As you can see, this allows you to change the variables my reference.

The same can be done with structures.