答:
Nested like this

/*
   CSS for Lounge Project
   Filename: styles.css

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
*/

/*Reset Styles*/

html,
body {
  font-size: 14px;
  width: 100%;
}

a,
body,
footer,
header,
h1,
h2,
h3,
img,
li,
nav,
p,
ul,
table,
tbody,
td,
tfoot,
th,
thead,
tr {
  border: 0;
  padding: 0;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto;
  width: auto;
}

/*Drink font colors*/

h2.green {
  color: green;
}

h2.blue {
  color: blue;
}

h2.purple {
  color: purple;
}

h2.red {
  color: red;
}

h2.yellow {
  color: gold;
}

/*center and border image*/

img.smlounge {
  display: block;
  margin-left: auto;
  margin-right: auto;
  border: 3px solid;
  border-color: red;
}

/*Table styles*/

td,
th {
  border: 1px solid black;
  font-size: 1.3em;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding: 0 1em;
}

table {
  border-collapse: collapse;
  margin: 0 auto;
}

td[colspan="2"] {
  width: 20%;
}

.drink-name {
  text-align: left;
}

.mintable {
  border-collapse: initial;
  font-size: 0.9em;
}

tbody {
  border: solid black 1px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <!--
   Elixir page for Lounge Project
   Filename: elixir.html

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
   -->

  <link type="text/css" rel="stylesheet" href="../lounge.css" />
</head>

<body>
  <h1>Our Elixirs</h1>

  <h2 class="green">Green Tea Cooler</h2>
  <p>
    <img src="../images/green.jpg" alt="Green Tea Cooler" /> Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.
  </p>
  <hr/>
  <h2 class="blue">Raspberry Ice Concentration</h2>
  <p>
    <img src="../images/lightblue.jpg" alt="Rasberry Ice Concentration" /> Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.
  </p>
  <hr/>
  <h2 class="purple">Blueberry Bliss Elixir</h2>
  <p>
    <img src="../images/blue.jpg" alt="Blueberry Bliss Elixir" /> Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.
  </p>
  <hr/>
  <h2 class="red">Cranberry Antioxidant Blast</h2>
  <p>
    <img src="../images/red.jpg" alt="Cranberry Antioxidant Blast" /> Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.
  </p>
  <hr/>
  <h2 class="yellow">Lemon Breeze</h2>
  <p><img src="../images/yellow.gif" alt="Lemon Breeze Drink" /> The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.
  </p>
  <hr/>
  <br/>
  <table>
    <thead>
      <tr>
        <th colspan="6">Our Drink Prices</th>
      </tr>
      <tr>
        <th colspan="2">Drink</th>
        <th colspan="2">Size</th>
        <th colspan="2">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Green Tea Cooler</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Raspberry Ice Concentration</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td colspan="2" class="drink-name">Cranberry Antioxidant Blast</td>
        <td colspan="2">20 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Lemon Breeze</td>
        <td rowspan="2" colspan="2">
          <table class="mintable">
            <tr>
              <td>Iced</td>
              <td>16 oz.</td>
            </tr>
            <tr>
              <td>Frozen</td>
              <td>20 oz.</td>

            </tr>

          </table>

        </td>
        <td>
          <table class="mintable">
            <tr rowspan="2" colspan="2">
              <td>$4.75</td>
            </tr>
            <tr>
              <td>$3.75</td>
            </tr>
          </table>

        </td>
      </tr>
      <td></td>
    </tbody>
  </table>

  <br>
  <p>Back to the Lounge</p>

  <footer>
    ©2016, Head First Online Lounge<br /> All trademarks and registered trademarks appearing on this site are the property of their respective owners.
  </footer>
</body>

</html></code>```

Title: How to nest a table within a table?

Body:
Nested like this

/*
   CSS for Lounge Project
   Filename: styles.css

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
*/

/*Reset Styles*/

html,
body {
  font-size: 14px;
  width: 100%;
}

a,
body,
footer,
header,
h1,
h2,
h3,
img,
li,
nav,
p,
ul,
table,
tbody,
td,
tfoot,
th,
thead,
tr {
  border: 0;
  padding: 0;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto;
  width: auto;
}

/*Drink font colors*/

h2.green {
  color: green;
}

h2.blue {
  color: blue;
}

h2.purple {
  color: purple;
}

h2.red {
  color: red;
}

h2.yellow {
  color: gold;
}

/*center and border image*/

img.smlounge {
  display: block;
  margin-left: auto;
  margin-right: auto;
  border: 3px solid;
  border-color: red;
}

/*Table styles*/

td,
th {
  border: 1px solid black;
  font-size: 1.3em;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding: 0 1em;
}

table {
  border-collapse: collapse;
  margin: 0 auto;
}

td[colspan="2"] {
  width: 20%;
}

.drink-name {
  text-align: left;
}

.mintable {
  border-collapse: initial;
  font-size: 0.9em;
}

tbody {
  border: solid black 1px
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Head First Lounge Elixirs</title>

  <!--
   Elixir page for Lounge Project
   Filename: elixir.html

   Author:   Justus Self
   Date:     3/21/17
   HTML5 and CSS3 Illustrated Unit I, Lounge Independent Project
   -->

  <link type="text/css" rel="stylesheet" href="../lounge.css" />
</head>

<body>
  <h1>Our Elixirs</h1>

  <h2 class="green">Green Tea Cooler</h2>
  <p>
    <img src="../images/green.jpg" alt="Green Tea Cooler" /> Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.
  </p>
  <hr/>
  <h2 class="blue">Raspberry Ice Concentration</h2>
  <p>
    <img src="../images/lightblue.jpg" alt="Rasberry Ice Concentration" /> Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.
  </p>
  <hr/>
  <h2 class="purple">Blueberry Bliss Elixir</h2>
  <p>
    <img src="../images/blue.jpg" alt="Blueberry Bliss Elixir" /> Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.
  </p>
  <hr/>
  <h2 class="red">Cranberry Antioxidant Blast</h2>
  <p>
    <img src="../images/red.jpg" alt="Cranberry Antioxidant Blast" /> Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.
  </p>
  <hr/>
  <h2 class="yellow"><a name="Yellow">Lemon Breeze</a></h2>
  <p><img src="../images/yellow.gif" alt="Lemon Breeze Drink" /> The ultimate healthy drink, this elixir combines herbal botanicals, minerals, and vitamins with a twist of lemon into a smooth citrus wonder that will keep your immune system going all day
    and all night.
  </p>
  <hr/>
  <br/>
  <table>
    <thead>
      <tr>
        <th colspan="6">Our Drink Prices</th>
      </tr>
      <tr>
        <th colspan="2">Drink</th>
        <th colspan="2">Size</th>
        <th colspan="2">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Green Tea Cooler</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Raspberry Ice Concentration</td>
        <td colspan="2">16 oz.</td>
        <td colspan="2">$3.75</td>
      </tr>
      <tr>
        <td colspan="2">24 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td colspan="2" class="drink-name">Cranberry Antioxidant Blast</td>
        <td colspan="2">20 oz.</td>
        <td colspan="2">$4.75</td>
      </tr>
      <tr>
        <td rowspan="2" colspan="2" class="drink-name">Lemon Breeze</td>
        <td rowspan="2" colspan="2">
          <table class="mintable">
            <tr>
              <td>Iced</td>
              <td>16 oz.</td>
            </tr>
            <tr>
              <td>Frozen</td>
              <td>20 oz.</td>

            </tr>

          </table>

        </td>
        <td>
          <table class="mintable">
            <tr rowspan="2" colspan="2">
              <td>$4.75</td>
            </tr>
            <tr>
              <td>$3.75</td>
            </tr>
          </table>

        </td>
      </tr>
      <td></td>
    </tbody>
  </table>

  <br>
  <p><a href="../lounge.html">Back to the Lounge</a></p>

  <footer>
    &#169;2016, Head First Online Lounge<br /> All trademarks and registered trademarks appearing on this site are the property of their respective owners.
  </footer>
</body>

</html>


来源: stackexchange

问:
Regex java issue code not working
I have an issue with a little regex code I wrote. The code basically checks my "longString" which contains the string that's being checked and outputs the words in the string that matches the regex.

```<code>import java.util.regex.*;

public class regexPractice
{

    public static void main(String[] args) {
        String  longString = " Derek Banas CA ";

        regexChecker(longString, "\\s[A-Za-z]{2,20}\\s");
    }

    public static void regexChecker(String theregex, String stringCheck) {
        //theregex is the regex your searching for

        Pattern Checkregex = Pattern.compile(theregex);

        Matcher regexMatcher = Checkregex.matcher(stringCheck);

        while (regexMatcher.find()) { //kicks out all the matches for you
            if (regexMatcher.group().length() != 0) {
                System.out.println(regexMatcher.group().trim());
                //trim gets rid of all the white space
            }
        }
    }
}
</code>```

When I run the code nothing shows up not even an error message. I rechecked my code and didn't find any errors.

By the way, I'm using android studio.

答: You are passing in your arguments in the wrong order.  The method signature has them reversed</p>

ContentLicense: CC BY-SA 3.0

Title: Regex java issue code not working

Body:
I have an issue with a little regex code I wrote. The code basically checks my "longString" which contains the string that's being checked and outputs the words in the string that matches the regex.

import java.util.regex.*;

public class regexPractice
{

    public static void main(String[] args) {
        String  longString = " Derek Banas CA ";

        regexChecker(longString, "\\s[A-Za-z]{2,20}\\s");
    }

    public static void regexChecker(String theregex, String stringCheck) {
        //theregex is the regex your searching for

        Pattern Checkregex = Pattern.compile(theregex);

        Matcher regexMatcher = Checkregex.matcher(stringCheck);

        while (regexMatcher.find()) { //kicks out all the matches for you
            if (regexMatcher.group().length() != 0) {
                System.out.println(regexMatcher.group().trim());
                //trim gets rid of all the white space
            }
        }
    }
}

When I run the code nothing shows up not even an error message. I rechecked my code and didn't find any errors.

By the way, I'm using android studio.


问:
how to get and parse value from  tag in php code?
currently i have problem with this  tag.
I cannot get the value for this label to store in my database.

```<code><label class="autopopulate4" size="5" for="totalscore" id="totalscore" name="totalscore">100</label>
</code>```

The above code is the label tag.

Can anybody help me to solve this problem ?

How to get and parse the updated value into database ?

Do i have other alternative to make this happen ?

Thank you in advance.

答:
If you are sending data at server side using Ajax then you can get label value in J's variable using below jQuery and then pass it in Ajax parameters to send server side.

Var labelval = $('#totalscore').html();

Title: how to get and parse value from <label> tag in php code?

Body:
currently i have problem with this  tag.
I cannot get the value for this label to store in my database.

100

The above code is the label tag.

Can anybody help me to solve this problem ?

How to get and parse the updated value into database ?

Do i have other alternative to make this happen ?

Thank you in advance.


问:
Definitive books/resources on web application scalability?
What are the best, up-to-date, resources on web application scalability?

Any resource will do, books recommendations are preferred.

Alternative question - if you needed to recommend one book which covers web scalability, which would it be?

答:
This is a slightly different answer than you may be looking for, but check out some of the slideshows on it at SlideShare. Also, look for blogs of developers at semi-large to large companies.  I've read quite a few interesting articles that talk about scalability issues.

I also recommend checking out High Scalability.

ContentLicense: CC BY-SA 2.5


问:
C# DateTime format in Arrays
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.</p>

```<code>private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}
</code>```

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

```<code>string sDate = "6/16/1989";
Console.WriteLine(Convert.ToDateTime(sDate).ToString("MM-dd-yyyy"));
</code>```

Output is this:

```<code>06-16-1989
</code>```

Hope it helps!

Title: C# DateTime format in Arrays

Body:
Currently my function outputs date as 6/6/2016 and I need to be able to make it as 06/06/2016 for all the data. I found DateTime.Now.ToString("dd") is a solution. But when I do parts[0].DateTime.Now.ToString("dd") it doesn't accept it.

private static string FormatDate(string sDate)
{
    // "6/16/1989"
    //mysql format 06-16-1989

    string[] parts = sDate.Split('/');

    //sDay.DateTime.Now.ToString("dd");

    return $"'{parts[2]}-{parts[1]}-{parts[0]}'";
}

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

string sDate = "6/16/1989";
Console.WriteLine(Convert.ToDateTime(sDate).ToString("MM-dd-yyyy"));

Output is this:

06-16-1989

Hope it helps!


问:
Order By 2 columns
I have this table and .

```<code> id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25
</code>```

I want to order by created_at and also at the same time order by item_id like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

So if i add a new row for item_id: Grape my new results should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
</code>```

and then if i add new row for item_id: Apple it should be like this:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
</code>```

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

```<code> id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21
</code>```

答:
You need to first identify your first rule which is get the max created_at per item_id, therefore the subquery with the item_id grouped and a row_number() added so it can know which fruit cames first. Then just join with your table.

```<code>SELECT tt.id, tt.item_id, tt.created_at
  FROM test_table tt
         INNER JOIN
      (SELECT item_id,
              MAX(created_at),
              ROW_NUMBER() OVER (ORDER BY MAX(created_at) DESC) rn
         FROM test_table
        GROUP BY item_id
        ORDER BY 3) ord
     ON tt.item_id = ord.item_id
 ORDER BY ord.rn, tt.created_at DESC;
</code>```

Title: Order By 2 columns

Body:
I have this table and .

 id  |  item_id  | created_at
-----+-----------+------------
  1  |   Apple   | 2017-03-21
  2  |   Grape   | 2017-03-23
  3  |   Grape   | 2017-03-24
  4  |   Apple   | 2017-03-25

I want to order by created_at and also at the same time order by item_id like this:

 id  |  item_id  | created_at
-----+-----------+------------
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

So if i add a new row for item_id: Grape my new results should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  5  |   Grape   | 2017-03-28  (NEW)
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21

and then if i add new row for item_id: Apple it should be like this:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28  (NEW)
  4  |   Apple   | 2017-03-25
  1  |   Apple   | 2017-03-21
  5  |   Grape   | 2017-03-27
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23

...So it orders by the latest created_at and show the other rows with the same item_id below it

I have tried ORDER BY created_at, item_id  DESC but it does not works and give me this instead:

 id  |  item_id  | created_at
-----+-----------+------------
  6  |   Apple   | 2017-03-28
  5  |   Grape   | 2017-03-27
  4  |   Apple   | 2017-03-25
  3  |   Grape   | 2017-03-24
  2  |   Grape   | 2017-03-23
  1  |   Apple   | 2017-03-21

Body:
You need to first identify your first rule which is get the max created_at per item_id, therefore the subquery with the item_id grouped and a row_number() added so it can know which fruit cames first. Then just join with your table.

SELECT tt.id, tt.item_id, tt.created_at
  FROM test_table tt
         INNER JOIN
      (SELECT item_id,
              MAX(created_at),
              ROW_NUMBER() OVER (ORDER BY MAX(created_at) DESC) rn
         FROM test_table
        GROUP BY item_id
        ORDER BY 3) ord
     ON tt.item_id = ord.item_id
 ORDER BY ord.rn, tt.created_at DESC;


问:
Firebase authentication timeout with Google account login
Please can anyone help with config/troubleshooting for Firebase authentication with GAE Python apps.

I've tried to get the Firenotes app working (https://cloud.google.com/appengine/docs/python/authenticating-users-firebase-appengine) but when the app loads there's a popup with the error: The operation has timed out. Dismiss.

The email authentication works fine, all OK: can login, save notes, logout.

The problem is with the Google OAuth login.
Clicking on the Google sign button gives an error:
This site can’t provide a secure connection.
firebaseapp.com didn’t accept your login certificate, or your login certificate may have expired.
ERR_BAD_SSL_CLIENT_AUTH_CERT

The project was imported into the firebase project and as far as I can tell the config of main.js and app.yaml is correct.
The GAE .appspot.com has been added to the OAuth authorized doamins

The same error is if running local or deployed to GAE.

答:
If you go to the 'Overview' section of your firebase console. You can select to "add firebase to your web app". A screen pops up with the config information for the frontend main.js file.

Mind you, the apiKey in the client config needs to be set to the google cloud platform api key for the app engine project your using.

This will enable the login.


问:
Using Eigen Matrix as template
Kindly help me convert this function so that it can accept MatrixXf, Matrix3f, Matrix4f, I read the Eigen manual which recommends using MatrixBase but that didn't work, neither did the Eigen::Ref class. Thank you.     </p>

```<code>void MatrixIO::FEigentoFile(const Eigen::MatrixXf& in_mat,
                            const std::string filename)
{
  fmat fmat_pb;
  fmat_pb.set_rows(in_mat.rows());
  fmat_pb.set_cols(in_mat.cols());
  fmat_pb.mutable_data()->Reserve(in_mat.rows() * in_mat.cols());
  for (int i = 0; i < in_mat.rows(); i++)
  {
    for (int j = 0; j < in_mat.cols(); j++)
    {
      float c = in_mat(i, j);
      fmat_pb.add_data(c);
    }
  }
  std::fstream output(filename,
                      std::ios::out | std::ios::trunc | std::ios::binary);
  if (!fmat_pb.SerializeToOstream(&output))
  {
    LOG(INFO) << "Failed to write to file." << std::endl;
  }
  return;
}
</code>```

答:
```<code>template<typename Derived>
void FEigentoFile(const Eigen::EigenBase<Derived> &in_mat, const std::string filename)
</code>```

<p>This should accept MatrixX* as argument. </p>

Title: Using Eigen Matrix as template

Body:
Kindly help me convert this function so that it can accept MatrixXf, Matrix3f, Matrix4f, I read the Eigen manual which recommends using MatrixBase but that didn't work, neither did the Eigen::Ref class. Thank you.

void MatrixIO::FEigentoFile(const Eigen::MatrixXf& in_mat,
                            const std::string filename)
{
  fmat fmat_pb;
  fmat_pb.set_rows(in_mat.rows());
  fmat_pb.set_cols(in_mat.cols());
  fmat_pb.mutable_data()->Reserve(in_mat.rows() * in_mat.cols());
  for (int i = 0; i < in_mat.rows(); i++)
  {
    for (int j = 0; j < in_mat.cols(); j++)
    {
      float c = in_mat(i, j);
      fmat_pb.add_data(c);
    }
  }
  std::fstream output(filename,
                      std::ios::out | std::ios::trunc | std::ios::binary);
  if (!fmat_pb.SerializeToOstream(&output))
  {
    LOG(INFO) << "Failed to write to file." << std::endl;
  }
  return;
}

Body:
template<typename Derived>
void FEigentoFile(const Eigen::EigenBase<Derived> &in_mat, const std::string filename)

This should accept MatrixX* as argument.


问:
Can Cloud Functions for Firebase be set up to work with Unity?
I'm trying to set up a cloud function to use in my Realtime Database. I went to the setup page and the instructions do not appear to be for Firebase for Unity. Is it not possible to use cloud functions with Unity or am I reading the instructions wrong?</p>

答: Cloud Functions for Firebase operates completely independently of any client SDK.  It facilitates server-side development, not client-side.  It's not at all opinionated about what platform(s) your app is built on.</p>


问:
How to organize the directory used for a distributable Python module?
I'm creating a Python module. My question is how can I organize the distribution such that it has a directory structure similar to most of the standard Python modules. Is there anything similar to MakeFile in Python which has setup.py file name?

Directory Structure:

```<code>pymodule_x-y.tar.gz/
                   + pymodule/
                             + __init__.py
                             + pymodule.py
                   + setup.cfg
                   + setup.py
                   + test/
                         + test_case.py
</code>```

答: You have several options, including distributing egg files, tarballs, etc. A great resource on distributing Python packages is The Hitchhiker's Guide to Packaging (still under development, but good nonetheless).</p>

Body:
I'm creating a Python module. My question is how can I organize the distribution such that it has a directory structure similar to most of the standard Python modules. Is there anything similar to MakeFile in Python which has setup.py file name?

Directory Structure:

pymodule_x-y.tar.gz/
                   + pymodule/
                             + __init__.py
                             + pymodule.py
                   + setup.cfg
                   + setup.py
                   + test/
                         + test_case.py


问:
How to write Unicode data as Cyrillic symbols to file?
I have some variables in Unicode.

```<code>title

 u'\u0410\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442-\u043c\u0430\u0433\u0430\u0437\u0438\u043d\u0430'

type(title)

 unicode
</code>```

If I print this vaiable, I get:

```<code> print (title)

  Администратор интернет-магазин
</code>```

When I try to write this data (Cyrillic symbols) to CSV file:

```<code> with open('avito.csv','a') as f:
      writer=csv.writer(f)
      writer.writerow((title))
</code>```

This error occurs:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0410' in position 0: ordinal not in range(128)
```

How can I write this variable as Cyrillic symbols to a CSV?

答:
Three ways on Python 2.7.  Note that to open the files in Excel that program likes a UTF-8 BOM encoded at the start of the file.  I write it manually in the brute force method, but the utf-8-sig codec will handle it for you otherwise.  Skip the BOM signature if you aren't dealing with lame editors (Windows Notepad) or Excel.

```<code>import csv
import codecs
import cStringIO

title = u'\u0410\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442-\u043c\u0430\u0433\u0430\u0437\u0438\u043d\u0430'
print(title)

# Brute force

with open('avito.csv','wb') as f:
    f.write(u'\ufeff'.encode('utf8')) # writes "byte order mark" UTF-8 signature
    writer=csv.writer(f)
    writer.writerow([title.encode('utf8')])

# Example from the documentation for csv module

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

with open('avito2.csv','wb') as f:
    w = UnicodeWriter(f)
    w.writerow([title])

# 3rd party module, install from pip

import unicodecsv
with open('avito3.csv','wb') as f:
    w = unicodecsv.writer(f,encoding='utf-8-sig')
    w.writerow([title])
</code>```

Body:
I have some variables in Unicode.

title

 u'\u0410\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442-\u043c\u0430\u0433\u0430\u0437\u0438\u043d\u0430'

type(title)

 unicode

If I print this vaiable, I get:

 print (title)

  Администратор интернет-магазин

When I try to write this data (Cyrillic symbols) to CSV file:

 with open('avito.csv','a') as f:
      writer=csv.writer(f)
      writer.writerow((title))

This error occurs:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0410' in position 0: ordinal not in range(128)

How can I write this variable as Cyrillic symbols to a CSV?

Body:
Three ways on Python 2.7.  Note that to open the files in Excel that program likes a UTF-8 BOM encoded at the start of the file.  I write it manually in the brute force method, but the utf-8-sig codec will handle it for you otherwise.  Skip the BOM signature if you aren't dealing with lame editors (Windows Notepad) or Excel.

import csv
import codecs
import cStringIO

title = u'\u0410\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u043e\u0440 \u0438\u043d\u0442\u0435\u0440\u043d\u0435\u0442-\u043c\u0430\u0433\u0430\u0437\u0438\u043d\u0430'
print(title)

# Brute force

with open('avito.csv','wb') as f:
    f.write(u'\ufeff'.encode('utf8')) # writes "byte order mark" UTF-8 signature
    writer=csv.writer(f)
    writer.writerow([title.encode('utf8')])

# Example from the documentation for csv module

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

with open('avito2.csv','wb') as f:
    w = UnicodeWriter(f)
    w.writerow([title])

# 3rd party module, install from pip

import unicodecsv
with open('avito3.csv','wb') as f:
    w = unicodecsv.writer(f,encoding='utf-8-sig')
    w.writerow([title])


问:
ASP.Net MasterPage with Bootstrap Popup Modal & Content Pages With Code Behind
I have created an ASP.Net Master page with Bootstrap 3.3.7 and Jquery 3.1.0.

Default.master

```<code><%@ Master Language="C#" AutoEventWireup="true"   CodeBehind="Default.master.cs" Inherits="BootStrap_With_ASPDotNet.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is My Site Using BootStrap in ASP.Net</title>

<!-- Bootstrap -->
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"    integrity="sha384-  BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

     <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
     <!--<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">       </script>-->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">    </script>

      <!-- Include all compiled plugins (below), or include individual files as needed -->
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

     <!-- Font Awesome inclusion for the icons on the pages -->
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text\css" />

     <!-- Adding Google Web Fonts to Bootstrap -->
     <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet" />

     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js">  </script>
     <![endif]-->
     <link href="custom/custom.css" rel="stylesheet" type="text\css" />

     <!-- Adding a web font -->
     <!--<link href="https://fonts.googleapis.com/css?family=Open+Sans"    rel="stylesheet" type="text/css />-->

          <script type="text/javascript">
             function openModal() {
                 $('#myModal').modal('show');
           }

        </script>
 </head>
 <body>
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>
     <!--Bootstrap Modal (Dialog Box / Pop-up Window) Example-->
     <div id="MyModal" class="modal fade" role="dialog" runat="server">
        <div class="modal-dialog" runat="server">
            <div class="modal-content" runat="server">
                <div class="modal-header" runat="server">
                    <button type="button" class="close" data-   dismiss="modal">×</button>
                     <h4>This is Modal Header</h4>
                 </div>
                 <div class="modal-body" runat="server">This is Modal Body
                  </div>
                  <div class="modal-footer" runat="server">This is Modal Footer
                      <button type="button" class="btn btn-default" data-dismiss="modal" runat="server">Close</button>
                 </div>
              </div>
          </div>
      </div>
      <!-- End of Bootstrap Model (Dialog Box / Popup Window)-->
  </body>
 </html>
</code>```

As you can see I have placed a Popup Dialog at the bottom of the MasterPage so that every instance of the MasterPage i.e. Content Pages will be use this.

Also I have created a JavaScript Function called 'openModal()' has created at the head of the MasterPage to use across all the content pages.

Now I have created a content page 'WebForm1.aspx' using the previously created MasterPage and added a button. Please refer the code below.

WebForm1.aspx

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Default.Master"
        AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
        Inherits="BootStrap_With_ASPDotNet.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="btnClickMe" runat="server" OnClick="btnClickMe_Click"
     Text="Click Me" CssClass="btn btn-danger"/>
</asp:Content>
</code>```

What I want is when I click the button it should show the popup and I need to do it from code behind. See below what I have tried.

```<code>protected void btnClickMe_Click(object sender, EventArgs e)
{
   ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}
</code>```

However it's not working. I can't figure it out why. So could someone help me on this?

Thanks

答:
I got the answer by my self. Please refer the below information.

First place the below JS code in the .

```<code>     function openModal() {
         $('#myModal').modal('show');
     }
</code>```

Second In server side on button click add the below function()

ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);

Body:
I have created an ASP.Net Master page with Bootstrap 3.3.7 and Jquery 3.1.0.

Default.master

<%@ Master Language="C#" AutoEventWireup="true"   CodeBehind="Default.master.cs" Inherits="BootStrap_With_ASPDotNet.Default" %>

<!DOCTYPE html>

<title>This is My Site Using BootStrap in ASP.Net</title>

     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"    integrity="sha384-  BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text\css" />

     <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet" />

     <link href="custom/custom.css" rel="stylesheet" type="text\css" />

        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>

                    <button type="button" class="close" data-   dismiss="modal">×</button>

This is Modal Header

This is Modal Body

This is Modal Footer
                      <button type="button" class="btn btn-default" data-dismiss="modal" runat="server">Close</button>

As you can see I have placed a Popup Dialog at the bottom of the MasterPage so that every instance of the MasterPage i.e. Content Pages will be use this.

Also I have created a JavaScript Function called 'openModal()' has created at the head of the MasterPage to use across all the content pages.

Now I have created a content page 'WebForm1.aspx' using the previously created MasterPage and added a button. Please refer the code below.

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Default.Master"
        AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
        Inherits="BootStrap_With_ASPDotNet.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="btnClickMe" runat="server" OnClick="btnClickMe_Click"
     Text="Click Me" CssClass="btn btn-danger"/>
</asp:Content>

What I want is when I click the button it should show the popup and I need to do it from code behind. See below what I have tried.

protected void btnClickMe_Click(object sender, EventArgs e)
{
   ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}

However it's not working. I can't figure it out why. So could someone help me on this?

Thanks

Body:
I got the answer by my self. Please refer the below information.

First place the below JS code in the .

     function openModal() {
         $('#myModal').modal('show');
     }

Second In server side on button click add the below function()

ScriptManager.RegisterStartupScript(this, this.GetType(), "LaunchServerSide", "$(function() { openModal(); });", true);


问:
Python 3 Float Decimal Points/Precision
I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point.

Assume I have a text file with the numbers -3.65, 9.17, 1. I read each one, and once I convert them to float and append them to a list. Now in Python 2, calling float(-3.65) returns -3.65. In Python 3 however, float(-3.65) returns -3.6499999999999999 which loses its precision.

I want to print the list of floats, [-3.6499999999999999, 9.1699999999999999, 1.0] with 2 decimal points only. Doing something along the lines of '%.1f' % round(n, 1) would return a string. How can I return a list of all two decimal points of floats, and not strings? So far, I rounded it using [round(num, 2) for num in list] but would need to set the decimal points / precision instead of round().

答:
The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

```<code>>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'
</code>```

or equivalently with f-strings (Python 3.6+):

```<code>>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'
</code>```

As always, the float value is an approximation:

```<code>>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'
</code>```

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

ContentLicense: CC BY-SA 4.0

Title: Python 3 Float Decimal Points/Precision

Body:
The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.


问:
UISlider not progressing smoothly
I have two UIViewControllers and each one has a UISlider. One slider tracks the progress of an audio file playing from AVPlayer the other viewcontroller slider tracks the progress of an audio file playing from AVAudioPlayer. The slider responding to AVPlayer animates perfectly smooth while the animation for the slider responding to AVAudioPlayer is not smooth. The sliders are set up exactly the same except for how I obtain the current time of each player as shown below:

```<code>//AVPlayer slider

func trackAudio() {
    let currentTime = self.newPlayer!.currentTime()
    let currentTimeInSeconds = CMTimeGetSeconds(currentTime)
    slider.setValue(Float(currentTimeInSeconds), animated: true)
}

//AVAudioPlayer Slider

func trackAudio() {
    let currentTime = self.player!.currentTime
    slider.setValue(Float(currentTime), animated: true)
}

func playPressed(){

    player!.play()
    updater = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
</code>```

答:
The reason for the non-smooth UISlider was because i had two CADisplayLink's in the same view controller.

I initially had the following:

```<code>var displayLink: CADisplayLink?  // for recording animation
var updater: CADisplayLink?      // for updating slider

func record() {
     let displayLink = CADisplayLink(target: self, selector:#selector(RecordController.updateMeters))
     displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

func play() {
    let updater = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
</code>```

I got it to work by doing:

```<code>func record() {
     self.displayLink = CADisplayLink(target: self, selector:#selector(RecordController.updateMeters))
     self.displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

func play() {
    self.displayLink = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    self.displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
</code>```

Title: UISlider not progressing smoothly

Body:
I have two UIViewControllers and each one has a UISlider. One slider tracks the progress of an audio file playing from AVPlayer the other viewcontroller slider tracks the progress of an audio file playing from AVAudioPlayer. The slider responding to AVPlayer animates perfectly smooth while the animation for the slider responding to AVAudioPlayer is not smooth. The sliders are set up exactly the same except for how I obtain the current time of each player as shown below:

//AVPlayer slider

func trackAudio() {
    let currentTime = self.newPlayer!.currentTime()
    let currentTimeInSeconds = CMTimeGetSeconds(currentTime)
    slider.setValue(Float(currentTimeInSeconds), animated: true)
}

//AVAudioPlayer Slider

func trackAudio() {
    let currentTime = self.player!.currentTime
    slider.setValue(Float(currentTime), animated: true)
}

func playPressed(){

    player!.play()
    updater = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

Body:
The reason for the non-smooth UISlider was because i had two CADisplayLink's in the same view controller.

I initially had the following:

var displayLink: CADisplayLink?  // for recording animation
var updater: CADisplayLink?      // for updating slider

func record() {
     let displayLink = CADisplayLink(target: self, selector:#selector(RecordController.updateMeters))
     displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

func play() {
    let updater = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    updater.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

I got it to work by doing:

func record() {
     self.displayLink = CADisplayLink(target: self, selector:#selector(RecordController.updateMeters))
     self.displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}

func play() {
    self.displayLink = CADisplayLink(target: self, selector: #selector(RecordController.trackAudio))
    self.displayLink.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}


问:
How to make a method run only once in the lifetime of application
I have a method that fills in a file with default values and I call that method in the constructor. I want that method to run only once ( I mean by only once so when the user press the play button /in eclipse/ then that method will not run in the second press.

I have tried something like this but it doesn't work :

```<code>private boolean defaultExecuted;
public synchronized void defaultStatsFile()
{
    if (defaultExecuted)
    {
        return;
    }
    else
    {
        fileReadNWrite.configWriter("panel1", "non-US incidents");
        fileReadNWrite.configWriter("panel2", "Hoaxes");
        fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
        fileReadNWrite.configWriter("panel4", "Likliest Shape");
        defaultExecuted = true;
    }

}
</code>```

Is there a smarter way to fill in a file only once ?

Please if something is not clear comment and I will reply.
Any help is appreciated.

答: Because all code goes in classes and you can have multiple independend class-loaders, you can not do this in java, you need some resource outside of java. </p>

Body:
I have a method that fills in a file with default values and I call that method in the constructor. I want that method to run only once ( I mean by only once so when the user press the play button /in eclipse/ then that method will not run in the second press.

I have tried something like this but it doesn't work :

private boolean defaultExecuted;
public synchronized void defaultStatsFile()
{
    if (defaultExecuted)
    {
        return;
    }
    else
    {
        fileReadNWrite.configWriter("panel1", "non-US incidents");
        fileReadNWrite.configWriter("panel2", "Hoaxes");
        fileReadNWrite.configWriter("panel3", "Under NUFORC investigation");
        fileReadNWrite.configWriter("panel4", "Likliest Shape");
        defaultExecuted = true;
    }

}

Is there a smarter way to fill in a file only once ?

Please if something is not clear comment and I will reply.
Any help is appreciated.


问:
Conditionally acquire an std::mutex
I have a multi-threaded app that uses the GPU, which is inherently single-threaded, and the actual APIs I use, cv::gpu::FAST_GPU, does crash when I try to use them multi-threaded, so basically I have:

```<code>static std::mutex s_FAST_GPU_mutex;

{
    std::lock_guard<std::mutex> guard(s_FAST_GPU_mutex);
    cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
}
</code>```

Now, benchmarking the code shows me FAST_GPU() in isolation is faster than the CPU FAST(), but in the actual application my other threads spend a lot of time waiting for the lock, so the overall throughput is worse.

Looking through the documentation, and at this answer it seems that this might be possible:

```<code>static std::mutex s_FAST_GPU_mutex;
static std::unique_lock<std::mutex> s_FAST_GPU_lock(s_FAST_GPU_mutex, std::defer_lock);

{
    // Create an unlocked guard
    std::lock_guard<decltype(s_FAST_GPU_lock)> guard(s_FAST_GPU_lock, std::defer_lock);
    if (s_FAST_GPU_lock.try_lock())
    {
        cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
    }
    else
    {
        cv::FAST(/*parameters*/);
    }
}
</code>```

However, this will not compile as std::lock_guard only accepts a std::adopt_lock. How can I implement this properly?

答:
It is actually unsafe to have a unique_lock accessible from multiple threads at the same time.  I'm not familiar with the opencv portion of your question, so this answer is focused on the mutex/lock usage.

```<code>static std::mutex s_FAST_GPU_mutex;
{
   // Create a unique lock, attempting to acquire
   std::unique_lock<std::mutex> guard(s_FAST_GPU_mutex, std::try_to_lock);
   if (guard.owns_lock())
   {
       cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
       guard.unlock(); // Or just let it go out of scope later
   }
   else
   {
       cv::FAST(/*parameters*/);
   }
}
</code>```

This attempts to acquire the lock, if it succeeds, uses FAST_GPU, and then releases the lock.  If the lock was already acquired, then goes down the second branch, invoking FAST

Title: Conditionally acquire an std::mutex

Body:
I have a multi-threaded app that uses the GPU, which is inherently single-threaded, and the actual APIs I use, cv::gpu::FAST_GPU, does crash when I try to use them multi-threaded, so basically I have:

static std::mutex s_FAST_GPU_mutex;

{
    std::lock_guard<std::mutex> guard(s_FAST_GPU_mutex);
    cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
}

Now, benchmarking the code shows me FAST_GPU() in isolation is faster than the CPU FAST(), but in the actual application my other threads spend a lot of time waiting for the lock, so the overall throughput is worse.

Looking through the documentation, and at this answer it seems that this might be possible:

static std::mutex s_FAST_GPU_mutex;
static std::unique_lock<std::mutex> s_FAST_GPU_lock(s_FAST_GPU_mutex, std::defer_lock);

{
    // Create an unlocked guard
    std::lock_guard<decltype(s_FAST_GPU_lock)> guard(s_FAST_GPU_lock, std::defer_lock);
    if (s_FAST_GPU_lock.try_lock())
    {
        cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
    }
    else
    {
        cv::FAST(/*parameters*/);
    }
}

However, this will not compile as std::lock_guard only accepts a std::adopt_lock. How can I implement this properly?

Body:
It is actually unsafe to have a unique_lock accessible from multiple threads at the same time.  I'm not familiar with the opencv portion of your question, so this answer is focused on the mutex/lock usage.

static std::mutex s_FAST_GPU_mutex;
{
   // Create a unique lock, attempting to acquire
   std::unique_lock<std::mutex> guard(s_FAST_GPU_mutex, std::try_to_lock);
   if (guard.owns_lock())
   {
       cv::gpu::FAST_GPU(/*params*/)(/*parameters*/);
       guard.unlock(); // Or just let it go out of scope later
   }
   else
   {
       cv::FAST(/*parameters*/);
   }
}

This attempts to acquire the lock, if it succeeds, uses FAST_GPU, and then releases the lock.  If the lock was already acquired, then goes down the second branch, invoking FAST


问:
How to call a controller function from angular directive
I want to call controller function from directive. Here is the fiddle. I have a sayHello() function in controller. And I want to call that function from angular directive. If i wall like scope.sayHello();

```<code>scope.sayHello is not a function
</code>```

I am getting like the above in console.

答:
To get your alert in your fiddle to fire, all I had to do what add the person into your template. You had the updateparent="updatePerson()", and you just needed to pass the person in that call, like this: updateparent="updatePerson(person)". Then your alert fired.

The reason for this is that you need to state in the template all of the parameters that you are passing in to the function. Since you call it like updateparent({person: mandatePerson}), you have to put the key person into your template that it will be called with that param. They have to match.

Body:
I want to call controller function from directive. Here is the fiddle. I have a sayHello() function in controller. And I want to call that function from angular directive. If i wall like scope.sayHello();

scope.sayHello is not a function

I am getting like the above in console.


问:
Don't understand why replace() method is not working as expected
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

```<code>function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}
</code>```

All of the example test cases work except for the following:

```<code>Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''
</code>```

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?

答:
replace() is searching using a pattern (or regular expression) and it replaces all occurrences.

Instead, you want to truncate and create a new string, which is known as assignment in other languages (but strings in JS are immutable). See here for more details.

Body:
Working on the following problem:

Create a function called alienLanguage where the input will be a str and the output should capitalize all letters except for the last letter of each word

alienLanguage("My name is John") should return "My NAMe Is JOHn"

This is what I have coded:

function alienLanguage(str){
  var words = str.toUpperCase().split(' ').map(function (a) {
    return a.replace(a[a.length - 1], a[a.length - 1].toLowerCase())
  });
  return words.join(' ');
}

All of the example test cases work except for the following:

Expected: '\'THIs Is An EXAMPLe\'', instead got: '\'THIs Is An eXAMPLE\''

Why is the e in eXAMPLE turning lowercase? Shouldn't everything automatically turn upperCase ?

edit: I just realized that there are 2 e's and the first one is being replaced. How can I replace the last e? and isn't the last character specified already?


问:
How to make database go to SQL Server instead of localDB?
I am able to log into SSMS under Windows Authentication and SQL Server Authentication. But I am not seeing the Database anywhere in the SQL Server Management Studio. In Visual Studio, it goes to the localDb even though I have changed the connection string to have the db created in my SSMS.

```<code><!--<add name="BookServiceContext" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=BookServiceContext-20170328200803; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|BookServiceContext-20170328200803.mdf"
      providerName="System.Data.SqlClient" />-->
    <add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</code>```

Sometimes, I can see the name BookServiceContext under Data Connections in VS Server Explorer, but when I click on the connection I get this error message

Cannot open database "BookServiceContext" requested by the login. The login failed.
  Login failed for user 'MLS\AAnwar'.

What can I do so that it goes to the right connection in my SSMS?

答:
VS Sql Server Object Explorer and the Server Explorer just provide a convient way of accessing the database

It provide similar functionality as SSMS - since you can log in to SSMS why not just manage there.

But if you really want to manage database through VS,
then the Sql Server Object Explorer and the Server Explorer both provide a way of adding (toolbar there is add icon) any db connection, so you can do it there.

more info about the two view

The reason you see localdb in the SQL Server object explorer is because when you install VS, a localdb is installed, henc it will be shown by default
As said above, if you want to connect to othere sql server, you can always add new sql server via tool bar

The Server Explorer will read your web.config to provide easy way of accessing the DB -
by your error info, it seems that the current windows user do not have right to access db - it could be alot of reasons, seems you have mix login, why not just use sql server account?
just change your connection string to:

```<code><add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;user id=sqlUserId;password=sqlUserPassword" providerName="System.Data.SqlClient" />
</code>```

you can also manualy add a db connection via tool bar

Body:
I am able to log into SSMS under Windows Authentication and SQL Server Authentication. But I am not seeing the Database anywhere in the SQL Server Management Studio. In Visual Studio, it goes to the localDb even though I have changed the connection string to have the db created in my SSMS.

    <add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

Sometimes, I can see the name BookServiceContext under Data Connections in VS Server Explorer, but when I click on the connection I get this error message

Cannot open database "BookServiceContext" requested by the login. The login failed.
  Login failed for user 'MLS\AAnwar'.

What can I do so that it goes to the right connection in my SSMS?

Body:
VS Sql Server Object Explorer and the Server Explorer just provide a convient way of accessing the database

It provide similar functionality as SSMS - since you can log in to SSMS why not just manage there.

But if you really want to manage database through VS,
then the Sql Server Object Explorer and the Server Explorer both provide a way of adding (toolbar there is add icon) any db connection, so you can do it there.

more info about the two view

The reason you see localdb in the SQL Server object explorer is because when you install VS, a localdb is installed, henc it will be shown by default
As said above, if you want to connect to othere sql server, you can always add new sql server via tool bar

The Server Explorer will read your web.config to provide easy way of accessing the DB -
by your error info, it seems that the current windows user do not have right to access db - it could be alot of reasons, seems you have mix login, why not just use sql server account?
just change your connection string to:

<add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;user id=sqlUserId;password=sqlUserPassword" providerName="System.Data.SqlClient" />

you can also manualy add a db connection via tool bar


问:
How to format and insert a character in between a string- Postgresql
I have this table.

member_id | phone_number
-----------+--------------
         1 | 09151234567
         2 | 09904897851
         3 | 09196332111
         4 | 09957935412
         5 | 09251279633
         6 | 09357489412
         7 | 09155974684
(7 rows)

I format the phone_number column to this format (63)xxxxxxxxx. Using this code

update member set phone_number = regexp_replace(phone_number, '0(.)', '(63)');

member_id | phone_number

-----------+---------------
         1 | (63)151234567
         2 | (63)904897851
         3 | (63)196332111
         4 | (63)957935412
         5 | (63)251279633
         6 | (63)357489412
         7 | (63)155974684
(7 rows)

And now I need to update this column again to this format (63)xxx-xxxxxx.
I don't want to replace a character, I need to insert a character in between the string.
I've tried using substring, regexp_replace but failed. I'm doing something wrong. I did find questions somehow related to this but they are all about string replacement.

答:
You can do that in a few ways, I like this one with right() and left():

```<code>update member
set phone_number = format('%s-%s', left(phone_number, 7), right(phone_number, -7));
</code>```

Body:
You can do that in a few ways, I like this one with right() and left():

update member
set phone_number = format('%s-%s', left(phone_number, 7), right(phone_number, -7));


答:
The Angular directive's link function has arguments for both scope and controller -- if the method you want to call is directly on $scope in your controller you can just call it off of the scope arg-- if you are using controllerAs syntax (which I would recommend as it is a recommended Angular pattern) you can call it off the controller argument.

So, for your specific case (methods directly on $scope) in your directive return object you add a property link:

```<code>link: function (scope, iElement, iAttrs, controller, transcludeFn)
    scope.sayHello();
}
</code>```

link runs once at directive creation-- if you want the scope or method to be available outside of that for some reason, assign it to a variable defined at the top level of the module.

Title: How to call a controller function from angular directive

Body:
The Angular directive's link function has arguments for both scope and controller -- if the method you want to call is directly on $scope in your controller you can just call it off of the scope arg-- if you are using controllerAs syntax (which I would recommend as it is a recommended Angular pattern) you can call it off the controller argument.

So, for your specific case (methods directly on $scope) in your directive return object you add a property link:

link: function (scope, iElement, iAttrs, controller, transcludeFn)
    scope.sayHello();
}

link runs once at directive creation-- if you want the scope or method to be available outside of that for some reason, assign it to a variable defined at the top level of the module.


问:
MarkLogic using JavaAPI
I have been trying a normal Java API using the same example as mentioned in this page. I had to download various JARs:

java-client-api-3.0.7.jar

slf4j-api-1.7.25.jar

com.fasterxml.jackson.databind.jar

jackson-core-2.2.0-rc1.jar

apache-httpcomponents-httpclient.jar

javax.ws.rs.jar

It still gives me NoClassDefFoundError on

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/params/HttpParams at com.marklogic.client.DatabaseClientFactory.newClientImpl(DatabaseClientFactory.java:322)

My Code:

```<code>import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.document.*;
import com.marklogic.client.io.*;
public class JavaML {
  public static void main(String args[]) {
    System.out.println("Here");
    DatabaseClient client =
      DatabaseClientFactory.newClient(
        "localhost", 8000,"admin", "######",
        DatabaseClientFactory.Authentication.DIGEST);
    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    docMgr.write("/afternoon-drink",
      new StringHandle("{name: \"Iced Mocha\", size: \"Grandé\", tasty: true}"));
    String doc = docMgr.read("/afternoon-drink", new StringHandle()).get();
    //System.out.println(doc);
  }
}
</code>```

Run:

```<code>javac -cp .;%CLASSES% JavaML.java
java -cp .;%CLASSES% JavaML
</code>```

%CLASSES% - path to all the jars mentioned above.

Please help - am I missing something? Or is it a mandate that I have to download all these JARs?

答:
It appears from the error message that you are missing the httpcore-4.1.jar.

However, there are a number of other dependencies that you are likely to be missing as well.

If you are maintaining your own set of dependencies and building your classpath manually, then you should download the Java API zip, which includes all of the necessary dependencies in the /lib directory.

However, it would be much easier if you were to use a build/dependency management tool, such as Gradle or Maven. If you have the Java API as a dependency, it will download all of it's dependencies and will compile your application with the necessary libraries on your classpath. It makes upgrades much easier, facilitates automation, and is a best practice in favor of manually collecting and organizing dependencies.

Title: MarkLogic using JavaAPI

Body:
I have been trying a normal Java API using the same example as mentioned in this page. I had to download various JARs:

java-client-api-3.0.7.jar

slf4j-api-1.7.25.jar

com.fasterxml.jackson.databind.jar

jackson-core-2.2.0-rc1.jar

apache-httpcomponents-httpclient.jar

javax.ws.rs.jar

It still gives me NoClassDefFoundError on

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/params/HttpParams at com.marklogic.client.DatabaseClientFactory.newClientImpl(DatabaseClientFactory.java:322)

My Code:

import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.document.*;
import com.marklogic.client.io.*;
public class JavaML {
  public static void main(String args[]) {
    System.out.println("Here");
    DatabaseClient client =
      DatabaseClientFactory.newClient(
        "localhost", 8000,"admin", "######",
        DatabaseClientFactory.Authentication.DIGEST);
    JSONDocumentManager docMgr = client.newJSONDocumentManager();
    docMgr.write("/afternoon-drink",
      new StringHandle("{name: \"Iced Mocha\", size: \"Grandé\", tasty: true}"));
    String doc = docMgr.read("/afternoon-drink", new StringHandle()).get();
    //System.out.println(doc);
  }
}

Run:

javac -cp .;%CLASSES% JavaML.java
java -cp .;%CLASSES% JavaML

%CLASSES% - path to all the jars mentioned above.

Please help - am I missing something? Or is it a mandate that I have to download all these JARs?


问:
Gem/Bundler load error: can't activate...already activated
I ran bundle update to update my gems. now I get this when I try to start up the local, development server. Anyone know how to fix? </p>

```<code>hostname:myapp username$ rails s
/Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:238:in `activate': can't activate i18n (~> 0.4.1, runtime) for ["mail-2.2.10", "actionmailer-3.0.3", "rails-3.0.3"], already activated i18n-0.5.0 for ["activemodel-3.0.3", "actionpack-3.0.3", "rails-3.0.3"] (Gem::LoadError)
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:1065:in `gem'
    from /Users/username/.rvm/gems/ruby-1.9.2-p0@rails3/bin/rails:18:in `<main>'
</code>```

答: You need to uninstall the i18n-0.5.0 gem. That fixed it for me...</p>

Body:
I ran bundle update to update my gems. now I get this when I try to start up the local, development server. Anyone know how to fix?

hostname:myapp username$ rails s
/Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:238:in `activate': can't activate i18n (~> 0.4.1, runtime) for ["mail-2.2.10", "actionmailer-3.0.3", "rails-3.0.3"], already activated i18n-0.5.0 for ["activemodel-3.0.3", "actionpack-3.0.3", "rails-3.0.3"] (Gem::LoadError)
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:1065:in `gem'
    from /Users/username/.rvm/gems/ruby-1.9.2-p0@rails3/bin/rails:18:in `'


问:
Restricting Uniques from Showing
I currently have this SQL query and this output.

```<code>SELECT b.HotelNo,g.guestName,b.dateFrom,b.dateToFrom Booking b, Guest g
FROM Booking b, Guest g
WHERE b.guestNo = g.guestNo
GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;
</code>```

I am getting this output:
Output

How do I remove all the rows that are not duplicates of first two columns?

Output would be (In words Get all the hotel numbers guest names and dates of stay of all guest only if they have stayed in the same hotel more than once):

```<code>1234 John Doe 2017-02-01 00:00:00.000 2017-02-28 00:00:00.000
1234 John Doe 2017-03-16 00:00:00.000 2017-03-21 00:00:00.000
</code>```

EDIT:

I got what I wanted but I when I add b.dateFrom,b.dateTo into my select statement. I get an error saying: Column 'Booking.dateFrom' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

This is the SQL query that gets this error:

```<code>SELECT b.hotelNo,g.guestName,b.dateFrom,b.dateTo
FROM Booking b, Guest g
WHERE b.guestNo = g.guestNo
GROUP BY b.hotelNo,g.guestName
HAVING COUNT(*) > 1;
</code>```

If I add those two column names in (which I need) I get the error above. How do I add them in without getting an error?

答:
If you don't mind picking only one of the "dateFrom"s (first or last depending on the order clause) then you can assign a row number to each row, partitioning by the first two columns.
Then only pick the first rows of each group (RN=1) which has the same first two column

```<code>WITH CTE AS
( SELECT ROW_NUMBER()
          OVER ( PARTITION BY b.HotelNo,g.guestName
            ORDER BY b.dateFrom) AS RN,
         b.HotelNo,g.guestName,b.dateFrom,b.dateTo
  FROM Booking b, Guest g
  WHERE b.guestNo = g.guestNo
  GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;
)
SELECT HotelNo,guestName,dateFrom,dateToFrom
WHERE RN=1
</code>```

You can read more HERE

Title: Restricting Uniques from Showing

Body:
I currently have this SQL query and this output.

SELECT b.HotelNo,g.guestName,b.dateFrom,b.dateToFrom Booking b, Guest g
FROM Booking b, Guest g
WHERE b.guestNo = g.guestNo
GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;

I am getting this output:
Output

How do I remove all the rows that are not duplicates of first two columns?

Output would be (In words Get all the hotel numbers guest names and dates of stay of all guest only if they have stayed in the same hotel more than once):

1234 John Doe 2017-02-01 00:00:00.000 2017-02-28 00:00:00.000
1234 John Doe 2017-03-16 00:00:00.000 2017-03-21 00:00:00.000

EDIT:

I got what I wanted but I when I add b.dateFrom,b.dateTo into my select statement. I get an error saying: Column 'Booking.dateFrom' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

This is the SQL query that gets this error:

SELECT b.hotelNo,g.guestName,b.dateFrom,b.dateTo
FROM Booking b, Guest g
WHERE b.guestNo = g.guestNo
GROUP BY b.hotelNo,g.guestName
HAVING COUNT(*) > 1;

If I add those two column names in (which I need) I get the error above. How do I add them in without getting an error?

Body:
If you don't mind picking only one of the "dateFrom"s (first or last depending on the order clause) then you can assign a row number to each row, partitioning by the first two columns.
Then only pick the first rows of each group (RN=1) which has the same first two column

WITH CTE AS
( SELECT ROW_NUMBER()
          OVER ( PARTITION BY b.HotelNo,g.guestName
            ORDER BY b.dateFrom) AS RN,
         b.HotelNo,g.guestName,b.dateFrom,b.dateTo
  FROM Booking b, Guest g
  WHERE b.guestNo = g.guestNo
  GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;
)
SELECT HotelNo,guestName,dateFrom,dateToFrom
WHERE RN=1

You can read more HERE


问:
U-SQL with Python to convert JSON to CSV in Azure Data Lake store
We need to convert some huge files stored in Azure data lake  store from nested JSON to CSV. Since the python modules pandas, numpy are supported in Azure data lake analytics apart from the standard modules I believe its pretty much possible to achieve this using python. Does anyone have the python code to achieve this?

Source Format:

{"Loc":"TDM","Topic":"location","LocMac":"location/fe:7a:xx:xx:xx:xx","seq":"296083773","timestamp":1488986751,"op":"OP_UPDATE","topicSeq":"46478211","sourceId":"AFBWmHSe","location":{"staEthMac":{"addr":"/xxxxx"},"staLocationX":1643.8915,"staLocationY":571.04205,"errorLevel":1076,"associated":0,"campusId":"n5THo6IINuOSVZ/cTidNVA==","buildingId":"7hY/xx==","floorId":"xxxxxxxxxx+BYoo0A==","hashedStaEthMac":"xxxx/pMVyK4Gu9qG6w=","locAlgorithm":"ALGORITHM_ESTIMATION","unit":"FEET"},"EventProcessedUtcTime":"2017-03-08T15:35:02.3847947Z","PartitionId":3,"EventEnqueuedUtcTime":"2017-03-08T15:35:03.7510000Z","IoTHub":{"MessageId":null,"CorrelationId":null,"ConnectionDeviceId":"xxxxx","ConnectionDeviceGenerationId":"636243184116591838","EnqueuedTime":"0001-01-01T00:00:00.0000000","StreamId":null}}

Expected Output

TDM,location,location/80:7a:bf:d4:d6:50,974851970,1490004475,OP_UPDATE,151002334,xxxxxxx,gHq/1NZQ,977.7259,638.8827,490,1,n5THo6IINuOSVZ/cTidNVA==,7hY/jVh9NRqqxF6gbqT7Jw==,LV/ZiQRQMS2wwKiKTvYNBQ==,H5rrAD/jg1Fnkmo1Zmquau/Qn1U=,ALGORITHM_ESTIMATION,FEET

答:
According to your description, based on my understanding, I think your key needs is how to convert data stored in Azure Data Lake Store from JSON format to CSV format in Python with pandas/numpy packages. So I viewed your source data, and assumed there is not array type in JSON, then I designed the code below for the sample data conversion.

Here is my sample code for a JSON format object string. As reference, I add some comments for understanding my idea which the key is flattern method for converting the structure {"A": 0, "B": {"C": 1}} to the structure [["A", "B.C"], [0, 1]].

```<code>import json
import pandas as pd

# Source Data string
json_raw = '''{"Loc":"TDM","Topic":"location","LocMac":"location/fe:7a:xx:xx:xx:xx","seq":"296083773","timestamp":1488986751,"op":"OP_UPDATE","topicSeq":"46478211","sourceId":"AFBWmHSe","location":{"staEthMac":{"addr":"/xxxxx"},"staLocationX":1643.8915,"staLocationY":571.04205,"errorLevel":1076,"associated":0,"campusId":"n5THo6IINuOSVZ/cTidNVA==","buildingId":"7hY/xx==","floorId":"xxxxxxxxxx+BYoo0A==","hashedStaEthMac":"xxxx/pMVyK4Gu9qG6w=","locAlgorithm":"ALGORITHM_ESTIMATION","unit":"FEET"},"EventProcessedUtcTime":"2017-03-08T15:35:02.3847947Z","PartitionId":3,"EventEnqueuedUtcTime":"2017-03-08T15:35:03.7510000Z","IoTHub":{"MessageId":null,"CorrelationId":null,"ConnectionDeviceId":"xxxxx","ConnectionDeviceGenerationId":"636243184116591838","EnqueuedTime":"0001-01-01T00:00:00.0000000","StreamId":null}}'''

# Load source data string to a Python dict
json_data = json.loads(json_raw)

# The key method `flattern` for converting `dict` to `2D-list`
def flattern(data, key):
    keys = []
    values = []
    if key is None:
        for key in data:
            if type(data[key]) is dict:
                keys.extend(flattern(data[key], key)[0])
                values.extend(flattern(data[key], key)[1])
            else:
                keys.append(key)
                values.append(data[key])
    else:
        for subkey in data:
            if type(data[subkey]) is dict:
                keys.extend(flattern(data[subkey], key+"."+subkey)[0])
                values.extend(flattern(data[subkey], subkey)[1])
            else:
                keys.append(key+"."+subkey)
                values.append(data[subkey])
    return [keys, values]

list2D = flattern(json_data, None)
df = pd.DataFrame([list2D[1],], columns=list2D[0])

# If you want to extract the items `Loc` & `Topic` & others like `location.staEthMac.addr`, you just need to create a list for them.
selected = ["Loc", "Topic"]
# Use `selected` list to select the columns you want.
result = df.ix[:,selected]
# Transform DataFrame to csv string
csv_raw = "\n".join([",".join(lst) for lst in pd.np.array(result)])
</code>```

Hope it helps.

Body:
According to your description, based on my understanding, I think your key needs is how to convert data stored in Azure Data Lake Store from JSON format to CSV format in Python with pandas/numpy packages. So I viewed your source data, and assumed there is not array type in JSON, then I designed the code below for the sample data conversion.

Here is my sample code for a JSON format object string. As reference, I add some comments for understanding my idea which the key is flattern method for converting the structure {"A": 0, "B": {"C": 1}} to the structure [["A", "B.C"], [0, 1]].

import json
import pandas as pd

# Source Data string
json_raw = '''{"Loc":"TDM","Topic":"location","LocMac":"location/fe:7a:xx:xx:xx:xx","seq":"296083773","timestamp":1488986751,"op":"OP_UPDATE","topicSeq":"46478211","sourceId":"AFBWmHSe","location":{"staEthMac":{"addr":"/xxxxx"},"staLocationX":1643.8915,"staLocationY":571.04205,"errorLevel":1076,"associated":0,"campusId":"n5THo6IINuOSVZ/cTidNVA==","buildingId":"7hY/xx==","floorId":"xxxxxxxxxx+BYoo0A==","hashedStaEthMac":"xxxx/pMVyK4Gu9qG6w=","locAlgorithm":"ALGORITHM_ESTIMATION","unit":"FEET"},"EventProcessedUtcTime":"2017-03-08T15:35:02.3847947Z","PartitionId":3,"EventEnqueuedUtcTime":"2017-03-08T15:35:03.7510000Z","IoTHub":{"MessageId":null,"CorrelationId":null,"ConnectionDeviceId":"xxxxx","ConnectionDeviceGenerationId":"636243184116591838","EnqueuedTime":"0001-01-01T00:00:00.0000000","StreamId":null}}'''

# Load source data string to a Python dict
json_data = json.loads(json_raw)

# The key method `flattern` for converting `dict` to `2D-list`
def flattern(data, key):
    keys = []
    values = []
    if key is None:
        for key in data:
            if type(data[key]) is dict:
                keys.extend(flattern(data[key], key)[0])
                values.extend(flattern(data[key], key)[1])
            else:
                keys.append(key)
                values.append(data[key])
    else:
        for subkey in data:
            if type(data[subkey]) is dict:
                keys.extend(flattern(data[subkey], key+"."+subkey)[0])
                values.extend(flattern(data[subkey], subkey)[1])
            else:
                keys.append(key+"."+subkey)
                values.append(data[subkey])
    return [keys, values]

list2D = flattern(json_data, None)
df = pd.DataFrame([list2D[1],], columns=list2D[0])

# If you want to extract the items `Loc` & `Topic` & others like `location.staEthMac.addr`, you just need to create a list for them.
selected = ["Loc", "Topic"]
# Use `selected` list to select the columns you want.
result = df.ix[:,selected]
# Transform DataFrame to csv string
csv_raw = "\n".join([",".join(lst) for lst in pd.np.array(result)])

Hope it helps.


问:
What is the number ways to map alphabet to alphabet without overlap?
I want to make mapping table with alphabet to alphabet. We can't use same alphabet value and key.

For example, we can use key A - value C , key B - key D. But we can't use key A - value A, key C - value C. In this situation, what is the number of mapping tables that we can make?

答:
148,362,637,348,470,135,821,287,825.

In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position. In other words, derangement is a permutation that has no fixed points.
  -Wikipedia

Assuming you're only using 26 substitutions (e.g. capital letters), the question boils down to "what's the number of derangements for a set of 26 items?"; which is 1.48e26, which is about a 63% reduction in the total keyspace (26! == 4.03e26).

For large values it turns out to be approximately equal to n! / e (e being the number approximately equal to 2.71828).


问:
"Clickable" textblock?
I have a WP7 app where I would like to have a "clickable" TextBlock area, that when a user clicks on the TextBlock, it puts it into edit mode (a different control).
This would add another explicit step for a user before editing text.

There is no click event for the TextBlock (which doesn't surprise me).

Is there any way to do this?  Wrapped in another control, or something similar?

答:
Yes, there is a click event. Its called MouseLeftButtonDown</p>

```<code>textBlock1.MouseLeftButtonDown +=new MouseButtonEventHandler(textBlock1_MouseLeftButtonDown);

private void textBlock1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

}
</code>```

Title: "Clickable" textblock?

Body:
Yes, there is a click event. Its called MouseLeftButtonDown

textBlock1.MouseLeftButtonDown +=new MouseButtonEventHandler(textBlock1_MouseLeftButtonDown);

private void textBlock1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

}


答:
I changed your directive a bit, but this is how you get that sort of functionality.
FIDDLE

If you're interested in AngularJS I would highly recommend the John papa styleguide.
https://github.com/johnpapa/angular-styleguide

It will get you using syntax like controllerAs and will help make your code cleaner.

HTML

```<code><body ng-app="myApp" ng-controller="MainCtrl">
    <div>
      Original name: {{mandat.name}}
    </div>
    <my-directive mandat="mandat"></my-directive>
</body>
</code>```

JS

```<code>var app = angular.module('myApp', []);
app.controller('MainCtrl', MainController);

function MainController($scope) {
  $scope.mandat = {
    name: "John",
    surname: "Doe",
    person: { id: 1408, firstname: "sam" }
  };
}

app.directive('myDirective', MyDirective);

function MyDirective() {
  return {
    restrict: 'E',
    template: "<div><input type='text' ng-model='mandat.person.firstname' /><button ng-click='updateparent()'>click</button></div>",
    replace: true,
    scope: {
      mandat: "="
    },
    controller: function($scope) {
      $scope.updateparent = function() {
        $scope.mandat.name = "monkey";
      }
    }
  }
}
</code>```

Body:
I changed your directive a bit, but this is how you get that sort of functionality.
FIDDLE

If you're interested in AngularJS I would highly recommend the John papa styleguide.
https://github.com/johnpapa/angular-styleguide

It will get you using syntax like controllerAs and will help make your code cleaner.

HTML

<body ng-app="myApp" ng-controller="MainCtrl">
    <div>
      Original name: {{mandat.name}}
    </div>
    <my-directive mandat="mandat"></my-directive>
</body>

JS

var app = angular.module('myApp', []);
app.controller('MainCtrl', MainController);

function MainController($scope) {
  $scope.mandat = {
    name: "John",
    surname: "Doe",
    person: { id: 1408, firstname: "sam" }
  };
}

app.directive('myDirective', MyDirective);

function MyDirective() {
  return {
    restrict: 'E',
    template: "<div><input type='text' ng-model='mandat.person.firstname' /><button ng-click='updateparent()'>click</button></div>",
    replace: true,
    scope: {
      mandat: "="
    },
    controller: function($scope) {
      $scope.updateparent = function() {
        $scope.mandat.name = "monkey";
      }
    }
  }
}


问:
How can I get the checked status of a checkbox
I have a gridview parameter in my asp.net program as follows:

Name: row.Cells[5].Controls[0]

Value: (Text="" Checked=true)

type: System.Web.UI.WebControls.CheckBox

How can I get the Checked status of such parameter?

答:
It's been quite a while since I worked on GridView. Did you try this?

```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   var mycheckbox = (CheckBox)e.Row.Cells[5].Controls[0];
   var status = mycheckbox.checked;
}
</code>```

Body:
It's been quite a while since I worked on GridView. Did you try this?

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
   var mycheckbox = (CheckBox)e.Row.Cells[5].Controls[0];
   var status = mycheckbox.checked;
}


问:
AngularJS , REST, C# Service, 405 - Post Method Not Allowed
I'm trying to do a full Angularjs web site for training. I've read many articles about this Method not allowed, but didn't find a solution. I'm trying to send a data object to my service.

Error : Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Here is my AngularJS Part.

```<code>var addNews =
        {
            Title: newsList.newsTitle,
            NewsContent: newsList.newsContent,
            CreationDate: newsList.newsCreationDate,
            CreatedBy: newsList.newsAuthor,
            ModificationDate: newsList.newsCreationDate,
            ModifiedBy: newsList.newsAuthor
        };

    var news = JSON.stringify(addNews);

    $http({
        method: 'POST',
        dataType: 'json',
        url: 'http://localhost:11672/InfinytecServices.svc/SaveNews',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        data: news
    });
</code>```

Here's my service part

```<code>    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "/SaveNews",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    int SaveNews(News news);
</code>```

WebConfig Comming

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>

  <system.serviceModel>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>

    <extensions>
      <behaviorExtensions>
        <add
          name="crossOriginResourceSharingBehavior"
          type="InfinytecWebService.CORSEnablingBehavior, InfinytecWebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
      </behaviorExtensions>
    </extensions>

    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
          <crossOriginResourceSharingBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <services>
      <service behaviorConfiguration="serviceBehavior" name="InfinytecWebService.InfinytecServices">
        <endpoint address=""
                  behaviorConfiguration="web"
                  binding="webHttpBinding"
                  contract="InfinytecWebService.IInfinytecServices" />
      </service>
    </services>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
```

<p>And at least , the CORS</p>

```public class CORSEnablingBehavior : BehaviorExtensionElement, IEndpointBehavior

    {
        public void AddBindingParameters(
            ServiceEndpoint endpoint,
            BindingParameterCollection bindingParameters){ }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
              new CORSHeaderInjectingMessageInspector()
            );
        }

        public void Validate(ServiceEndpoint endpoint) { }

        public override Type BehaviorType { get { return typeof(CORSEnablingBehavior); } }

        protected override object CreateBehavior() { return new CORSEnablingBehavior(); }

        private class CORSHeaderInjectingMessageInspector : IDispatchMessageInspector
        {
            public object AfterReceiveRequest(
              ref Message request,
              IClientChannel channel,
              InstanceContext instanceContext)
            {
                return null;
            }
            private static IDictionary<string, string> _headersToInject = new Dictionary<string, string>
          {
            { "Access-Control-Allow-Origin", "*" },
            { "Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS" },
            { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" }
          };
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
                var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
                foreach (var item in _headersToInject)
                    httpHeader.Headers.Add(item.Key, item.Value);
            }
        }
    }
```

Can you help me?

In advance, thanks! :)

答:
Try one of the following

Define a another WebInvoke method with Method="OPTIONS"  , the method should return empty content , since your CORS behavior handler adds all pre-flight headers needed for your browser .

Your CORS Extension should analyze the current request METHOD if it is OPTIONS it should short-circuit and return empty content with the pre-flight headers. If the method type is "GET"/"POST" it should let the request through to be processed by the endpoint.

The browser makes two request one to get pre-flight info using options and another for the actual api call .

the problem you are having is the first call by the browser Method=OPTIONS is being rejected by your endpoint. because it can only process POST.

Body:
I'm trying to do a full Angularjs web site for training. I've read many articles about this Method not allowed, but didn't find a solution. I'm trying to send a data object to my service.

Error : Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

Here is my AngularJS Part.

var addNews =
        {
            Title: newsList.newsTitle,
            NewsContent: newsList.newsContent,
            CreationDate: newsList.newsCreationDate,
            CreatedBy: newsList.newsAuthor,
            ModificationDate: newsList.newsCreationDate,
            ModifiedBy: newsList.newsAuthor
        };

    var news = JSON.stringify(addNews);

    $http({
        method: 'POST',
        dataType: 'json',
        url: 'http://localhost:11672/InfinytecServices.svc/SaveNews',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        data: news
    });

Here's my service part

    [OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "/SaveNews",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    int SaveNews(News news);

WebConfig Comming

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>

  <system.serviceModel>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>

    <extensions>
      <behaviorExtensions>
        <add
          name="crossOriginResourceSharingBehavior"
          type="InfinytecWebService.CORSEnablingBehavior, InfinytecWebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
      </behaviorExtensions>
    </extensions>

    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
          <crossOriginResourceSharingBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <services>
      <service behaviorConfiguration="serviceBehavior" name="InfinytecWebService.InfinytecServices">
        <endpoint address=""
                  behaviorConfiguration="web"
                  binding="webHttpBinding"
                  contract="InfinytecWebService.IInfinytecServices" />
      </service>
    </services>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

And at least , the CORS

public class CORSEnablingBehavior : BehaviorExtensionElement, IEndpointBehavior

    {
        public void AddBindingParameters(
            ServiceEndpoint endpoint,
            BindingParameterCollection bindingParameters){ }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
              new CORSHeaderInjectingMessageInspector()
            );
        }

        public void Validate(ServiceEndpoint endpoint) { }

        public override Type BehaviorType { get { return typeof(CORSEnablingBehavior); } }

        protected override object CreateBehavior() { return new CORSEnablingBehavior(); }

        private class CORSHeaderInjectingMessageInspector : IDispatchMessageInspector
        {
            public object AfterReceiveRequest(
              ref Message request,
              IClientChannel channel,
              InstanceContext instanceContext)
            {
                return null;
            }
            private static IDictionary<string, string> _headersToInject = new Dictionary<string, string>
          {
            { "Access-Control-Allow-Origin", "*" },
            { "Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS" },
            { "Access-Control-Allow-Headers", "X-Requested-With,Content-Type" }
          };
            public void BeforeSendReply(ref Message reply, object correlationState)
            {
                var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
                foreach (var item in _headersToInject)
                    httpHeader.Headers.Add(item.Key, item.Value);
            }
        }
    }

Can you help me?

In advance, thanks! :)