问:
Middle align a sticky column
I´m trying to have a table with a sticky first column. The content in the sticky column is always in top of the probably because position is absolute.
How can I middle align the text in the sticky column?

        table {
          border-collapse: separate;
          border-top: 3px solid grey;
        }

        td,
        th {
          margin: 0;
          border: 3px solid grey;
          border-top-width: 0px;
          height: 30px;
        }

        div {
          width: 600px;
          overflow-x: scroll;
          margin-left: 70px;
          overflow-y: visible;
          padding-bottom: 1px;
        }

        .stickycol {
          line-height: 13px;
          position: absolute;
          width: 70px;
          left: 0;
          top: auto;
          border-right: 0px none black;
          border-top-width: 3px;
          /*only relevant for first row*/
          margin-top: -3px;
          /*compensate for top border*/

          word-wrap: break-word;
           white-space: -moz-pre-wrap !important;
          /* Mozilla, since 1999 */
          white-space: -pre-wrap;
          /* Opera 4-6 */
          white-space: -o-pre-wrap;
          /* Opera 7 */
          white-space: pre-wrap;
          /* css-3 */
          word-wrap: break-word;
          /* Internet Explorer 5.5+ */
          white-space: -webkit-pre-wrap;
          /* Newer versions of Chrome/Safari*/
          word-break: break-all;
          white-space: normal;
        }

        .long {
          letter-spacing: 1em;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <thead>
      <tr>
        <th class="stickycol">col1</th>
        <th>col2</th>
        <th>col3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="stickycol">This text is so long</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">2</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">3</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">4</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">5</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">6</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">7</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">8</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">9</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
You need to just add few css properties in the stickycol css class.

align-items:center and display:flex are for verically align

justify-content and text-align are for horizontally align.

see the snippet.

   table {
          border-collapse: separate;
          border-top: 3px solid grey;
        }

        td,
        th {
          margin: 0;
          border: 3px solid grey;
          border-top-width: 0px;
          height: 30px;
        }

        div {
          width: 600px;
          overflow-x: scroll;
          margin-left: 70px;
          overflow-y: visible;
          padding-bottom: 1px;
        }

        .stickycol {
        text-align:center;
        justify-content:center;
        align-items:center;
        display:flex;
          line-height: 13px;
          position: absolute;
          width: 70px;
          left: 0;
          top: auto;
          border-right: 0px none black;
          border-top-width: 3px;
          /*only relevant for first row*/
          margin-top: -3px;
          /*compensate for top border*/

          word-wrap: break-word;
           white-space: -moz-pre-wrap !important;
          /* Mozilla, since 1999 */
          white-space: -pre-wrap;
          /* Opera 4-6 */
          white-space: -o-pre-wrap;
          /* Opera 7 */
          white-space: pre-wrap;
          /* css-3 */
          word-wrap: break-word;
          /* Internet Explorer 5.5+ */
          white-space: -webkit-pre-wrap;
          /* Newer versions of Chrome/Safari*/
          word-break: break-all;
          white-space: normal;
        }

        .long {
          letter-spacing: 1em;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <table>
    <thead>
      <tr>
        <th class="stickycol">col1</th>
        <th>col2</th>
        <th>col3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="stickycol">This text is so long</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">2</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">3</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">4</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">5</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">6</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">7</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">8</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">9</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Title: Middle align a sticky column

Body:
I´m trying to have a table with a sticky first column. The content in the sticky column is always in top of the probably because position is absolute.
How can I middle align the text in the sticky column?

        table {
          border-collapse: separate;
          border-top: 3px solid grey;
        }

        td,
        th {
          margin: 0;
          border: 3px solid grey;
          border-top-width: 0px;
          height: 30px;
        }

        div {
          width: 600px;
          overflow-x: scroll;
          margin-left: 70px;
          overflow-y: visible;
          padding-bottom: 1px;
        }

        .stickycol {
          line-height: 13px;
          position: absolute;
          width: 70px;
          left: 0;
          top: auto;
          border-right: 0px none black;
          border-top-width: 3px;
          /*only relevant for first row*/
          margin-top: -3px;
          /*compensate for top border*/

          word-wrap: break-word;
           white-space: -moz-pre-wrap !important;
          /* Mozilla, since 1999 */
          white-space: -pre-wrap;
          /* Opera 4-6 */
          white-space: -o-pre-wrap;
          /* Opera 7 */
          white-space: pre-wrap;
          /* css-3 */
          word-wrap: break-word;
          /* Internet Explorer 5.5+ */
          white-space: -webkit-pre-wrap;
          /* Newer versions of Chrome/Safari*/
          word-break: break-all;
          white-space: normal;
        }

        .long {
          letter-spacing: 1em;
        }

        col1
        col2
        col3

        This text is so long
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        2
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        3
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        4
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        5
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        6
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        7
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        8
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

        9
        QWERTYUIOPASDFGHJKLZXCVBNM
        QWERTYUIOPASDFGHJKLZXCVBNM

Body:
You need to just add few css properties in the stickycol css class.

align-items:center and display:flex are for verically align

justify-content and text-align are for horizontally align.

see the snippet.

   table {
          border-collapse: separate;
          border-top: 3px solid grey;
        }

        td,
        th {
          margin: 0;
          border: 3px solid grey;
          border-top-width: 0px;
          height: 30px;
        }

        div {
          width: 600px;
          overflow-x: scroll;
          margin-left: 70px;
          overflow-y: visible;
          padding-bottom: 1px;
        }

        .stickycol {
        text-align:center;
        justify-content:center;
        align-items:center;
        display:flex;
          line-height: 13px;
          position: absolute;
          width: 70px;
          left: 0;
          top: auto;
          border-right: 0px none black;
          border-top-width: 3px;
          /*only relevant for first row*/
          margin-top: -3px;
          /*compensate for top border*/

          word-wrap: break-word;
           white-space: -moz-pre-wrap !important;
          /* Mozilla, since 1999 */
          white-space: -pre-wrap;
          /* Opera 4-6 */
          white-space: -o-pre-wrap;
          /* Opera 7 */
          white-space: pre-wrap;
          /* css-3 */
          word-wrap: break-word;
          /* Internet Explorer 5.5+ */
          white-space: -webkit-pre-wrap;
          /* Newer versions of Chrome/Safari*/
          word-break: break-all;
          white-space: normal;
        }

        .long {
          letter-spacing: 1em;
        }

<div>
  <table>
    <thead>
      <tr>
        <th class="stickycol">col1</th>
        <th>col2</th>
        <th>col3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="stickycol">This text is so long</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">2</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">3</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">4</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">5</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">6</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">7</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">8</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
      <tr>
        <td class="stickycol">9</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
      </tr>
    </tbody>
  </table>
</div>


来源: stackexchange

问:
Paramiko uploading file successfully but it's empty
Trying to export a dataframe to csv using StringIO and transfer it via SFTP using paramiko. The file comes through successfully but it's empty. Any idea why?</p>

```<code>import pandas as pd
from StringIO import StringIO
import paramiko

names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]

BabyDataSet = list(zip(names,births))
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])

buf = StringIO()
df.to_csv(buf, sep = ',', header = True, index = False)
#buf.getvalue() # Correct output

transport = paramiko.Transport(('localhost', 22))
transport.connect(username='user', password='pass')
sftp = paramiko.SFTPClient.from_transport(transport)

upload_path = '/Users/user/Desktop/test.csv'
sftp.putfo(buf, upload_path)
sftp.close()
</code>```

答:
With this line, you have written to buf as though it's a file.

```<code>df.to_csv(buf, sep = ',', header = True, index = False)
</code>```

It's a file-like object, so it has a reference to how far through that 'file' you are. When putfo tries to read from buf it will read from the last place used, and since you've written to the buffer, that location is at the end of your data. buf.getvalue() returns the entire contents of the buffer, regardless of the current position in the file. Seek to the start to get everything when reading normally:

```<code>df.to_csv(buf, sep = ',', header = True, index = False)
buf.seek(0) # rewind to the beginning of the 'file'
sftp.putfo(buf, upload_path)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to export a dataframe to csv using StringIO and transfer it via SFTP using paramiko. The file comes through successfully but it's empty. Any idea why?

import pandas as pd
from StringIO import StringIO
import paramiko

names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]

BabyDataSet = list(zip(names,births))
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])

buf = StringIO()
df.to_csv(buf, sep = ',', header = True, index = False)
#buf.getvalue() # Correct output

transport = paramiko.Transport(('localhost', 22))
transport.connect(username='user', password='pass')
sftp = paramiko.SFTPClient.from_transport(transport)

upload_path = '/Users/user/Desktop/test.csv'
sftp.putfo(buf, upload_path)
sftp.close()

Body:
With this line, you have written to buf as though it's a file.

df.to_csv(buf, sep = ',', header = True, index = False)

It's a file-like object, so it has a reference to how far through that 'file' you are. When putfo tries to read from buf it will read from the last place used, and since you've written to the buffer, that location is at the end of your data. buf.getvalue() returns the entire contents of the buffer, regardless of the current position in the file. Seek to the start to get everything when reading normally:

df.to_csv(buf, sep = ',', header = True, index = False)
buf.seek(0) # rewind to the beginning of the 'file'
sftp.putfo(buf, upload_path)


问:
Linq GroupBy and multiple columns
```<code>class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}

List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}
</code>```

Excuse the rather contrived example.

How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.

Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.

so...

```<code>ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }
</code>```

答:
In your particular case, you could use x.First().Team inside your Select to get your team information.

For other cases of actually needing to group on multiple fields, you could group on an anonymous type. Such as

someQuery.GroupBy(f => new { f.Foo, f.Bar }).Select(...);

ContentLicense: CC BY-SA 2.5

Title: Linq GroupBy and multiple columns

Body:
class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}

List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}

Excuse the rather contrived example.

How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.

Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.

so...

ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }


问:
Is logistic regression better for a linearly separable data?
Regarding classification...
Suppose that it is found a data to be linearly separable( tested the linear separability using SVM/Clustering/Single perceptron etc..)
Can we go with a simpler model like logistic regression (instead of SVM or any other) as they say simple model is the better model

Please correct me if wrong

Thanks in advance !
Surya

答:
Don't confuse the algorithm with the model.  With linearly separable data, each of those algorithms should return a simple hyperplane, a sum of linear (first-degree) terms with real coefficients.  Thus, each of the models is equally simple.

If you're concerned with the simplest algorithm, then you do have a point.

I would stick with straightforward SVM: it provides a closed-form computation to determine the optimum separation, based on the nearest N+1 observations (given N features).

Each of the algorithms has its advantages with respect to run-time, clarity, accuracy, etc.  If your criterion is something other than maximum gap, then linear regression (in its closed form) may be the best choice.


问:
Android Studio - view both Text and Design preview of layout
In Android Studio, how can I view both the text and design preview of an XML layout side by side.

I could see it by default when I installed Studio, but now that is gone,
and I'm not sure why. I can only see or the other.

How do I re-enable it?

答: Click on preview while text is selected.


问:
Amazon Simple Notification Service to send SMS in asp.net
I want to send sms to mobile devices using amazon sns in asp.net without creating any topic and subsciption. Can anybody suggest me some helpful material or link. Thanks.</p>

答:
This is now possible with AWS SNS. When you create a PublishRequest you will see a property for PhoneNumber. Just enter the phone number and publish the message as you normally would.

Important thing to note: the phone number has to be in E.164 format. example: +14155552671


问:
How to determine the file extension of a file from a uri
Assuming I am given a URI, and I want to find the file extension of the file that is returned, what do I have to do in Java.

For example the file at http://www.daml.org/2001/08/baseball/baseball-ont is http://www.daml.org/2001/08/baseball/baseball-ont.owl

When I do

```<code>    URI uri = new URI(address);
    URL url = uri.toURL();
    String file = url.getFile();
    System.out.println(file);
</code>```

I am not able to see the full file name with .owl extension, just /2001/08/baseball/baseball-ont how do I get the file extension as well.
``

答:
As other answers have explained, you don't really know the content type without inspecting the file. However, you can predict the file type from a URL.

Java almost provides this functionality as part of the URL class. The method URL::getFile will intelligently grab the file portion of a URL:

```<code>final URL url = new URL("http://www.example.com/a/b/c/stuff.zip?u=1");
final String file = url.getFile(); // file = "/a/b/c/stuff.zip?u=1"
</code>```

We can use this to write our implementation:

```<code>public static Optional<String> getFileExtension(final URL url) {

    Objects.requireNonNull(url, "url is null");

    final String file = url.getFile();

    if (file.contains(".")) {

        final String sub = file.substring(file.lastIndexOf('.') + 1);

        if (sub.length() == 0) {
            return Optional.empty();
        }

        if (sub.contains("?")) {
            return Optional.of(sub.substring(0, sub.indexOf('?')));
        }

        return Optional.of(sub);
    }

    return Optional.empty();
}
</code>```

This implementation should handle edge-cases properly:

```<code>assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/stuff.zip")));

assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/stuff.zip")));

assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/a/b/c/stuff.zip")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com/")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com/.")));
</code>```

Body:
Assuming I am given a URI, and I want to find the file extension of the file that is returned, what do I have to do in Java.

For example the file at http://www.daml.org/2001/08/baseball/baseball-ont is http://www.daml.org/2001/08/baseball/baseball-ont.owl

When I do

    URI uri = new URI(address);
    URL url = uri.toURL();
    String file = url.getFile();
    System.out.println(file);

I am not able to see the full file name with .owl extension, just /2001/08/baseball/baseball-ont how do I get the file extension as well.
``

Body:
As other answers have explained, you don't really know the content type without inspecting the file. However, you can predict the file type from a URL.

Java almost provides this functionality as part of the URL class. The method URL::getFile will intelligently grab the file portion of a URL:

final URL url = new URL("http://www.example.com/a/b/c/stuff.zip?u=1");
final String file = url.getFile(); // file = "/a/b/c/stuff.zip?u=1"

We can use this to write our implementation:

public static Optional<String> getFileExtension(final URL url) {

    Objects.requireNonNull(url, "url is null");

    final String file = url.getFile();

    if (file.contains(".")) {

        final String sub = file.substring(file.lastIndexOf('.') + 1);

        if (sub.length() == 0) {
            return Optional.empty();
        }

        if (sub.contains("?")) {
            return Optional.of(sub.substring(0, sub.indexOf('?')));
        }

        return Optional.of(sub);
    }

    return Optional.empty();
}

This implementation should handle edge-cases properly:

assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/stuff.zip")));

assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/stuff.zip")));

assertEquals(
    Optional.of("zip"),
    getFileExtension(new URL("http://www.example.com/a/b/c/stuff.zip")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com/")));

assertEquals(
    Optional.empty(),
    getFileExtension(new URL("http://www.example.com/.")));


问:
Cannot connect to MongoDB via NodeJS - No primary found in replica set error
I am having difficulty connecting to MongoDB via NodeJS. The Mongo setup consists of a shared cluster.

The URL is below:

mongodb://dev.testserver.com:27017,dev.testserver.com:27018,dev.testserver.com:27019/ua?w=0&replicaSet=dev-testserver-com&readPreference=secondary&slaveOk=true

The code that I have is below:

```<code>    var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url, function(err db) {
  if(!err) {
    console.log("We are connected");
  }

  db.close();
});
</code>```

The error that I keep getting is "MongoError: no primary found in replicaset".

Can someone please help?

答: Looks like there is a problem in your server(s). You need to get on the server(s) and run rs.status() to find out the state of your replica set, and each server's logs to find out if and why one or more has stopped or become disconnected.</p>

Body:
I am having difficulty connecting to MongoDB via NodeJS. The Mongo setup consists of a shared cluster.

The URL is below:

mongodb://dev.testserver.com:27017,dev.testserver.com:27018,dev.testserver.com:27019/ua?w=0&replicaSet=dev-testserver-com&readPreference=secondary&slaveOk=true

The code that I have is below:

    var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url, function(err db) {
  if(!err) {
    console.log("We are connected");
  }

  db.close();
});

The error that I keep getting is "MongoError: no primary found in replicaset".

Can someone please help?


问:
Local file download with a lot of content
I'm using a local in-browser database to store data. However I want to give users the ability to export that data to CSV.

While googling I found the solution with data urls - prepare the url with data. However in my case this is >1MB of data to generate each time the page (link) is rendered. Is there any alternative solution that would allow me to generate a file download from JavaScript, but does not require me to prepare the content upfront - only when user actually clicks the link?

In case it matters I'm using React to build my application..

答:
Try a blob.

(no, not that kind)

demo

```<code>var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);
</code>```

Need to convert JSON to CSV?

demo

(https://stackoverflow.com/a/14966131/6560716)

```<code>var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);
</code>```

Need to have a name for the file?

demo

```<code>var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();
</code>```

Filename and JSON?

demo

```<code>var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();
</code>```

Body:
Try a blob.

(no, not that kind)

demo

var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);

Need to convert JSON to CSV?

demo

(https://stackoverflow.com/a/14966131/6560716)

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
open(url);

Need to have a name for the file?

demo

var blob = new Blob(["CSV DATA HERE"], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();

Filename and JSON?

demo

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "";
data.forEach(function(infoArray, index){
   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;
});
var blob = new Blob([csvContent], {type: "text/csv"});
var url  = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "filename.csv");
document.body.appendChild(link);
link.click();


问:
ReactJS: Warning: setState(...): Cannot update during an existing state transition
I am trying to refactor the following code from my render view:

```<code><Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button>
</code>```

to a version where the bind is within the constructor. The reason for that is that bind in the render view will give me performance issues, especially on low end mobile phones.

I have created the following code, but I am constantly getting the following errors (lots of them). It looks like the app gets in a loop:

```<code>Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
</code>```

Below is the code I use:

```<code>var React = require('react');
var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var Button = require('react-bootstrap/lib/Button');
var Form = require('react-bootstrap/lib/Form');
var FormGroup = require('react-bootstrap/lib/FormGroup');
var Well = require('react-bootstrap/lib/Well');

export default class Search extends React.Component {

    constructor() {
        super();

        this.state = {
            singleJourney: false
        };

        this.handleButtonChange = this.handleButtonChange.bind(this);
    }

    handleButtonChange(value) {
        this.setState({
            singleJourney: value
        });
    }

    render() {

        return (
            <Form>

                <Well style={wellStyle}>

                    <FormGroup className="text-center">

                        <ButtonGroup>
                            <Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange(false)} >Retour</Button>
                            <Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChange(true)} >Single Journey</Button>
                        </ButtonGroup>
                    </FormGroup>

                </Well>

            </Form>
        );
    }
}

module.exports = Search;
</code>```

答:
If you are trying to add arguments to a handler in recompose, make sure that you're defining your arguments correctly in the handler. It is essentially a curried function, so you want to be sure to require the correct number of arguments. This page has a good example of using arguments with handlers.

Example (from the link):

```<code>withHandlers({
  handleClick: props => (value1, value2) => event => {
    console.log(event)
    alert(value1 + ' was clicked!')
    props.doSomething(value2)
  },
})
</code>```

for your child HOC and in the parent

```<code>class MyComponent extends Component {
  static propTypes = {
    handleClick: PropTypes.func,
  }
  render () {
    const {handleClick} = this.props
    return (
      <div onClick={handleClick(value1, value2)} />
    )
  }
}
</code>```

this avoids writing an anonymous function out of your handler to patch fix the problem with not supplying enough parameter names on your handler.

Body:
I am trying to refactor the following code from my render view:

<Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button>

to a version where the bind is within the constructor. The reason for that is that bind in the render view will give me performance issues, especially on low end mobile phones.

I have created the following code, but I am constantly getting the following errors (lots of them). It looks like the app gets in a loop:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

Below is the code I use:

var React = require('react');
var ButtonGroup = require('react-bootstrap/lib/ButtonGroup');
var Button = require('react-bootstrap/lib/Button');
var Form = require('react-bootstrap/lib/Form');
var FormGroup = require('react-bootstrap/lib/FormGroup');
var Well = require('react-bootstrap/lib/Well');

export default class Search extends React.Component {

    constructor() {
        super();

        this.state = {
            singleJourney: false
        };

        this.handleButtonChange = this.handleButtonChange.bind(this);
    }

    handleButtonChange(value) {
        this.setState({
            singleJourney: value
        });
    }

    render() {

        return (
            <Form>

                <Well style={wellStyle}>

                    <FormGroup className="text-center">

                        <ButtonGroup>
                            <Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange(false)} >Retour</Button>
                            <Button href="#" active={this.state.singleJourney} onClick={this.handleButtonChange(true)} >Single Journey</Button>
                        </ButtonGroup>
                    </FormGroup>

                </Well>

            </Form>
        );
    }
}

module.exports = Search;

Body:
If you are trying to add arguments to a handler in recompose, make sure that you're defining your arguments correctly in the handler. It is essentially a curried function, so you want to be sure to require the correct number of arguments. This page has a good example of using arguments with handlers.

Example (from the link):

withHandlers({
  handleClick: props => (value1, value2) => event => {
    console.log(event)
    alert(value1 + ' was clicked!')
    props.doSomething(value2)
  },
})

for your child HOC and in the parent

class MyComponent extends Component {
  static propTypes = {
    handleClick: PropTypes.func,
  }
  render () {
    const {handleClick} = this.props
    return (
      <div onClick={handleClick(value1, value2)} />
    )
  }
}

this avoids writing an anonymous function out of your handler to patch fix the problem with not supplying enough parameter names on your handler.


问:
UWP play a YouTube video
I am trying to find a resource that would explain how to retrieve a YouTube video URL to play in an external player. Of course, I have taken a look at the YouTube Data API, but there doesn't seem to be a way to do this.

However, I know it is possible, given that there exist YouTube client applications that are able to stream video (MetroTube is one example).

I saw the related post (How to play a YouTube video in WPF using C#), but it was posted a long time ago. I would like to avoid having to use a WebBrowser control (or WebView in UWP).

Can someone suggest an approach or point to a resource that allows this?

答:
I have used MyToolKit.Extended in the past to integrate Youtube Videos in one of my App.

Install Nuget Package from Here

Once done, you need to call this method

```<code>internal async Task<Uri> GetYoutubeUri(string VideoID)
{
    YouTubeUri uri = await YouTube.GetVideoUriAsync(VideoID, YouTubeQuality.Quality1080P);
    return uri.Uri;
}
</code>```

Make sure you are passing only VideoID. i.e, If your URL is

```<code>https://www.youtube.com/watch?v=UO-8CMdeSHA
</code>```

you need to pass only UO-8CMdeSHA.

Once done, you will receive the actual Media Uri. You can now set this as a source to MediaPlayer. Something like below.

```<code>Uri _videoUri = await GetYoutubeUri("UO-8CMdeSHA");
if (_videoUri != null)
{
    player.Source = _videoUri;
    player.Play();
}
</code>```

To ensure you see basic Play/Pause button and few others, Use Below in your XAML.

```<code>MediaElement x:Name="player" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AreTransportControlsEnabled="True" />
</code>```

And you should be able to play YouTube Videos.

Good Luck.

Title: UWP play a YouTube video

Body:
I have used MyToolKit.Extended in the past to integrate Youtube Videos in one of my App.

Install Nuget Package from Here

Once done, you need to call this method

internal async Task<Uri> GetYoutubeUri(string VideoID)
{
    YouTubeUri uri = await YouTube.GetVideoUriAsync(VideoID, YouTubeQuality.Quality1080P);
    return uri.Uri;
}

Make sure you are passing only VideoID. i.e, If your URL is

https://www.youtube.com/watch?v=UO-8CMdeSHA

you need to pass only UO-8CMdeSHA.

Once done, you will receive the actual Media Uri. You can now set this as a source to MediaPlayer. Something like below.

Uri _videoUri = await GetYoutubeUri("UO-8CMdeSHA");
if (_videoUri != null)
{
    player.Source = _videoUri;
    player.Play();
}

To ensure you see basic Play/Pause button and few others, Use Below in your XAML.

MediaElement x:Name="player" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AreTransportControlsEnabled="True" />

And you should be able to play YouTube Videos.

Good Luck.


问:
Extracting data from Google spreadsheets via API + c#
In General I have a problem I can't read the data from the table.
The problem I have is really simple, I'll describe it on the example of the Excel spreadsheet.

Get cell value from table in status, if this cell says "Not sent" or cell is empty in this case, I take from another cell the data in the same row and begin to work with these data.
After successful completion of the task, I set the status "sent" to the cell from which the received data. Here everything is simple, but using the API to do not understand. Already mastered authorization, i.e. using the standard code I can write data to the table, but can not get please, edit code.
Here is the code:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SheetsQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        static string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
        static string ApplicationName = "Google Sheets API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Define request parameters.
            String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
            String range = "Class Data!A2:E";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;
            if (values != null && values.Count > 0)
            {
                Console.WriteLine("Name, Major");
                foreach (var row in values)
                {
                    // Print columns A and E, which correspond to indices 0 and 4.
                    Console.WriteLine("{0}, {1}", row[0], row[4]);
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            Console.Read();

        }
    }
}```

答: You may follow this Google Sheets with C# tutorial. It stated that you will need the NuGet packages from both client libraries. The first one is the current Google .net client library which we need to authenticate. The second is the old Gdata library which we use to access Google SpreadSheets. You may also refer with this SO post: Accessing Google Spreadsheets with C# using Google Data API</p>


问:
Attaching a Drive file to an assignment with Google Classroom API
Using Google Apps Script I have managed to create an assignment with the following code:

```<code>Classroom.Courses.CourseWork.create({
 "courseId": id,
 "title" : title,
 "description" : desc,
 "workType" : 'ASSIGNMENT',
 }, id)
</code>```

This works fine, creating a draft assignment on Classroom. However, when I try to attach a Drive file like so:

```<code>  Classroom.Courses.CourseWork.create({
    "courseId": id,
    "title" : title,
    "description" : desc,
    "workType" : 'ASSIGNMENT',
    "materials" : [
      {
      "driveFile": {
        "id" : fileId,
        "title" : fileTitle,
        "alternateLink" : fileLink,
        "thumbnailUrl" : fileThumbnail,
      },
      "shareMode" : 'STUDENT_COPY',
    }
    ],
  }, id)
</code>```

I receive these errors:

Execution failed: Invalid JSON payload received. Unknown name "share_mode" at 'course_work.materials[0]': Cannot find field.

Invalid JSON payload received. Unknown name "alternate_link" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "id" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "title" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "thumbnail_url" at 'course_work.materials[0].drive_file': Cannot find field. (line 61, file "Classroom") [1.187 seconds total runtime]

Any help will be appreciated, thank you

答:
You may refer with this SO answer. This error might happen because of wrong formatting of the request.

Sample code:

```<code>function myFunction() {
  var ClassSource =  {
    title: "Test File",
    state: "DRAFT",
    materials: [
      {
        driveFile:{
        driveFile: {
          id: "fileID",
          title: "Sample Document"

        },
        shareMode: "STUDENT_COPY"
        }

      }
      ],
    workType: "ASSIGNMENT"
  };

  Classroom.Courses.CourseWork.create(ClassSource, COURSEID)
  //Logger.log(exec);
}
</code>```

You may try this using Try this API.

Hope this helps!

Body:
Using Google Apps Script I have managed to create an assignment with the following code:

Classroom.Courses.CourseWork.create({
 "courseId": id,
 "title" : title,
 "description" : desc,
 "workType" : 'ASSIGNMENT',
 }, id)

This works fine, creating a draft assignment on Classroom. However, when I try to attach a Drive file like so:

  Classroom.Courses.CourseWork.create({
    "courseId": id,
    "title" : title,
    "description" : desc,
    "workType" : 'ASSIGNMENT',
    "materials" : [
      {
      "driveFile": {
        "id" : fileId,
        "title" : fileTitle,
        "alternateLink" : fileLink,
        "thumbnailUrl" : fileThumbnail,
      },
      "shareMode" : 'STUDENT_COPY',
    }
    ],
  }, id)

I receive these errors:

Execution failed: Invalid JSON payload received. Unknown name "share_mode" at 'course_work.materials[0]': Cannot find field.

Invalid JSON payload received. Unknown name "alternate_link" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "id" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "title" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "thumbnail_url" at 'course_work.materials[0].drive_file': Cannot find field. (line 61, file "Classroom") [1.187 seconds total runtime]

Any help will be appreciated, thank you

Body:
You may refer with this SO answer. This error might happen because of wrong formatting of the request.

Sample code:

function myFunction() {
  var ClassSource =  {
    title: "Test File",
    state: "DRAFT",
    materials: [
      {
        driveFile:{
        driveFile: {
          id: "fileID",
          title: "Sample Document"

        },
        shareMode: "STUDENT_COPY"
        }

      }
      ],
    workType: "ASSIGNMENT"
  };

  Classroom.Courses.CourseWork.create(ClassSource, COURSEID)
  //Logger.log(exec);
}

You may try this using Try this API.

Hope this helps!


问:
How to clean up left over $watches
We interop our angularJS web components with a jqxGrid. When the user edits in a cell, we create a custom typeahead editor (written in angular). When the editor is destroyed, I noticed that my $watches array doesn't return back to the previous value.

I am creating a new isolateScope for my directive, which I then compile and then append to the DOM element that JQX passes to me when the editor is needed:

var scope = $rootScope.$new(true);
 var customEditor = $compile(directive)(scope);

What do I have to do in order to clean up these $watches?

答:
Its likely that the new scope you are creating via

```<code>var scope = $rootScope.$new(true);
</code>```

Is not being destroyed by the jqxGrid once the jqxGrid is done with the editor.

To clean up the watches, you simply need to ensure that a call is made to

```<code>scope.$destroy();
</code>```

The tricky part is figuring out when to execute the destroy call;  I believe the jqxGrid should raise events such as beforeEdit and afterEdit which you can subscribe to;  the place where the $destroy() call should be made is within an event handler for the afterEdit event.

Title: How to clean up left over $watches

Body:
Its likely that the new scope you are creating via

var scope = $rootScope.$new(true);

Is not being destroyed by the jqxGrid once the jqxGrid is done with the editor.

To clean up the watches, you simply need to ensure that a call is made to

scope.$destroy();

The tricky part is figuring out when to execute the destroy call;  I believe the jqxGrid should raise events such as beforeEdit and afterEdit which you can subscribe to;  the place where the $destroy() call should be made is within an event handler for the afterEdit event.


问:
nightwatch - check for popup window, after each click event
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

```<code>.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

</code>```

Solution I have come up with so far:

```<code>.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)
</code>```

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?

答: you should yse .switchWindow() method.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there a way in nightwatch to check whether a popup window appears after each click event?

I have a problem that randomly an error message appear and I don't want to write for each click event the same callback function.

I have already tried out the after and afterEach commands in the Global.js but then the commands will only run after the whole test suite.

I also have tried it local within a test file, although it also does not cover all single click events, even though the official website writes "... while beforeEach and afterEach are ran before and after each testcase (test step)"?

Solution I'm looking for:

.waitForElementVisible('selector')
    .click('selector')
    .click('selector')

Solution I have come up with so far:

.waitForElementVisible('selector')
    .click('selector', isPresent)
    .click('selector', isPresent)

isPresent as a callback function, which does the checking and close the popup window if it appears.

Is there another way to write a function (with or without after and/or forEach), so that it will be called after each click event or after each command. Thus, I don't have to write the isPresent repetitive code?

Body: you should yse .switchWindow() method.


问:
Restoring database failed in SQL Server 2005 enterprise edition
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

```<code>    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)
</code>```

What should I do?

答: Install SQL Server 2005 Service Pack 3 on your copy of SQL server, and it will be able to restore the file without a problem.  The database server which backed up the database originally was running SP3, and you must have at least that version if you want to restore the DB.</p>

Body:
I have tried to restore a database in SQL Server 2005 enterprise edition on Windows Server 2003. It shows the following error.

    Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
    Additional information:
    System.Data.SqlClient.SqlError: The database was backed up on a server running version
 9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server.  (Microsoft.SqlServer.Express.Smo)

What should I do?


问:
Is the Channel 9 explanation of Tasks vs. Threads correct?
There's a Channel 9 Video that attempts to explain the difference between Threads and Tasks. I usually like the Channel 9 videos for their technical accuracy, but from my understanding, this one gets some of the key statements wrong.

Here are the statements:

@~1:48 to ~2:30: Threads are expensive in memory and time. Each thread gets 1 MB of user mode stack.

@~2:30 to 2:37: It also takes time to create threads. Time to allocate the data structures and initialize them.

@~2:38 to 2:45: Context switching also takes time.

@~2:58 to 3:23 and 3:48 to : Tasks make use of a multi-core system [...] So when you do compute, you're using multiple cores.

@~5:02 to 5:30: Threads run on a single core and context switching happens a lot.

@~5:40 to 5:51: Threads have different ways to execute. They execute on multiple cores.

@~6:20 to 6:30: As you see here in the diagram, Threading has overhead.

And here are my thoughts that I'd like to be confirmed or disproven:

The amount of call stack is configurable. That way, the thread limit is not ~1300 but up to 12000 for a 32 bit process. Those who have a copy of SysInternals TestLimit available can try it:

```<code>D:\>testlimit -t -n 64
Testlimit v5.04 - test Windows limits
By Mark Russinovich - www.sysinternals.com

Creating threads with 64 KB stacks...
Created 12500 threads. Lasterror: 8
</code>```

The stack size is also exposed in the Thread Constructor for .NET

Tasks rely on Threads as a basis. Those threads are taken from the thread pool, but nevertheless, the threads of the thread pool need to be created before they can be used. AFAIK, Mark Russinovich also explained in the Windows Internals book, that the kernel structure (_ETHREAD) is kept in memory for reuse. This minimizes the overhead of allocation and reduces it to initialization.

I didn't find the exact place I was looking for, but in Windows Internals 6, part 1 it says on page 417:

[...] the executive thread object might or might not be deallocated.

Since Tasks rely on threads as the technical implementation, context switching occurs in any case.

If I have 2 threads, they can also be executed on different processors. IMHO that's the whole idea of it.

The speaker is taslking about threads on a single core system. IMHO, tasks will have almost no benefit in that case as well. See 4.)

See 4. and 5.)

The slide may be correct, but it does not show the actual reason for that. The slide it missing the ~15 ms time slices which cause the context switching. The overhead can only be reduced using Tasks if the thread needs to wait for a result.

In that case, the lower part of the slide is incorrect as well, because the first part of Work 1 seems to be blocking, in which case Work 2 could be executed only. When Work 2 finishes, the condition to continue with Work 1 might be fulfilled. Only if all that occurs within a time slice, Tasks have a benefit.

In any case, a context switch will occur with Tasks as well, sooner or later.

I have tried confirming my understanding with the help of these questions on SO

Task vs. Thread differences

What is the difference between a task and a thread

Above might seem like 7 individual questions. I asked them all in one place because

the all have their source in one video

some questions depend on each other

it's IMHO more important to find the information in one place than following the SO rule of asking one question at a time.

答:
Note:  Haven't watched the video, based purely on the info in OP.

The amount of call stack is configurable.

Probably, but not really relevant unless we're getting into very gritty details.

for .NET Tasks rely on Threads as a basis. Those threads are taken
  from the thread pool, but nevertheless, the threads of the thread pool
  need to be created before they can be used.

Somewhat correct... though we need to keep a very clear demarcation between abstraction and implementation.  Tasks can use the Threadpool in .Net for execution is more correct.

Tasks represent the idea of a self-contained section of code that (usually) can run concurrently of other code.  Threads are an OS implementation of similar nature.

Since Tasks rely on threads as the technical implementation, context switching occurs in any case.

Incorrect.  While Tasks can be run on threads, and context switching can occur, Tasks contain a layer of abstraction that provides more flexibility.

For example, to swap execution between threads, a context switch must occur in the hardware.  To swap execution between tasks, no such hardware context switch must occur.  Tasks can be moved between different threads, put to sleep and restored all without a single hardware context switch.

If I have 2 threads, they can also be executed on different
  processors. IMHO that's the whole idea of it.

Correct.

The speaker is talking about threads on a single core system. IMHO, tasks will have almost no benefit in that case as well.

Incorrect.  Tasks run well on single threaded systems as they are simply an abstraction.  Furthermore you can run many tasks in a single thread without any hardware-context switches, potentially increasing performance.

The main conceptual issue here seems to be the thinking that Task = Thread.  This is not the case.  A task is a conceptual way of breaking down work.  A thread is a implementation of a similar idea with certain behavioral characteristics.  While tasks can run on threads under the covers (not necessarily) the abstraction allows them to behave in a very different way than a hardware thread.

Body:
There's a Channel 9 Video that attempts to explain the difference between Threads and Tasks. I usually like the Channel 9 videos for their technical accuracy, but from my understanding, this one gets some of the key statements wrong.

Here are the statements:

@~1:48 to ~2:30: Threads are expensive in memory and time. Each thread gets 1 MB of user mode stack.

@~2:30 to 2:37: It also takes time to create threads. Time to allocate the data structures and initialize them.

@~2:38 to 2:45: Context switching also takes time.

@~2:58 to 3:23 and 3:48 to : Tasks make use of a multi-core system [...] So when you do compute, you're using multiple cores.

@~5:02 to 5:30: Threads run on a single core and context switching happens a lot.

@~5:40 to 5:51: Threads have different ways to execute. They execute on multiple cores.

@~6:20 to 6:30: As you see here in the diagram, Threading has overhead.

And here are my thoughts that I'd like to be confirmed or disproven:

The amount of call stack is configurable. That way, the thread limit is not ~1300 but up to 12000 for a 32 bit process. Those who have a copy of SysInternals TestLimit available can try it:

D:\>testlimit -t -n 64
Testlimit v5.04 - test Windows limits
By Mark Russinovich - www.sysinternals.com

Creating threads with 64 KB stacks...
Created 12500 threads. Lasterror: 8

The stack size is also exposed in the Thread Constructor for .NET

Tasks rely on Threads as a basis. Those threads are taken from the thread pool, but nevertheless, the threads of the thread pool need to be created before they can be used. AFAIK, Mark Russinovich also explained in the Windows Internals book, that the kernel structure (_ETHREAD) is kept in memory for reuse. This minimizes the overhead of allocation and reduces it to initialization.

I didn't find the exact place I was looking for, but in Windows Internals 6, part 1 it says on page 417:

[...] the executive thread object might or might not be deallocated.

Since Tasks rely on threads as the technical implementation, context switching occurs in any case.

If I have 2 threads, they can also be executed on different processors. IMHO that's the whole idea of it.

The speaker is taslking about threads on a single core system. IMHO, tasks will have almost no benefit in that case as well. See 4.)

See 4. and 5.)

The slide may be correct, but it does not show the actual reason for that. The slide it missing the ~15 ms time slices which cause the context switching. The overhead can only be reduced using Tasks if the thread needs to wait for a result.

In that case, the lower part of the slide is incorrect as well, because the first part of Work 1 seems to be blocking, in which case Work 2 could be executed only. When Work 2 finishes, the condition to continue with Work 1 might be fulfilled. Only if all that occurs within a time slice, Tasks have a benefit.

In any case, a context switch will occur with Tasks as well, sooner or later.

I have tried confirming my understanding with the help of these questions on SO

Task vs. Thread differences

What is the difference between a task and a thread

Above might seem like 7 individual questions. I asked them all in one place because

the all have their source in one video

some questions depend on each other

it's IMHO more important to find the information in one place than following the SO rule of asking one question at a time.


问:
Repeated incrementation of a floating point number
I'm looking at some legacy code that defines some grid points along the axis f.

```<code>int main(){
    double f[9];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.125){
        f[i++] = a;
    }
}
</code>```

I'm worried about the repeated addition of 1 / 8 to a, and the loop not running correctly. This is because I don't think you can add floating point values like this and rely on it being exactly 1 when i is 8.

Or is this code OK and I should stop worrying? (The code is at least 20 years old apparently and has never caused trouble - although in the original version, double a was declared outside the loop, I'm reading up on why that is.).

答:
The code is fine when compiled with a C compiler that provides either exactly IEEE 754 semantics or a close approximation of them (say, FLT_EVAL_METHOD>0, or even arbitrary excess precision for sub-expressions and arbitrary roundings to the nominal precision).

The problems you fear are:

representation error, where 0.125 is not exactly 1/8, and

operation error, where + is not exactly mathematical addition. None of these happen for this particular program.

0.125 requires 1 bit of precision to be represented exactly in base 2. This means that the floating-point number used by the program in these conditions is exactly the intended 1/8. Furthermore, it can be added to itself 253 times before there is any approximation in the addition.

This reasoning is not correct for other increment steps. For instance, the variation of your program below leaves one index of the array, f[100], uninitialized with at least my compiler (which implements strict IEEE 754 semantics):

```<code>int main(){
    double f[101];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.01){
        printf("%.16e %d\n", a, i);
        f[i++] = a;
    }
}
</code>```

When I run it I get at the last lines:

```
...
9.8000000000000065e-01 98
9.9000000000000066e-01 99
```

f[100] is never written to because of both representation error and operation error that occur when trying to add 0.01 repeatedly to itself in binary floating-point.

Body:
I'm looking at some legacy code that defines some grid points along the axis f.

int main(){
    double f[9];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.125){
        f[i++] = a;
    }
}

I'm worried about the repeated addition of 1 / 8 to a, and the loop not running correctly. This is because I don't think you can add floating point values like this and rely on it being exactly 1 when i is 8.

Or is this code OK and I should stop worrying? (The code is at least 20 years old apparently and has never caused trouble - although in the original version, double a was declared outside the loop, I'm reading up on why that is.).

Body:
The code is fine when compiled with a C compiler that provides either exactly IEEE 754 semantics or a close approximation of them (say, FLT_EVAL_METHOD>0, or even arbitrary excess precision for sub-expressions and arbitrary roundings to the nominal precision).

The problems you fear are:

representation error, where 0.125 is not exactly 1/8, and

operation error, where + is not exactly mathematical addition. None of these happen for this particular program.

0.125 requires 1 bit of precision to be represented exactly in base 2. This means that the floating-point number used by the program in these conditions is exactly the intended 1/8. Furthermore, it can be added to itself 253 times before there is any approximation in the addition.

This reasoning is not correct for other increment steps. For instance, the variation of your program below leaves one index of the array, f[100], uninitialized with at least my compiler (which implements strict IEEE 754 semantics):

int main(){
    double f[101];
    int i = 0;
    for (double a = 0; a <= 1; a += 0.01){
        printf("%.16e %d\n", a, i);
        f[i++] = a;
    }
}

When I run it I get at the last lines:

...
9.8000000000000065e-01 98
9.9000000000000066e-01 99

f[100] is never written to because of both representation error and operation error that occur when trying to add 0.01 repeatedly to itself in binary floating-point.


问:
Codeigniter 4 , running error
I am testing CodeIgniter 4, but I am getting this error:

Fatal error: Default value for parameters with a class type hint can only be NULL in C:\xampp\htdocs\CodeIgniter4-develop\system\Config\DotEnv.php on line 121

What am I missing?

答:
Codeigniter 4 requires php 7.

Verifying that, and then making sure CI works with a clean install from the git repo. Once you see the welcome page then you're good to go. If you are having issues with your own code, then please post that on here. Or post in the repo if you have found a bug in CI4.

Refer to the Documentation:

PHP version 7.0 or newer is required.

https://bcit-ci.github.io/CodeIgniter4/intro/requirements.html

Current GitHub Repo:

https://github.com/bcit-ci/CodeIgniter4

Title: Codeigniter 4 , running error


问:
Spring data JPA. Find by in
I have an usual Spring Data JPA repository in my spring project.

```<code>@Repository
public interface EventRepository extends CrudRepository<Event, Long> {
  List<Event> findByOriginalIdIn(Collection<String> originalEventIds);
  ...
</code>```

I used before method findByOriginalIdIn it was working good. But situation is changed and I need to handle same request using collection of pairs to find and filter correct events.

My alternative method should Handle next logic:
find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR

Is it possible handle this request using Selectively exposing CRUD methods? If yes, could I have an example please?

答:
I would suggest using QueryDSL with Spring JPA to make your implementation in easy manner.

With QueryDSL, you could easily construct your predicate (nothing but the criteria) and use it in the query. In your case, it would probably be something like below. Please refer to the link: Spring Data JPA Tutorial: Creating Database Queries With Querydsl on how to use QueryDSL with Spring Data JPA.

In your case, for given condition,

```<code>find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR
</code>```

I did not understand if e.g. originalId1/originalCalendarId1 should be equal to any value. Let's say, for the sake of simplicity and explanation, they are to be equal to some value.

```<code>import com.mysema.query.BooleanBuilder;
import com.mysema.query.types.Predicate;

public class EventPredicates {

    public static Predicate getAllEventsByOrginalIds(String[] originalIds, String[] originalCalendarIds) {
        QEvent event = QEventEntity.event;

        BooleanBuilder builder = new BooleanBuilder();

        //assuming both arrays are of same size.
        for (int idx = 0; idx < originalIds.length; idx++) {
            builder.or(event.originalIds[0].eq.(someValue)).and(event.originalCalendarIds[0].eq.(someCalValue));
        }
        return builder;
    }
}
</code>```

However, your repository interface should extend QueryDslPredicateExecutor<Event> to make use of the QueryDSL functionality.

In your service method, you could make the call something like below assuming EventRepository is declared as below:

```<code>@Autowired
EventRepository eventRepository;

public void someMethod(){

    ...
    List<Events> events = eventRepository.findAll(EventPredicates.getAllEventsByOrginalIds(originalIdsArr, originalCalendarIdsArr));
    ...

}
</code>```

Btw, QueryDSL makes it very easy to implement different criteria (simple to complex). Refer to the above link on how to use it.

Hope this helps.

Title: Spring data JPA. Find by in

Body:
I have an usual Spring Data JPA repository in my spring project.

@Repository
public interface EventRepository extends CrudRepository<Event, Long> {
  List<Event> findByOriginalIdIn(Collection<String> originalEventIds);
  ...

I used before method findByOriginalIdIn it was working good. But situation is changed and I need to handle same request using collection of pairs to find and filter correct events.

My alternative method should Handle next logic:
find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR

Is it possible handle this request using Selectively exposing CRUD methods? If yes, could I have an example please?

Body:
I would suggest using QueryDSL with Spring JPA to make your implementation in easy manner.

With QueryDSL, you could easily construct your predicate (nothing but the criteria) and use it in the query. In your case, it would probably be something like below. Please refer to the link: Spring Data JPA Tutorial: Creating Database Queries With Querydsl on how to use QueryDSL with Spring Data JPA.

In your case, for given condition,

find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR

I did not understand if e.g. originalId1/originalCalendarId1 should be equal to any value. Let's say, for the sake of simplicity and explanation, they are to be equal to some value.

import com.mysema.query.BooleanBuilder;
import com.mysema.query.types.Predicate;

public class EventPredicates {

    public static Predicate getAllEventsByOrginalIds(String[] originalIds, String[] originalCalendarIds) {
        QEvent event = QEventEntity.event;

        BooleanBuilder builder = new BooleanBuilder();

        //assuming both arrays are of same size.
        for (int idx = 0; idx < originalIds.length; idx++) {
            builder.or(event.originalIds[0].eq.(someValue)).and(event.originalCalendarIds[0].eq.(someCalValue));
        }
        return builder;
    }
}

However, your repository interface should extend QueryDslPredicateExecutor<Event> to make use of the QueryDSL functionality.

In your service method, you could make the call something like below assuming EventRepository is declared as below:

@Autowired
EventRepository eventRepository;

public void someMethod(){

    ...
    List<Events> events = eventRepository.findAll(EventPredicates.getAllEventsByOrginalIds(originalIdsArr, originalCalendarIdsArr));
    ...

}

Btw, QueryDSL makes it very easy to implement different criteria (simple to complex). Refer to the above link on how to use it.

Hope this helps.


问:
C# project builds OK , but no binaries produced
Using VS 2012, I build a C# project for a Debug build.  The build succeeds, but the directory ..\bin\debug is empty.

What can cause that and what can cure it?

Update:  This project builds a DLL

答:
A possibility is that output path for project is wrong.
For checking output path : right click on Project and then click on Properties. Then in Build Tab check the value of field output path . It must be "bin\Debug\" .


问:
Fetching data from database in a loop
Is there a logical way to get the data from sql periodically? I want to fetch a row from a table in my postgres DB, run some calculations on it in my python script, and fetch the second row of the data and go on with this procedure till all the calculation has been done.

enter image description here

In the table above, I would like to fetch each array of the travel time, do the calculations on it in my python code, and then go to the 2nd row and so on.

答:
I believe your database library will provide you with a method for doing this. It might be called a cursor, a pointer or an iterator, which will have a method for fetching the next row from a query.

From https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html

```<code>cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()
</code>```

Title: Fetching data from database in a loop

Body:
I believe your database library will provide you with a method for doing this. It might be called a cursor, a pointer or an iterator, which will have a method for fetching the next row from a query.

From https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html

cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()


问:
How can I access variable inside another function jquery
I have this object and want to access the variable scrolled var scrolled = 10; from the init function within the scrollDown function.

I am having trouble accessing the variable. How can I achieve this?

```<code>// Summary Screen Functions
var summary = {
    init: function() {

        var scrolled = 0;

        $('.page-summary-action a').on('click', summary.continueToSummary);
        $('.scroll-down').on('click', summary.scrollDown);
        $('.scroll-up').on('click', summary.scrollUp);
    },

    scrollDown: function(e) {
        e.preventDefault();
        scrolled = scrolled + 300;

        console.log('clicked');

        $(".data-cards").animate({
            scrollTop:  scrolled
        });
    },

    scrollUp: function(e) {
        e.preventDefault();
        console.log('clicked');

        $(".data-cards").animate({
            scrollTop: 15
        });
    }
};

summary.init();
</code>```

答:
var scrolled = 0; // Put the variable in an outer scope
var summary = {
    init: function() {
        // access "scrolled"
        scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();
```

<p>or</p>

<pre class="lang-js prettyprint-override"><code>var summary = {
    scrolled: 0, // Make it a property of the "summary" object
    init: function() {
        // access "scrolled"
        summary.scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();
</code>```

Body:
I have this object and want to access the variable scrolled var scrolled = 10; from the init function within the scrollDown function.

I am having trouble accessing the variable. How can I achieve this?

// Summary Screen Functions
var summary = {
    init: function() {

        var scrolled = 0;

        $('.page-summary-action a').on('click', summary.continueToSummary);
        $('.scroll-down').on('click', summary.scrollDown);
        $('.scroll-up').on('click', summary.scrollUp);
    },

    scrollDown: function(e) {
        e.preventDefault();
        scrolled = scrolled + 300;

        console.log('clicked');

        $(".data-cards").animate({
            scrollTop:  scrolled
        });
    },

    scrollUp: function(e) {
        e.preventDefault();
        console.log('clicked');

        $(".data-cards").animate({
            scrollTop: 15
        });
    }
};

summary.init();

Body:
var scrolled = 0; // Put the variable in an outer scope
var summary = {
    init: function() {
        // access "scrolled"
        scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();

or

var summary = {
    scrolled: 0, // Make it a property of the "summary" object
    init: function() {
        // access "scrolled"
        summary.scrolled = 0;
    },

    scrollDown: function(e) {
        // access "scrolled"
    },

    scrollUp: function(e) {
        // ...
    }
};

summary.init();


问:
Retrieving Kodi MAC address shows 00:00:00:00:00
I am using an add on for Kodi that retrieves the MAC address from the android device.  This is used to verify the install on the correct device.
With Android TV boxes running lollipop and marshmallow it seems to be working correctly, but on tablets and phones it returns 00:00:00:00:00 as the MAC address, which obviously is not correct.   Any suggestions on how to fix this or get around it?</p>

答: 00:00:00:00:00 returns as the MAC address when vmware instances are started and left unconfigured they originate frames with all 0 source address. You can check it in this thread. Here's another post which might help: What could these IP addresses with MAC: 00:00:00:00:00:00 be?


问:
Tensorflow SEQ2SEQ training suddenly super slow
I was training seq2seq NMT (neural machine translation) using the code from https://google.github.io/seq2seq/. After I interrupted the training process, restarted process becomes super slow (from 1.2 step/second to 0.07 step/second). Does anyone else have this experience? How do I debug? I have running this for weeks, really do not want to give up... Thanks!~

The last line of normal training,

```<code>INFO:tensorflow:loss = 0.585205, step = 830853 (79.477 sec)
INFO:tensorflow:global_step/sec: 1.24179
INFO:tensorflow:loss = 0.267574, step = 830953 (80.529 sec)
</code>```

The first few line of super slow training ...

```<code>INFO:tensorflow:global_step/sec: 0.0746058
INFO:tensorflow:loss = 0.554718, step = 830854 (1340.379 sec)
</code>```

答:
Ah, after carefully going through log, it appears that one latest update on Cuda created the problem.AND automated updates removed the problem later on now. Here is the log ..</p>

```<code>2017-06-02 22:47:22.684229: E tensorflow/stream_executor/cuda/cuda_driver.cc:405] failed call to cuInit: CUDA_ERROR_NO_DEVICE
2017-06-02 22:47:22.684260: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:158] retrieving CUDA diagnostic information for host: POSingularity
2017-06-02 22:47:22.684276: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:165] hostname: POSingularity
2017-06-02 22:47:22.684305: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:189] libcuda reported version is: 375.66.0
2017-06-02 22:47:22.684331: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:369] driver version file contents: """NVRM version: NVIDIA UNIX x86_64 Kernel Module  375.51  Wed Mar 22 10:26:12 PDT
2017
GCC version:  gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
"""
2017-06-02 22:47:22.684352: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:193] kernel reported version is: 375.51.0
2017-06-02 22:47:22.684368: E tensorflow/stream_executor/cuda/cuda_diagnostics.cc:303] kernel version 375.51.0 does not match DSO version 375.66.0 -- cannot find working devices in this configuration
</code>```

Body:
I was training seq2seq NMT (neural machine translation) using the code from https://google.github.io/seq2seq/. After I interrupted the training process, restarted process becomes super slow (from 1.2 step/second to 0.07 step/second). Does anyone else have this experience? How do I debug? I have running this for weeks, really do not want to give up... Thanks!~

The last line of normal training,

INFO:tensorflow:loss = 0.585205, step = 830853 (79.477 sec)
INFO:tensorflow:global_step/sec: 1.24179
INFO:tensorflow:loss = 0.267574, step = 830953 (80.529 sec)

The first few line of super slow training ...

INFO:tensorflow:global_step/sec: 0.0746058
INFO:tensorflow:loss = 0.554718, step = 830854 (1340.379 sec)

Body:
Ah, after carefully going through log, it appears that one latest update on Cuda created the problem.AND automated updates removed the problem later on now. Here is the log ..

2017-06-02 22:47:22.684229: E tensorflow/stream_executor/cuda/cuda_driver.cc:405] failed call to cuInit: CUDA_ERROR_NO_DEVICE
2017-06-02 22:47:22.684260: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:158] retrieving CUDA diagnostic information for host: POSingularity
2017-06-02 22:47:22.684276: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:165] hostname: POSingularity
2017-06-02 22:47:22.684305: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:189] libcuda reported version is: 375.66.0
2017-06-02 22:47:22.684331: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:369] driver version file contents: """NVRM version: NVIDIA UNIX x86_64 Kernel Module  375.51  Wed Mar 22 10:26:12 PDT
2017
GCC version:  gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
"""
2017-06-02 22:47:22.684352: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:193] kernel reported version is: 375.51.0
2017-06-02 22:47:22.684368: E tensorflow/stream_executor/cuda/cuda_diagnostics.cc:303] kernel version 375.51.0 does not match DSO version 375.66.0 -- cannot find working devices in this configuration


问:
how to Copy files inside Azure Data lake store using C# .NET and Powershell
I want to copy the files from One folder to another folder on Azure Data Lake store. Is this possible through C# or Powershell?</p>

答:
Copying data is not currently supported by Data Lake Store as a built-in operation.

If you'd like to copy data, I recommend using the ADLCopy client. Another option is using Azure Data Factory's copy activity.


问:
How to determine which device is not registered
How to determine which particular device is "NotRegisterd".

I send message to some butch of devices. Here my body:

```<code>{
   "registration_ids": ["someCode1", "someCode2", "someCode3"],
   "notification": {...},
   "data": {...}
}
</code>```

And got response:

```<code>{
  "multicast_id": 6613705169343972705,
  "success": 1,
  "failure": 2,
  "canonical_ids": 0,
  "results": [
    {
      "error": "NotRegistered"
    },
    {
      "message_id": "0:1496749257460993%5fe3e4105fe3e410"
    },
    {
      "error": "NotRegistered"
    }]
}
</code>```

How to determine which devices not registered?
I have only one idea. The order of registration_ids is equal order of results.

答:
In Table 5 of the HTTP Server Protocol documentation it describes the results array as:

Array of objects representing the status of the messages processed.
The objects are listed in the same order as the request (i.e., for
each registration ID in the request, its result is listed in the same
index in the response)

So your guess is correct, the order of the results is the same order as the registration IDs.

Body:
How to determine which particular device is "NotRegisterd".

I send message to some butch of devices. Here my body:

{
   "registration_ids": ["someCode1", "someCode2", "someCode3"],
   "notification": {...},
   "data": {...}
}

And got response:

{
  "multicast_id": 6613705169343972705,
  "success": 1,
  "failure": 2,
  "canonical_ids": 0,
  "results": [
    {
      "error": "NotRegistered"
    },
    {
      "message_id": "0:1496749257460993%5fe3e4105fe3e410"
    },
    {
      "error": "NotRegistered"
    }]
}

How to determine which devices not registered?
I have only one idea. The order of registration_ids is equal order of results.


问:
Executing a powershell script on a remote computer file system
There is a powershell script located on the C:\. The script executes a .msu file.

Invoke-Command -ComputerName [name] -FilePath C:\file.txt doesn't work because it checks locally on your system for the file to pass over to execute.

I want a powershell script that executes another remote powershell script remotely.

答:
If you use powershell 5 on both sides you could copy the file via:
$TargetSession = New-PSSession -ComputerName server

Copy-Item -ToSession $TargetSession -Path "c:\local\" -Destination "C:\remote\" -Recurse

You could also use copy to admin share c$


问:
Python - Using gspread to create a spreadsheet in a specific folder in Google Drive
I'm trying to create a new spreadsheet using gspread, and I want to be able to control where it ends up.

```<code>    gc = gspread.authorize(credentials)

    sheetname = 'Test sheet'
    sheet = gc.create(sheetname)
</code>```

I think that what's happening is that when I do gc.create(sheetname), it's making it in my Google service account, but I want it to end up in a specific folder in my normal account.

-

--Figured it out--

Needed to change to the following:

```<code>if parent_folder_ids:
    body["parents"] = parent_folder_ids
</code>```

答:
You may refer with this tutorial.

```<code>def create_google_spreadsheet(title: str, parent_folder_ids: list=None, share_domains: list=None) -> Spreadsheet:
    """Create a new spreadsheet and open gspread object for it.
</code>```

Be noted that created spreadsheet is not instantly visible in your Drive search and you need to access it by direct link.

Body:
I'm trying to create a new spreadsheet using gspread, and I want to be able to control where it ends up.

    gc = gspread.authorize(credentials)

    sheetname = 'Test sheet'
    sheet = gc.create(sheetname)

I think that what's happening is that when I do gc.create(sheetname), it's making it in my Google service account, but I want it to end up in a specific folder in my normal account.

-

--Figured it out--

Needed to change to the following:

if parent_folder_ids:
    body["parents"] = parent_folder_ids

Body:
You may refer with this tutorial.

def create_google_spreadsheet(title: str, parent_folder_ids: list=None, share_domains: list=None) -> Spreadsheet:
    """Create a new spreadsheet and open gspread object for it.

Be noted that created spreadsheet is not instantly visible in your Drive search and you need to access it by direct link.


问:
Echo Option from 1 single column
Hello guys I have this table :

```<code>ID| NUM_Slides |P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12
3 | 2          |1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0   | 0   | 0
</code>```

I want to select the values only from P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11 and P12 and insert them into a <option> tag

I got this so far but dont work

```<code><?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12 FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 =$connect->query($query);
$resultado = $result1->fetch_all();
?>

<select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value=""<?php echo $row1[1];?>"><?php echo $row1[1];?>"</option>
<?php endwhile;?>
</select>
</code>```

because my query only return 1 array I want the Options to be display 1,1,0,0,0,0,0,0,0,0,0

can some 1 help me

答:
How about this?</p>

```<code><select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1))
{
    for($i=2; $i<13; $i++) {
        echo '<option value="'.$row1[$i]'">'.$row1[1].'</option>';
    }
}
?>
</select>
</code>```

Title: Echo Option from 1 single column

Body:
Hello guys I have this table :

ID| NUM_Slides |P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12
3 | 2          |1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0   | 0   | 0

I want to select the values only from P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11 and P12 and insert them into a <option> tag

I got this so far but dont work

<?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12 FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 =$connect->query($query);
$resultado = $result1->fetch_all();
?>

<select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value=""<?php echo $row1[1];?>"><?php echo $row1[1];?>"</option>
<?php endwhile;?>
</select>

because my query only return 1 array I want the Options to be display 1,1,0,0,0,0,0,0,0,0,0

can some 1 help me

Body:
How about this?

<select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1))
{
    for($i=2; $i<13; $i++) {
        echo '<option value="'.$row1[$i]'">'.$row1[1].'</option>';
    }
}
?>
</select>


问:
Do while loop runs more than once with flag set?
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

```<code>voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);
</code>```

答:
You are waiting for the voltage variable to change, without actually changing it (reading from analog pin).

You need to add voltage = analogRead(A0); into your loop.

```<code>do
{
    voltage = analogRead(A0);
    if ((voltage >= 1) && (voltage <= 10))   //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    {                                        //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
        ...

        flag = 1;
    }
} while (flag == 0);
</code>```

Body:
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);

Body:
You are waiting for the voltage variable to change, without actually changing it (reading from analog pin).

You need to add voltage = analogRead(A0); into your loop.

do
{
    voltage = analogRead(A0);
    if ((voltage >= 1) && (voltage <= 10))   //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    {                                        //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
        ...

        flag = 1;
    }
} while (flag == 0);


问:
Electron require() is not defined
I'm creating an Electron app for my own purpose. My problem is when I'm using node functions inside my HTML page it throws an error of:

'require()' is not defined.

Is there any way to use Node functionalities in all my HTML pages? If it is possible please give me an example of how to do this or provide a link. Here are the variables I'm trying to use in my HTML page:

```<code>  var app = require('electron').remote;
  var dialog = app.dialog;
  var fs = require('fs');
</code>```

and these are the values I'm using in all my HTML windows within Electron.

答:
Are you using nodeIntegration: false while BrowserWindow initialization? If so, set it to true (defaults value is true).

And include your external scripts in the HTML like this (not as ):

```<code><script>
   require('./index.js')
</script>
</code>```

Title: Electron require() is not defined

Body:
I'm creating an Electron app for my own purpose. My problem is when I'm using node functions inside my HTML page it throws an error of:

'require()' is not defined.

Is there any way to use Node functionalities in all my HTML pages? If it is possible please give me an example of how to do this or provide a link. Here are the variables I'm trying to use in my HTML page:

  var app = require('electron').remote;
  var dialog = app.dialog;
  var fs = require('fs');

and these are the values I'm using in all my HTML windows within Electron.

Body:
Are you using nodeIntegration: false while BrowserWindow initialization? If so, set it to true (defaults value is true).

And include your external scripts in the HTML like this (not as <script> src="./index.js" </script>):

<script>
   require('./index.js')
</script>


问:
Algorithm to find subset within two sets of integers whose sums match
I'm looking for an algorithm which can take two sets of integers (both positive and negative) and find subsets within each that have the same sum.

The problem is similar to the subset sum problem except that I'm looking for subsets on both sides.

Here's an example:

List A {4, 5, 9, 10, 1}

List B {21, 7, -4, 180}

So the only match here is:
{10, 1, 4, 9} <=> {21, 7, -4}

Does anyone know if there are existing algorithms for this kinda problems?

So far, the only solution I have is a brute force approach which tries every combination but it performs in Exponential time and I've had to put a hard limit on the number of elements to consider to avoid it from taking too long.

The only other solution I can think of is to run a factorial on both lists and look for equalities there but that is still not very efficient and takes exponentially longer as the lists get bigger.

答:
What others have said is true:

This problem is NP-complete.  An easy reduction is to usual subset-sum.  You can show this by noting that a subset of A sums to a subset of B (not both empty) only if a non-empty subset of A union (-B) sums to zero.

This problem is only weakly NP-complete, in that it's polynomial in the size of the numbers involved, but is conjectured to be exponential in their logarithms.  This means that the problem is easier than the moniker "NP-complete" might suggest.

You should use dynamic programming.

So what am I contributing to this discussion?  Well, code (in Perl):

```<code>@a = qw(4 5 9 10 1);
@b = qw(21 7 -4 180);
%a = sums( @a );
%b = sums( @b );
for $m ( keys %a ) {
    next unless exists $b{$m};
    next if $m == 0 and (@{$a{0}} == 0 or @{$b{0}} == 0);
    print "sum(@{$a{$m}}) = sum(@{$b{$m}})\n";
}

sub sums {
    my( @a ) = @_;
    my( $a, %a, %b );
    %a = ( 0 => [] );
    while( @a ) {
        %b = %a;
        $a = shift @a;
        for my $m ( keys %a ) {
            $b{$m+$a} = [@{$a{$m}},$a];
        }
    %a = %b;
    }
    return %a;
}
</code>```

It prints

```<code>sum(4 5 9 10) = sum(21 7)
sum(4 9 10 1) = sum(21 7 -4)
</code>```

so, notably, there is more than one solution that works in your original problem!

Edit: User itzy correctly pointed out that this solution was wrong, and worse, in multiple ways!!  I'm very sorry about that and I've hopefully addressed these concerns in the new code above.  Nonetheless, there is still one problem, namely that for any particular subset-sum, it only prints one of the possible solutions.  Unlike the previous problems, which were straight-up errors, I would classify this as an intentional limitation.  Best of luck and beware of bugs!

OwnerDisplayName: theburningmonk

LastEditorDisplayName: Andrew Rollings

Body:
What others have said is true:

This problem is NP-complete.  An easy reduction is to usual subset-sum.  You can show this by noting that a subset of A sums to a subset of B (not both empty) only if a non-empty subset of A union (-B) sums to zero.

This problem is only weakly NP-complete, in that it's polynomial in the size of the numbers involved, but is conjectured to be exponential in their logarithms.  This means that the problem is easier than the moniker "NP-complete" might suggest.

You should use dynamic programming.

So what am I contributing to this discussion?  Well, code (in Perl):

@a = qw(4 5 9 10 1);
@b = qw(21 7 -4 180);
%a = sums( @a );
%b = sums( @b );
for $m ( keys %a ) {
    next unless exists $b{$m};
    next if $m == 0 and (@{$a{0}} == 0 or @{$b{0}} == 0);
    print "sum(@{$a{$m}}) = sum(@{$b{$m}})\n";
}

sub sums {
    my( @a ) = @_;
    my( $a, %a, %b );
    %a = ( 0 => [] );
    while( @a ) {
        %b = %a;
        $a = shift @a;
        for my $m ( keys %a ) {
            $b{$m+$a} = [@{$a{$m}},$a];
        }
    %a = %b;
    }
    return %a;
}

It prints

sum(4 5 9 10) = sum(21 7)
sum(4 9 10 1) = sum(21 7 -4)

so, notably, there is more than one solution that works in your original problem!

Edit: User itzy correctly pointed out that this solution was wrong, and worse, in multiple ways!!  I'm very sorry about that and I've hopefully addressed these concerns in the new code above.  Nonetheless, there is still one problem, namely that for any particular subset-sum, it only prints one of the possible solutions.  Unlike the previous problems, which were straight-up errors, I would classify this as an intentional limitation.  Best of luck and beware of bugs!

OwnerDisplayName: A. Rex


问:
How to write a shell script that runs next command even if current command fails?
I currently need to automate a task where I need to execute 5 commands, even if any command fails, all next commands should get executed, currently if 4th commands fails, shell script exits and dont run 5th command.

So, what should I do so that, shell script run all the next commands even if current command fails?

答:
Well, what's wrong with code below?</p>

```<code>#!/bin/bash
cmd1
cmd2
cmd3
cmd4
cmd5
</code>```

Body:
Well, what's wrong with code below?

#!/bin/bash
cmd1
cmd2
cmd3
cmd4
cmd5