问:
Text align left in a span
I have a paragraph split up as follows:

```<code><a href="#" class="nostyle">
  <p>
    <span class="heading">Really long heading</span><br>
    <br>
    Lots of text that needs to be justified
  </p>
</a>
</code>```

The paragraph is set to text-align: justify, which it needs to stay at.
I want just the  to be text-align: left, so that large gaps don't form between rows. How can I do this?

I want to keep it all as a single paragraph, as it's part of a flex item and having a
 and
 means it won't all work nicely!

Thanks.

答:
The problem is that inline elements do not have a width and cannot be affected by text-align. To fix this, you can set the  to display: block and then it should display with the text aligned to the left, as shown in the snippet below.

NOTE: that I changed text-align: justify to text-align: center in the below snippet to make it easier to see.

p {
  text-align: center;
}

p span {
  display: block;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <p>
    <span class="heading">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum.</span><br>
    <br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum. Aliquam posuere purus vitae justo mollis lobortis vel vitae sapien.
    Sed sapien nibh, tincidunt sed risus vel, vestibulum euismod augue. Quisque molestie vehicula magna, eget pulvinar augue pellentesque nec. Praesent venenatis risus placerat dapibus rhoncus. Aliquam lacinia, dolor non tristique congue, est nunc bibendum
    erat, id varius augue turpis id ipsum.
  </p>
</code>```

However, I really suggest using to
 tags here because that's what they're for. Also note that you're using two
 tags to separate the span from the rest of the text and
 tags implicitly have a
 before and after, so switching to multiple
 would not change the spacing. See below:

p {
  text-align: center;
}

p.heading {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <p class="heading">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum.
  </p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum. Aliquam posuere purus vitae justo mollis lobortis vel vitae sapien.
    Sed sapien nibh, tincidunt sed risus vel, vestibulum euismod augue. Quisque molestie vehicula magna, eget pulvinar augue pellentesque nec. Praesent venenatis risus placerat dapibus rhoncus. Aliquam lacinia, dolor non tristique congue, est nunc bibendum
    erat, id varius augue turpis id ipsum.
  </p>
</code>```

Title: Text align left in a span

Body:
I have a paragraph split up as follows:

    Really long heading

    Lots of text that needs to be justified

The paragraph is set to text-align: justify, which it needs to stay at.
I want just the  to be text-align: left, so that large gaps don't form between rows. How can I do this?

I want to keep it all as a single paragraph, as it's part of a flex item and having a
 and
 means it won't all work nicely!

Thanks.

Body:
The problem is that inline elements do not have a width and cannot be affected by text-align. To fix this, you can set the <span> to display: block and then it should display with the text aligned to the left, as shown in the snippet below.

NOTE: that I changed text-align: justify to text-align: center in the below snippet to make it easier to see.

p {
  text-align: center;
}

p span {
  display: block;
  text-align: left;
}

<a href="#" class="nostyle">
  <p>
    <span class="heading">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum.</span><br>
    <br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum. Aliquam posuere purus vitae justo mollis lobortis vel vitae sapien.
    Sed sapien nibh, tincidunt sed risus vel, vestibulum euismod augue. Quisque molestie vehicula magna, eget pulvinar augue pellentesque nec. Praesent venenatis risus placerat dapibus rhoncus. Aliquam lacinia, dolor non tristique congue, est nunc bibendum
    erat, id varius augue turpis id ipsum.
  </p>
</a>

However, I really suggest using to <p> tags here because that's what they're for. Also note that you're using two <br/> tags to separate the span from the rest of the text and <p> tags implicitly have a <br/> before and after, so switching to multiple <p> would not change the spacing. See below:

p {
  text-align: center;
}

p.heading {
  text-align: left;
}

<a href="#" class="nostyle">
  <p class="heading">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum.
  </p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi convallis magna sit amet sollicitudin posuere. Vestibulum justo ex, lacinia dictum mollis et, egestas eu ipsum. Aliquam posuere purus vitae justo mollis lobortis vel vitae sapien.
    Sed sapien nibh, tincidunt sed risus vel, vestibulum euismod augue. Quisque molestie vehicula magna, eget pulvinar augue pellentesque nec. Praesent venenatis risus placerat dapibus rhoncus. Aliquam lacinia, dolor non tristique congue, est nunc bibendum
    erat, id varius augue turpis id ipsum.
  </p>
</a>


来源: stackexchange

问:
jQuery 1.9 .live() is not a function
I recently updated jQuery from 1.8 to 2.1. I suddenly discovered that the .live() stops working.

I get the error TypeError: $(...).live is not a function.

Is there any method I can use in place of .live()?

答:
If you happen to be using the Ruby on Rails' jQuery gem jquery-rails and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3 and you can lock it by using the following syntax on your Gemfile:

```<code>gem 'jquery-rails', '~> 2.1', '= 2.1.3'
</code>```

then you can use the following command to update:

```<code>bundle update jquery-rails
</code>```

I hope that help others facing a similar issue.

ContentLicense: CC BY-SA 3.0

Title: jQuery 1.9 .live() is not a function

Body:
If you happen to be using the Ruby on Rails' jQuery gem jquery-rails and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3 and you can lock it by using the following syntax on your Gemfile:

gem 'jquery-rails', '~> 2.1', '= 2.1.3'

then you can use the following command to update:

bundle update jquery-rails

I hope that help others facing a similar issue.


问:
Unable to determine the serialization information IIF
I have a price range query I'm trying to write for my C# code and depending on the currency type of the product I need to query the correct field

```<code>var minPrice = builder.Gte(s => s.Price.CurrencyCode == "USD" ? s.Price.Usd : s.Price.Foreign, filter.MinPrice);
var maxPrice = builder.Lte(s => s.Price.CurrencyCode == "USD" ? s.Price.Usd : s.Price.Foreign, filter.MaxPrice);
</code>```

but when I run the code to test this I get the following error:

Unable to determine the serialization information for s => IIF((s.Price.CurrencyCode == ""USD""), s.Price.Usd, s.Price.Foreign).

if I take the ternary out and just look for the US price it works perfectly, but I need to be able to have it look for non US prices as well, am I doing something wrong?

答:
Not sure what's going on here (I think this kind of query is just not supported yet) but how about you rewrite the query like so:</p>

```<code>    var minPrice = (builder.Where(s => s.Price.CurrencyCode == "USD") & builder.Gte(s => s.Price.Usd, filter.MinPrice))
                 | (builder.Where(s => s.Price.CurrencyCode != "USD") & builder.Gte(s => s.Price.Foreign, filter.MinPrice));
    var maxPrice = (builder.Where(s => s.Price.CurrencyCode == "USD") & builder.Lte(s => s.Price.Usd, filter.MaxPrice))
                 | (builder.Where(s => s.Price.CurrencyCode != "USD") & builder.Lte(s => s.Price.Foreign, filter.MaxPrice));
</code>```

Body:
I have a price range query I'm trying to write for my C# code and depending on the currency type of the product I need to query the correct field

var minPrice = builder.Gte(s => s.Price.CurrencyCode == "USD" ? s.Price.Usd : s.Price.Foreign, filter.MinPrice);
var maxPrice = builder.Lte(s => s.Price.CurrencyCode == "USD" ? s.Price.Usd : s.Price.Foreign, filter.MaxPrice);

but when I run the code to test this I get the following error:

Unable to determine the serialization information for s => IIF((s.Price.CurrencyCode == ""USD""), s.Price.Usd, s.Price.Foreign).

if I take the ternary out and just look for the US price it works perfectly, but I need to be able to have it look for non US prices as well, am I doing something wrong?

Body:
Not sure what's going on here (I think this kind of query is just not supported yet) but how about you rewrite the query like so:

    var minPrice = (builder.Where(s => s.Price.CurrencyCode == "USD") & builder.Gte(s => s.Price.Usd, filter.MinPrice))
                 | (builder.Where(s => s.Price.CurrencyCode != "USD") & builder.Gte(s => s.Price.Foreign, filter.MinPrice));
    var maxPrice = (builder.Where(s => s.Price.CurrencyCode == "USD") & builder.Lte(s => s.Price.Usd, filter.MaxPrice))
                 | (builder.Where(s => s.Price.CurrencyCode != "USD") & builder.Lte(s => s.Price.Foreign, filter.MaxPrice));


问:
Cumulative total by group
For the following dataset:

```<code>d = data.frame(date = as.Date(as.Date('2015-01-01'):as.Date('2015-04-10'), origin = "1970-01-01"),
               group = rep(c('A','B','C','D'), 25), value = sample(1:100))
head(d)
         date group value
1: 2015-01-01     A     4
2: 2015-01-02     B    32
3: 2015-01-03     C    46
4: 2015-01-04     D    40
5: 2015-01-05     A    93
6: 2015-01-06     B    10
</code>```

.. can anyone advise a more elegant way to calculate a cumulative total of values by group than this data.table) method?

```<code>library(data.table)
setDT(d)
d.cast = dcast.data.table(d, group ~ date, value.var = 'value', fun.aggregate = sum)
c.sum = d.cast[, as.list(cumsum(unlist(.SD))), by = group]
</code>```

.. which is pretty clunky and yields a flat matrix that needs dplyr::gather or reshape2::melt to reformat.

Surely R can do better than this??

答:
Is this it?</p>

```<code>sp <- split(d, d$group)
res <- lapply(seq_along(sp), function(i) cumsum(sp[[i]]$value))
res <- lapply(seq_along(res), function(i){
        sp[[i]]$c.sum <- res[[i]]
        sp[[i]]
    })
res <- do.call(rbind, res)
res
</code>```

Title: Cumulative total by group

Body:
For the following dataset:

d = data.frame(date = as.Date(as.Date('2015-01-01'):as.Date('2015-04-10'), origin = "1970-01-01"),
               group = rep(c('A','B','C','D'), 25), value = sample(1:100))
head(d)
         date group value
1: 2015-01-01     A     4
2: 2015-01-02     B    32
3: 2015-01-03     C    46
4: 2015-01-04     D    40
5: 2015-01-05     A    93
6: 2015-01-06     B    10

.. can anyone advise a more elegant way to calculate a cumulative total of values by group than this data.table) method?

library(data.table)
setDT(d)
d.cast = dcast.data.table(d, group ~ date, value.var = 'value', fun.aggregate = sum)
c.sum = d.cast[, as.list(cumsum(unlist(.SD))), by = group]

.. which is pretty clunky and yields a flat matrix that needs dplyr::gather or reshape2::melt to reformat.

Surely R can do better than this??

Body:
Is this it?

sp <- split(d, d$group)
res <- lapply(seq_along(sp), function(i) cumsum(sp[[i]]$value))
res <- lapply(seq_along(res), function(i){
        sp[[i]]$c.sum <- res[[i]]
        sp[[i]]
    })
res <- do.call(rbind, res)
res


问:
Display properties of child object in Datagridview
How can I display in a datagridview selected properties of an object, and also selected properties of a member object of this first object?  I think I will not require binding but rely on hard coding updates, because the updates will initiate on non-UI threads, and I think that will not be so easy to bind. At least I've had problems with that in other project.

Basically I'm looking to understand what different ways I can do this. Maybe with LINQ, or whatever is most suitable. Note: I want to display the data in the same table. As the child/parent is a 1:1 relation.

So example code:

```<code>Public Class User
public property Score as Integer
public property Details as UserDetails
End Class

Public Class UserDetails
public property Name as String
public property userName as String
End Class
</code>```

Hence, I want the table to show columns:  Score, Name, UserName

EDIT:
Oh, this was more easy than I thought, seems this will work:

```<code>Dim q = (From n in userList Select New With {n.Score, n.Details.Name, n.Details.userName}).ToArray
</code>```

答:
You can use databinding here, if you use the ITypedList interface to expose the properties you wanted.

ITypedList is very powerful, but somewhat hard to understand, IME.  The best tutorial I've found is Tips for binding grids to hierarchical data using the ITypedList interface

Body:
How can I display in a datagridview selected properties of an object, and also selected properties of a member object of this first object?  I think I will not require binding but rely on hard coding updates, because the updates will initiate on non-UI threads, and I think that will not be so easy to bind. At least I've had problems with that in other project.

Basically I'm looking to understand what different ways I can do this. Maybe with LINQ, or whatever is most suitable. Note: I want to display the data in the same table. As the child/parent is a 1:1 relation.

So example code:

Public Class User
public property Score as Integer
public property Details as UserDetails
End Class

Public Class UserDetails
public property Name as String
public property userName as String
End Class

Hence, I want the table to show columns:  Score, Name, UserName

EDIT:
Oh, this was more easy than I thought, seems this will work:

Dim q = (From n in userList Select New With {n.Score, n.Details.Name, n.Details.userName}).ToArray

ContentLicense: CC BY-SA 2.5


问:
List of strings from split() cant convert to int()
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

```<code>coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))
</code>```

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?

答:
You have a string which matches a float and you are trying to convert that to a int, which is not supported by int. As others suggested use int(float(your_str)).

So the problem is not the split, however, you could also use regexp which might be better suited for user input, as it is much more flexible.

To match an integer you could use:

```<code>pattern = r'(^[-+]?[0-9]+)\.'
re.findall(pattern, your_input_string)
</code>```

EDIT:

Regexp might not work perfectly, you have to test

Body:
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?

Body:
You have a string which matches a float and you are trying to convert that to a int, which is not supported by int. As others suggested use int(float(your_str)).

So the problem is not the split, however, you could also use regexp which might be better suited for user input, as it is much more flexible.

To match an integer you could use:

pattern = r'(^[-+]?[0-9]+)\.'
re.findall(pattern, your_input_string)

EDIT:

Regexp might not work perfectly, you have to test


问:
Why Can I not Get the reference of an object from another class in a namespace c#?
I am trying to open a connection to a database and I have used a configuration string to connect and I've instantiated the sqlConnection object. I would like to be able to use this reference in a new classes method. Why am I not able to achieve this? Why does it say "this class cannot be inherited"?</p>

```<code>namespace sqlLibrary
{
    public class sqlStuff
    {
        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SurplusConnectionString"].ConnectionString);

    }

    public class commands : sqlStuff
    {
        public void executeQuery()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = myConnection; --> Not able to get reference from sql stuff class?
        }
    }
}
</code>```

答:
By default, fields (and other class members) have private access modifier. Thus they are not visible in child classes. You should explicitly specify protected visibility

```<code> protected SqlConnection myConnection
</code>```

See Accessibility Levels (C# Reference)

Body:
I am trying to open a connection to a database and I have used a configuration string to connect and I've instantiated the sqlConnection object. I would like to be able to use this reference in a new classes method. Why am I not able to achieve this? Why does it say "this class cannot be inherited"?

namespace sqlLibrary
{
    public class sqlStuff
    {
        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SurplusConnectionString"].ConnectionString);

    }

    public class commands : sqlStuff
    {
        public void executeQuery()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = myConnection; --> Not able to get reference from sql stuff class?
        }
    }
}

Body:
By default, fields (and other class members) have private access modifier. Thus they are not visible in child classes. You should explicitly specify protected visibility

 protected SqlConnection myConnection

See Accessibility Levels (C# Reference)


问:
Appropriate Data structure
I have to implement the value iteration algorithm for finding the optimal policy for each state of an MDP using Bellman's equation.
The input file is some thing like below:
s1 0 (a1 s1 0.5) (a1 s2 0.5) (a2 s1 1.0)
s2 0 (a1 s2 1.0) (a2 s1 0.5) (a2 s3 0.5)
s3 10 (a1 s2 1.0) (a2 s3 0.5) (a2 s4 0.5)

where s1 is the state 0 is the reward associated with s1. Upon taking action a1, we stay in s1 with probability 0.5. Upon taking action a1, we go to s2 with probability 0.5.Upon taking action a2, we stay in s1 with probability 1.0.
And similarly the others.

After reading the input file, I have to store it in some data structure. Which would be the appropriate data structure to do so in PYTHON so that traversing through it is easy.

答:
Typically for discrete (and finite) state MDPs, HMMs, or POMDPs, the most useful representation is a set of sparse matrices. Then, the probability distribution of moving can be computed with a matrix-vector computation (and the stochastic Bellman equation can be implemented simply and efficiently). The matrix will be called a stochastic matrix.

http://en.wikipedia.org/wiki/Stochastic_matrix

I'd recommend looking at the SciPy library for sparse matrices if you're working in Python.

http://docs.scipy.org/doc/scipy/reference/sparse.html

Title: Appropriate Data structure


问:
How can I std::sqrt(boost::lambda::placeholder1_type)?
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

```<code>#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}
</code>```

However, if I replace the std::cout line with

```<code>std::cout << std::sqrt(boost::lambda::_1) << " "
</code>```

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

答:
Ah, the good old days of Boost.Lambda</p>

```<code>int main() {

    std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

    std::for_each(a.begin(), a.end(),
        std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1 * 5.0) << " "
    );
    return 0;
}
</code>```

Body:
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}

However, if I replace the std::cout line with

std::cout << std::sqrt(boost::lambda::_1) << " "

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

Body:
Ah, the good old days of Boost.Lambda

int main() {

    std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

    std::for_each(a.begin(), a.end(),
        std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1 * 5.0) << " "
    );
    return 0;
}


问:
how to cache frequently served images?
I am using an older version of grails. The grails version is 2.2.0. One problem i am seeing with the current application setup is that the log is flooded with get requests for images from the index page. If i click refresh then all the images are re-requested. The log record for images look as follows

```<code>27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/f6dfNSxvksQkrB83_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/I7w4dlwL1ejngl24_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/eZhBkSt2BQK9fHES_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/Wa7tHggCCmf95GH7_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/3rCuZaRedGvhJGx9_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/23i2HLxd1XbA0Bvd_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/lbsBuqo1Imny2Ggl_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/xtTZU9vrIHzct8sN_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/rbUZx7D59tP67pfs_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/7s47yiB3BmAnzMNX_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/4TvirWFiuhdpWz7I_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/oSBR4E5jH2m8iFiZ_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:21 -0600] "GET /uploads/logos/thumbnails/UGAVMxFQsotu2XNK_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:21 -0600] "GET
</code>```

These are images in the index page of the application and these images are not changed frequently. I am wondering for a manual solution to cache these images so that on every refresh of the page all these images are not re-requested from the application. I appreciate any help! Thanks!

答:
The cached-resources plugin is great for Grails 2 (credit to Mike W for first mention!).

If you plan to upgrade to 2.4, or 3 at any future point, you're probably better served just taking a look at asset pipeline: http://www.asset-pipeline.com/manual/#grails2 and http://plugins.grails.org/plugin/grails/asset-pipeline but that might be more work for you right now.

However, just as a heads up, note that all of the lines in your log that you included are 404's, and the URL of each is different.  In many environments, an error page won't be cached (it's certainly dependent on your setup, but that's pretty common to avoid false positives) and as long as you're requesting different resources every time (by URL) caching isn't going to help!

Title: how to cache frequently served images?

Body:
I am using an older version of grails. The grails version is 2.2.0. One problem i am seeing with the current application setup is that the log is flooded with get requests for images from the index page. If i click refresh then all the images are re-requested. The log record for images look as follows

27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/f6dfNSxvksQkrB83_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/I7w4dlwL1ejngl24_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/eZhBkSt2BQK9fHES_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/Wa7tHggCCmf95GH7_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/3rCuZaRedGvhJGx9_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/23i2HLxd1XbA0Bvd_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/lbsBuqo1Imny2Ggl_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/xtTZU9vrIHzct8sN_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/rbUZx7D59tP67pfs_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/7s47yiB3BmAnzMNX_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/4TvirWFiuhdpWz7I_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:20 -0600] "GET /uploads/logos/thumbnails/oSBR4E5jH2m8iFiZ_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:21 -0600] "GET /uploads/logos/thumbnails/UGAVMxFQsotu2XNK_thumb.jpg HTTP/1.1" 404 1599
27.34.20.149 - - [03/Jul/2017:22:50:21 -0600] "GET

These are images in the index page of the application and these images are not changed frequently. I am wondering for a manual solution to cache these images so that on every refresh of the page all these images are not re-requested from the application. I appreciate any help! Thanks!


问:
bash - How to find the index of the maximum value of a row in a matrix
Here's my input :

```<code>chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907
</code>```

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

```<code>data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)
</code>```

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

```<code>maxindex= 1  1  1  1
</code>```

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

答:
Perl solution:

```<code>perl -ane '$r = 2;
           for my $i (3 .. $#F) {
               $r = $i if $F[$i] > $F[$r];
           }
           print $r - 1, " ";
          ' < input-file > output-file
</code>```

-n processes the input line by line

-a splits each line on whitespace into the @F array

$r stores the index of the maximum (set to 2 before processing each line)

in the for loop, we try all the other indices and store the index of the max if we find it

after having processed the whole line, we output the index - 1 (because indices start from 0 in Perl and you want to ignore the first 2)

Body:
Here's my input :

chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

maxindex= 1  1  1  1

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

Body:
Perl solution:

perl -ane '$r = 2;
           for my $i (3 .. $#F) {
               $r = $i if $F[$i] > $F[$r];
           }
           print $r - 1, " ";
          ' < input-file > output-file

-n processes the input line by line

-a splits each line on whitespace into the @F array

$r stores the index of the maximum (set to 2 before processing each line)

in the for loop, we try all the other indices and store the index of the max if we find it

after having processed the whole line, we output the index - 1 (because indices start from 0 in Perl and you want to ignore the first 2)


问:
How can I take an UIImage and give it a black border?
How can I set the border of a UIImage?

答:
For those looking for a plug-and-play solution on UIImage, I wrote CodyMace's answer as an extension.

Usage: let outlined = UIImage(named: "something")?.outline()

```<code>extension UIImage {

    func outline() -> UIImage? {

        let size = CGSize(width: self.size.width, height: self.size.height)
        UIGraphicsBeginImageContext(size)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        self.draw(in: rect, blendMode: .normal, alpha: 1.0)
        let context = UIGraphicsGetCurrentContext()
        context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
        context?.stroke(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage

    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body: How can I set the border of a UIImage?

Body:
For those looking for a plug-and-play solution on UIImage, I wrote CodyMace's answer as an extension.

Usage: let outlined = UIImage(named: "something")?.outline()

extension UIImage {

    func outline() -> UIImage? {

        let size = CGSize(width: self.size.width, height: self.size.height)
        UIGraphicsBeginImageContext(size)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        self.draw(in: rect, blendMode: .normal, alpha: 1.0)
        let context = UIGraphicsGetCurrentContext()
        context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
        context?.stroke(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage

    }

}


问:
Execute only when array's length reaches X elements
I was wondering if it's possible to execute function only when arrays length is long enough.

I have a setInterval function to repeatedly fetch info from interweb, if a new user appears it will send his id to an array, and I want to execute different function only when this array's length reaches a specific amount.

Thanks in advance!

答: Not sure if this is as simple as it sounds, but why not just check the array length after each insertion of a new user into said array.  If length is greater than your desired size, simply call the function.  </p>


问:
Create table with calculated column
I want to create table with three columns:

```<code>START_DATE|END_DATE|TOTAL_TIME
</code>```

START_DATE and END_DATE should both be dates.
TOTAL_TIME should be calculated by using these two columns. How can I create the table?

答:
You can create a calculated column using the as keyword. Subtracting two dates in Oracle will give you the difference in days. You could then easily convert it to any unit you wish (e.g., multiply by 24 to get the duration in hours):

```<code>CREATE TABLE my_table (
    id NUMBER PRIMARY KEY,
    start_date DATE,
    end_date DATE,
    total_time NUMBER AS (end_date - start_date) -- This is in days
);
</code>```

Title: Create table with calculated column

Body:
I want to create table with three columns:

START_DATE|END_DATE|TOTAL_TIME

START_DATE and END_DATE should both be dates.
TOTAL_TIME should be calculated by using these two columns. How can I create the table?

Body:
You can create a calculated column using the as keyword. Subtracting two dates in Oracle will give you the difference in days. You could then easily convert it to any unit you wish (e.g., multiply by 24 to get the duration in hours):

CREATE TABLE my_table (
    id NUMBER PRIMARY KEY,
    start_date DATE,
    end_date DATE,
    total_time NUMBER AS (end_date - start_date) -- This is in days
);


问:
Google OAuth in Python 3 error
I followed this awesome answer for implementing Google OAuth in Python. However, when I tried running in Python 3, I get this error:

```<code>TypeError: ord() expected string of length 1, but int found
</code>```

This error is thrown by this line:

```<code>o = ord(h[19]) & 15
</code>```

Trying o = ord(str(h[19])) & 15 resulted in:

```<code>TypeError: ord() expected a character, but string of length 3 found
</code>```

This happens in Python 3, but not in Python 2, which makes me think that some types have changed between versions. This is the relevant code:

```<code>def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h
</code>```

I tried to follow this question's answers, but they did not help. The first answer did not help because I am not using a string literal for key or msg. This was my attempt at implementing the second answer's suggestion:

```<code>def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    key_bytes = bytes(key, 'latin-1')

    msg = struct.pack(">Q", intervals_no)
    msg_bytes = bytes(msg, 'latin-1')

    h = hmac.new(key_bytes, msg_bytes, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h
</code>```

This code threw this error on the key_bytes = <...> and msg_bytes = <...>:

```<code>TypeError: encoding without a string argument
</code>```

Using utf-8 instead of latin-1 had the same result.

If I print(key, msg), I get this, which suggests that they are already in a byte-like form:

```<code>b'fooooooo37' b'\x00\x00\x00\x00\x02\xfa\x93\x1e'
</code>```

The msg printed explains the ... string of length 3 found error above.

I am unsure where to go from here. Any suggestions/solutions would be great!

答: hmac.new() returns a string of bytes. In Python 3 this is an array of integers. Hence h[19] is an integer. Just use that int instead of calling ord(). Or decode h to str.

Title: Google OAuth in Python 3 error

Body:
I followed this awesome answer for implementing Google OAuth in Python. However, when I tried running in Python 3, I get this error:

TypeError: ord() expected string of length 1, but int found

This error is thrown by this line:

o = ord(h[19]) & 15

Trying o = ord(str(h[19])) & 15 resulted in:

TypeError: ord() expected a character, but string of length 3 found

This happens in Python 3, but not in Python 2, which makes me think that some types have changed between versions. This is the relevant code:

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

I tried to follow this question's answers, but they did not help. The first answer did not help because I am not using a string literal for key or msg. This was my attempt at implementing the second answer's suggestion:

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    key_bytes = bytes(key, 'latin-1')

    msg = struct.pack(">Q", intervals_no)
    msg_bytes = bytes(msg, 'latin-1')

    h = hmac.new(key_bytes, msg_bytes, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

This code threw this error on the key_bytes = <...> and msg_bytes = <...>:

TypeError: encoding without a string argument

Using utf-8 instead of latin-1 had the same result.

If I print(key, msg), I get this, which suggests that they are already in a byte-like form:

b'fooooooo37' b'\x00\x00\x00\x00\x02\xfa\x93\x1e'

The msg printed explains the ... string of length 3 found error above.

I am unsure where to go from here. Any suggestions/solutions would be great!


问:
trouble logging in to rails app after logout
This community looks great.  I'm new to rails so please bear with some confusion.  I have an app that lets a new user signup.  The user gets created along with a wallet object that obtains a foreign key that matches the users given primary key.  When I click logout, I return to the intended page, but all of a sudden, I am being thrown an "invalid combination" error... I feel like ever since I introduced the current_user helper method, that it's been throwing something off.  Here are pieces of my files

The session's controller

```<code>class SessionsController < ApplicationController
    skip_before_action :require_login, only: [:new, :create]

  def new

  end

 def create
    @user = User.find_by_email(params[:email])
    if @user && @user.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to "/users/#{@user.id}"
    else
      flash[:errors] = ["Invalid Combination"]
      redirect_to "/sessions/new"
    end
  end

  def destroy
    session.delete(:user_id)
    redirect_to "/sessions/new"
  end

end
</code>```

The user's controller

```<code>class UsersController < ApplicationController
  skip_before_action :require_login, only: [:new, :create]
  before_action :require_correct_user, only: [:edit, :show, :update, :destroy]

  def new

  end

  def show
    @user = User.includes(:wallet).find_by_id(params[:id])
  end

  def edit
  end

  def create
    @user = User.create user_params
    @wallet = Wallet.new
    @wallet.save
    @user.wallet_id = @wallet.id
    @wallet.user = @user
    if @user.save && @wallet.save
      session[:user_id] = @user.id

      redirect_to "/users/#{@user.id}"
    else
      flash[:errors] = @user.errors.full_messages + @wallet.errors.full_messages
      redirect_to "/sessions/new"
    end

  end

  private
    def require_correct_user
      if current_user != User.find(params[:id])
        redirect_to "/users/#{session[:user_id]}"
      end
        end

def user_params
        params.require(:user).permit(:email, :motto, :bio, :first_name,
:last_name,
:password, :password_confirmation)
    end

end
</code>```

And finally, here's the view I am directing to for both new signups and existing users login (sessions#new).  Please let me know where you see any potential hiccups! Thanks!

```<code>    <nav>
    <div class="nav-wrapper">
        <a href="#" class="brand-logo center">
        <%=image_tag("straightupLogoSiteHome.png")%></a>
        <ul id="nav-mobile" class="left hide-on-med-and-down">
        </ul>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
        </ul>
        <ul class="side-nav" id="mobile-demo">
        </ul>
    </div>
</nav>
<div class="container">
    <br><br>
    <div class="row">
        <h3 class="center light">SIMPLE P2P BETTING</h3>
        <br><br><br>
        <div class="col s5 push-s7">
            <H5 class="light">OR PLEASE... JOIN US</H5>
            <form action="/users" method="post">
                <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">
                <div class="input-field col s12">
                    <input type="text" id="Email" name = "user[email]">
                    <label for="Email">EMAIL</label>
                </div>
                <div class="input-field col s12">
                    <input type="text" id="Motto" name = "user[motto]">
                    <label for="Motto">YOUR MOTTO (OPTIONAL)</label>
                </div>
                <div class="input-field col s12">
                    <input type="text" id="Bio" name = "user[bio]">
                    <label for="Bio">A BIO (OPTIONAL)</label>
                </div>
                <div class="input-field col s6">
                    <input type="text" id="First_Name" name = "user[first_name]">
                    <label for="First_Name">FIRST NAME</label>
                </div>
                <div class="input-field col s6">
                    <input type="text" id="Last_Name" name = "user[last_name]">
                    <label for="Last_Name">HOUSE NAME</label>
                </div>
                <div class="input-field col s6">
                    <input type="text" id="Password" name = "user[password]">
                    <label for="Password">PASSWORD</label>
                </div>
                <div class="input-field col s6">
                    <input type="text" id="Password_Confirmation" name = "user[password_confirmation]">
                    <label for="Password_Confirmation">AND AGAIN!</label>
                </div>
                <a class="waves-effect waves-light btn"><input type="submit" name="Join" value="JOIN US"></a>
            </form>
        </div>
        <div class="col s4 pull-s4">
            <H5 class="light">LOG BACK IN. sorry...</H5>
            <form action="/sessions" method="post">
                <input type="hidden" name="authenticity_token" value="<%=
form_authenticity_token %>">
                <div class="input-field col s12">
                    <input type="text" id="Email" name = "user[email]">
                    <label for="Email">EMAIL</label>
                </div>
                <div class="input-field col s12">
                    <input type="text" id="Password" name = "user[password]">
                    <label for="Password">PASSWORD</label>
                </div>
                <a class="waves-effect waves-light btn"><input type="submit" name="login" value="Login"></a>
            </form>
        </div>
    </div>
</div>
</code>```

Aplogies. The current_user is defined in the applications_controller below.  Thanks!

```<code>class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

  def authorize
    redirect_to "/sessions/new" unless current_user
  end
end
</code>```

答:
Ok.  The issue was here... The answer I received was a bit of a workaround which is not at all what I need when I'm learning.  So in my sessions_controller, I was defining a user by the params specified for the user in the users_controller.  What I needed to do was define say login_params within the sessions_controller.. either that or in the create method .find_by_email(params[user.email]).  I chose to create this private method at the bottom and changed the
.find_by_email(params[:email]) and the authenticate(params[:password])
to
.find_by_email(login_params[:email]) and the authenticate(login_params[:password]) </p>

```<code> private

  def login_params
    params.require(:user).permit(:email, :password)
  end
</code>```

Body:
This community looks great.  I'm new to rails so please bear with some confusion.  I have an app that lets a new user signup.  The user gets created along with a wallet object that obtains a foreign key that matches the users given primary key.  When I click logout, I return to the intended page, but all of a sudden, I am being thrown an "invalid combination" error... I feel like ever since I introduced the current_user helper method, that it's been throwing something off.  Here are pieces of my files

The session's controller

class SessionsController < ApplicationController
    skip_before_action :require_login, only: [:new, :create]

  def new

  end

 def create
    @user = User.find_by_email(params[:email])
    if @user && @user.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to "/users/#{@user.id}"
    else
      flash[:errors] = ["Invalid Combination"]
      redirect_to "/sessions/new"
    end
  end

  def destroy
    session.delete(:user_id)
    redirect_to "/sessions/new"
  end

end

The user's controller

class UsersController < ApplicationController
  skip_before_action :require_login, only: [:new, :create]
  before_action :require_correct_user, only: [:edit, :show, :update, :destroy]

  def new

  end

  def show
    @user = User.includes(:wallet).find_by_id(params[:id])
  end

  def edit
  end

  def create
    @user = User.create user_params
    @wallet = Wallet.new
    @wallet.save
    @user.wallet_id = @wallet.id
    @wallet.user = @user
    if @user.save && @wallet.save
      session[:user_id] = @user.id

      redirect_to "/users/#{@user.id}"
    else
      flash[:errors] = @user.errors.full_messages + @wallet.errors.full_messages
      redirect_to "/sessions/new"
    end

  end

  private
    def require_correct_user
      if current_user != User.find(params[:id])
        redirect_to "/users/#{session[:user_id]}"
      end
        end

def user_params
        params.require(:user).permit(:email, :motto, :bio, :first_name,
:last_name,
:password, :password_confirmation)
    end

end

And finally, here's the view I am directing to for both new signups and existing users login (sessions#new).  Please let me know where you see any potential hiccups! Thanks!

        <%=image_tag("straightupLogoSiteHome.png")%>

SIMPLE P2P BETTING

OR PLEASE... JOIN US

            <form action="/users" method="post">
                <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">

                    <input type="text" id="Email" name = "user[email]">
                    EMAIL

                    <input type="text" id="Motto" name = "user[motto]">
                    YOUR MOTTO (OPTIONAL)

                    <input type="text" id="Bio" name = "user[bio]">
                    A BIO (OPTIONAL)

                    <input type="text" id="First_Name" name = "user[first_name]">
                    FIRST NAME

                    <input type="text" id="Last_Name" name = "user[last_name]">
                    HOUSE NAME

                    <input type="text" id="Password" name = "user[password]">
                    PASSWORD

                    <input type="text" id="Password_Confirmation" name = "user[password_confirmation]">
                    AND AGAIN!

                <input type="submit" name="Join" value="JOIN US">
            </form>

LOG BACK IN. sorry...

            <form action="/sessions" method="post">
                <input type="hidden" name="authenticity_token" value="<%=
form_authenticity_token %>">

                    <input type="text" id="Email" name = "user[email]">
                    EMAIL

                    <input type="text" id="Password" name = "user[password]">
                    PASSWORD

                <input type="submit" name="login" value="Login">
            </form>

Aplogies. The current_user is defined in the applications_controller below.  Thanks!

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

  def authorize
    redirect_to "/sessions/new" unless current_user
  end
end

Body:
Ok.  The issue was here... The answer I received was a bit of a workaround which is not at all what I need when I'm learning.  So in my sessions_controller, I was defining a user by the params specified for the user in the users_controller.  What I needed to do was define say login_params within the sessions_controller.. either that or in the create method .find_by_email(params[user.email]).  I chose to create this private method at the bottom and changed the
.find_by_email(params[:email]) and the authenticate(params[:password])
to
.find_by_email(login_params[:email]) and the authenticate(login_params[:password])

 private

  def login_params
    params.require(:user).permit(:email, :password)
  end


问:
how to check if data exist in mysql database before enter
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

```<code> TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID
</code>```

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

```<code>`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "<b>";
   echo "<h3>";
   echo "RECORD ADDED ";
   echo "<h3>";
   echo "</b>";
 }
   else
 {
 echo "<b>";
 echo "<h3>";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "</h3>";
 echo "</b>";
 echo "<br>";
 echo mysql_error();
  }
 ?>
</code>```

`

NOTE:ST2_ID is auto increment

I need your thought guys.

答:
Easily you can make it in PHP, first, you do a query:

```<code>SELECT * FROM TABLE2 WHERE name = '$name'
</code>```

Then:

```<code>if(mysql_num_rows($queryExecuted) > 0) { /* insert to table 2 */}
</code>```

We check if the query had return at least one row (where $queryExecuted is the return object of the SELECT)

Body:
Table 1 is loaded with data as seen below, there is TABLE 2 which is empty but contain same structure as TABLE1 my problem is if i want to insert data inTABLE 2 i want to to check first in TABLE 1 if records to be entered in TABLE 2 have same name as NAME column from TABLE 1 if NAME are not same data should be ignored and not entered into database.

 TABLE 1
 ST_ID   NAME          MATHS   GEOGRAPHY   ENGLISH
  1001   Alan Wegman    80       85          70
  1002   Robert Franko  79       65          60
  1003   Francis John   90       75          67
  1004   Finn Harry     88       87          93

  TABLE 2
  ST2_ID   NAME   MATHS   GEOGRAPHY   ENGLISH   ST_ID

These are my codes so far, even if there is alternative way of doing what i want i will appreciate if you share with me.

`$query="insert into student_info (NAME, MATHS, GEOGRAPHY, ENGLISH)  VALUES ('$name','$maths','$geog','$english')";

 if (mysql_query($query))
 {
   echo "";
   echo "
";
   echo "RECORD ADDED ";
   echo "
";
   echo "";
 }
   else
 {
 echo "";
 echo "
";
 echo "RECORD NOT ENTERED SOMETHING WENT WRONG";
 echo "
";
 echo "";
 echo "
";
 echo mysql_error();
  }
 ?>

`

NOTE:ST2_ID is auto increment

I need your thought guys.

Body:
Easily you can make it in PHP, first, you do a query:

SELECT * FROM TABLE2 WHERE name = '$name'

Then:

if(mysql_num_rows($queryExecuted) > 0) { /* insert to table 2 */}

We check if the query had return at least one row (where $queryExecuted is the return object of the SELECT)


问:
Using jQuery is there a way to capitalize the first letter of each word in a datalist option value
I have an input form with a datalist of options. I would like to capitalize the first letter of each word in the value attribute.

What I have:

```<code><div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New hampshire"></option>
    <option value="New jersey"></option>
    <option value="New mexico"></option>
    <option value="New york"></option>
    <option value="North carolina"></option>
    <option value="North dakota"></option>
    <option value="Rhode island"></option>
    <option value="South carolina"></option>
    <option value="South dakota"></option>
    <option value="West virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>
</code>```

What I need:

```<code><div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New Hampshire"></option>
    <option value="New Jersey"></option>
    <option value="New Mexico"></option>
    <option value="New York"></option>
    <option value="North Carolina"></option>
    <option value="North Dakota"></option>
    <option value="Rhode Island"></option>
    <option value="South Carolina"></option>
    <option value="South Dakota"></option>
    <option value="West Virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>
</code>```

答:
Untested, but it should work something like this, for the replace method have a look at this answer:</p>

```<code>function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
// grep all options
var dataList = $('#states').find('option');
// loop over them
dataList.each(function() {
    // and replace the original value
    this.value = toTitleCase(this.value);
});
</code>```

Body:
I have an input form with a datalist of options. I would like to capitalize the first letter of each word in the value attribute.

What I have:

<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New hampshire"></option>
    <option value="New jersey"></option>
    <option value="New mexico"></option>
    <option value="New york"></option>
    <option value="North carolina"></option>
    <option value="North dakota"></option>
    <option value="Rhode island"></option>
    <option value="South carolina"></option>
    <option value="South dakota"></option>
    <option value="West virginia"></option>
</datalist><button class="btn btn-default" type="submit"></button>

What I need:

<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New Hampshire"></option>
    <option value="New Jersey"></option>
    <option value="New Mexico"></option>
    <option value="New York"></option>
    <option value="North Carolina"></option>
    <option value="North Dakota"></option>
    <option value="Rhode Island"></option>
    <option value="South Carolina"></option>
    <option value="South Dakota"></option>
    <option value="West Virginia"></option>
</datalist><button class="btn btn-default" type="submit"></button>

Body:
Untested, but it should work something like this, for the replace method have a look at this answer:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
// grep all options
var dataList = $('#states').find('option');
// loop over them
dataList.each(function() {
    // and replace the original value
    this.value = toTitleCase(this.value);
});


问:
Is it spread "syntax" or the spread "operator"?
I've heard ... referred to both as 'spread syntax' and 'the spread operator', with the latter being a lot more popular. The URL of the relevant MDN documentation suggests that it was initially referred to as the spread operator but later changed to spread syntax, and MDN's list of operators doesn't mention it.

Google seems to suggest the term operator is more popular and accepted, with sites such as the Microsoft documentation and es6-features.org referring to it as such.

Which term would be the most correct in the context of ECMAScript, if any, and why? What about array destructuring assignment?

答:
It's not an operator.

In all senses of the word, it's not one. It has  been a huge misconception since it was introduced and despite popular opinion -- it's not one, and there are a few objective points to be made:

It doesn't fit the definition of an operator

It can't be used as an operator

The language specification implies that it's not an operator

It should be mentioned that spread syntax comes in different 'flavors', used in different contexts and are commonly referred to by different names while using the same punctuator. Spread syntax is basically an umbrella term for the application of the ... punctuator, and see Felix Kling's great answer detailing all the uses and names. More explanation about these individuals uses is given in the supplementary answer.

What is an operator?

Semantically, in the context of ECMAScript, operators are just builtin functions that take in arguments and evaluate to a single value -- written in prefix, infix, or postfix notation and usually with symbolic names such as + or /. From Wikipedia:

Simply, an expression involving an operator is evaluated in some way, and the resulting value may be just a value (an r-value), or may be an object allowing assignment (an l-value).

For example, the + operator results in a value such as 2, which is a right-hand-side expression, and the . operator results in an object allowing assignment such as foo.bar, a left-hand-side expression.

On the surface, the ... punctuator1 looks to be a prefix unary operator:

```<code>const baz = [foo, ...bar];
</code>```

But the problem with that argument is that ...bar doesn't evaluate to a singular value; it spreads the iterable bar's elements, one by one. The same goes for spread arguments:

```<code>foo(...bar);
</code>```

Here, foo receives separate arguments from the iterable bar. They're separate values being passed to foo, not just one value. It doesn't fit the definition of an operator, so it isn't one.

Why isn't it an operator?

Another point to be made is that operators are meant to be standalone and return a single value. For example:

```<code>const bar = [...foo];
</code>```

As already mentioned, this works well. The problem arises when you try to do this:

```<code>const bar = ...foo;
</code>```

If spread syntax were an operator, the latter would work fine because operators evaluate the expression to a single value but spread doesn't so it fails. Spread syntax and spread arguments only work in the context of arrays and function calls because those structures receive multiple values supplied by spreading array elements or arguments. Evaluating to multiple values is outside of the scope of what an operator is able to do.

What do the standards say?

The complete list of operators is listed in Clauses §12.5 through §12.15 in the ECMAScript 2015 Language Specification, the specification in which ... is introduced, which doesn't mention .... It can also be inferred that it's not an operator. The two main cases mentioned in this answer in which spread syntax is in a production, for function calls (spread arguments) or array literals (spread syntax) are described below:

```ArrayLiteral :
  [ Elision<sub>opt</sub> ]
  [ ElementList ]
  [ ElementList , Elisionopt ]

ElementList :
  Elision<sub>opt</sub> AssignmentExpression
  Elision<sub>opt</sub> SpreadElement
  ElementList , Elision<sub>opt</sub> AssignmentExpression
  ElementList , Elision<sub>opt</sub> SpreadElement

Elision :
  ,
  Elision ,

SpreadElement :
  ... AssignmentExpression
  ```

And for function calls:

```CallExpression :
  MemberExpression Arguments

Arguments :
  ( )
  ( ArgumentList )

ArgumentList :
  AssignmentExpression
  ... AssignmentExpression
  ArgumentList , AssignmentExpression
  ArgumentList , ... AssignmentExpression
  ```

In these productions, there's a conclusion that can be made: that the spread 'operator' doesn't exist. As mentioned earlier, operators should be standalone, as in const bar = ...foo and evaluate to one single value.  The syntax of the language prevents this, which means spread syntax was never meant to be standalone. It's an extension to array initializers and function calls, an extension to their grammar.

Why spread 'syntax'?

Syntax, as defined by Wikipedia:

In computer science, the syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language.

Syntax is basically the 'form' of the language, rules that govern what is legal or not regarding how the code should look, and how the code should be written. In this case,  ECMAScript's grammar specifically defines the ... punctuator to only appear in function calls and array literals as an extension -- which is a rule that defines a combination of symbols (...foo) that are considered to be legal together, thus it is syntax similar to how an arrow function (=>) is not an operator, but syntax2.

Calling ... an operator is a misnomer. An operator is a builtin function that takes in arguments (operands) and is in the form of prefix, infix, or postfix notation and evaluates to exactly one value. ..., while satisfying the first two conditions, does not satisfy the last. ..., instead, is syntax because it is defined specifically and explicitly in the language's grammar.  Thus, 'the spread operator' is objectively more correctly referred to as 'spread syntax'.

1 The term 'punctuator' refers to punctuators in ECMAScript 2015 and later specifications. These symbols include syntax components and operators, and are punctators of the language. ... is a punctuator itself, but the term 'spread syntax' refers to the whole application of the punctuator.

2 => itself is a punctuator, just as ... but what I'm referring to specifically is arrow function syntax, the application of the => punctuator ((…) => { … }), just as spread syntax refers to the application of the ... punctuator.

Body:
It's not an operator.

In all senses of the word, it's not one. It has  been a huge misconception since it was introduced and despite popular opinion -- it's not one, and there are a few objective points to be made:

It doesn't fit the definition of an operator

It can't be used as an operator

The language specification implies that it's not an operator

It should be mentioned that spread syntax comes in different 'flavors', used in different contexts and are commonly referred to by different names while using the same punctuator. Spread syntax is basically an umbrella term for the application of the ... punctuator, and see Felix Kling's great answer detailing all the uses and names. More explanation about these individuals uses is given in the supplementary answer.

What is an operator?

Semantically, in the context of ECMAScript, operators are just builtin functions that take in arguments and evaluate to a single value -- written in prefix, infix, or postfix notation and usually with symbolic names such as + or /. From Wikipedia:

Simply, an expression involving an operator is evaluated in some way, and the resulting value may be just a value (an r-value), or may be an object allowing assignment (an l-value).

For example, the + operator results in a value such as 2, which is a right-hand-side expression, and the . operator results in an object allowing assignment such as foo.bar, a left-hand-side expression.

On the surface, the ... punctuator1 looks to be a prefix unary operator:

const baz = [foo, ...bar];

But the problem with that argument is that ...bar doesn't evaluate to a singular value; it spreads the iterable bar's elements, one by one. The same goes for spread arguments:

foo(...bar);

Here, foo receives separate arguments from the iterable bar. They're separate values being passed to foo, not just one value. It doesn't fit the definition of an operator, so it isn't one.

Why isn't it an operator?

Another point to be made is that operators are meant to be standalone and return a single value. For example:

const bar = [...foo];

As already mentioned, this works well. The problem arises when you try to do this:

const bar = ...foo;

If spread syntax were an operator, the latter would work fine because operators evaluate the expression to a single value but spread doesn't so it fails. Spread syntax and spread arguments only work in the context of arrays and function calls because those structures receive multiple values supplied by spreading array elements or arguments. Evaluating to multiple values is outside of the scope of what an operator is able to do.

What do the standards say?

The complete list of operators is listed in Clauses §12.5 through §12.15 in the ECMAScript 2015 Language Specification, the specification in which ... is introduced, which doesn't mention .... It can also be inferred that it's not an operator. The two main cases mentioned in this answer in which spread syntax is in a production, for function calls (spread arguments) or array literals (spread syntax) are described below:

ArrayLiteral :
  [ Elisionopt ]
  [ ElementList ]
  [ ElementList , Elisionopt ]

ElementList :
  Elisionopt AssignmentExpression
  Elisionopt SpreadElement
  ElementList , Elisionopt AssignmentExpression
  ElementList , Elisionopt SpreadElement

Elision :
  ,
  Elision ,

SpreadElement :
  ... AssignmentExpression

And for function calls:

CallExpression :
  MemberExpression Arguments

Arguments :
  ( )
  ( ArgumentList )

ArgumentList :
  AssignmentExpression
  ... AssignmentExpression
  ArgumentList , AssignmentExpression
  ArgumentList , ... AssignmentExpression

In these productions, there's a conclusion that can be made: that the spread 'operator' doesn't exist. As mentioned earlier, operators should be standalone, as in const bar = ...foo and evaluate to one single value.  The syntax of the language prevents this, which means spread syntax was never meant to be standalone. It's an extension to array initializers and function calls, an extension to their grammar.

Why spread 'syntax'?

Syntax, as defined by Wikipedia:

In computer science, the syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language.

Syntax is basically the 'form' of the language, rules that govern what is legal or not regarding how the code should look, and how the code should be written. In this case,  ECMAScript's grammar specifically defines the ... punctuator to only appear in function calls and array literals as an extension -- which is a rule that defines a combination of symbols (...foo) that are considered to be legal together, thus it is syntax similar to how an arrow function (=>) is not an operator, but syntax2.

Calling ... an operator is a misnomer. An operator is a builtin function that takes in arguments (operands) and is in the form of prefix, infix, or postfix notation and evaluates to exactly one value. ..., while satisfying the first two conditions, does not satisfy the last. ..., instead, is syntax because it is defined specifically and explicitly in the language's grammar.  Thus, 'the spread operator' is objectively more correctly referred to as 'spread syntax'.

1 The term 'punctuator' refers to punctuators in ECMAScript 2015 and later specifications. These symbols include syntax components and operators, and are punctators of the language. ... is a punctuator itself, but the term 'spread syntax' refers to the whole application of the punctuator.

2 => itself is a punctuator, just as ... but what I'm referring to specifically is arrow function syntax, the application of the => punctuator ((…) => { … }), just as spread syntax refers to the application of the ... punctuator.


问:
Microsoft LUIS: Prebuilt entities and Intent
If I have a prebuilt entity temperature.

And how can I match it to my intent AskTemperature

Because In the AskTemperature.

It can't add the prebuilt entity.

So how do I implement to make entity temperature belongs to the intent AskTemperature?

Thank you!!!

答:
After you trained your model/intents, the prebuilt entities should be assigned to that utterances.

I have this utterance: are there room available on 12/21/2016?

When I tried to assign the 12/21/2016 to "datetimeV2" entity directly, I cannot find that prebuilt entity; but after I trained it, it shows automatically.

Click to see this image (cannot post image since reputation not reaching 10)

Hope this helps!


问:
how can i get 2d array by JSONArray in getting array from php?
this is in my activity for getting 2d array

```<code>    Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);

                //what to do here

            } catch (JSONException e) {
                e.printStackTrace();
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Error")
                        .setNegativeButton("Retry", null)
                        .create()
                        .show();

            }
        }
    };
</code>```

getting this value of "response" on calling it: (i edited this one)
use JSONArray in this code

```<code>{
   "0":[],
   "success":[true],
   "question":{
      "1":"question3",
      "2":"question1",
      "3":"question4"
   },
   "optiona":{
      "1":"optiona",
      "2":"optiona",
      "3":"optiona"
   },
   "optionb":{
      "1":"optionb",
      "2":"optionb",
      "3":"optionb"
   },
   "optionc":{
      "1":"optionc",
      "2":"optionc",
      "3":"optionc"
   },
   "optiond":{
      "1":"optiond",
      "2":"optiond",
      "3":"optiond"
   },
   "correct":{
      "1":"optiona",
      "2":"optionb",
      "3":"optiona"
   }
}
</code>```

want to make arrays like (in android):-

Arrayquestion=["question1","question2","question3"]

Arrayoptiona=["optiona","optiona","optiona"]

Arrayoptionb=["optionb","optionb","optionb"]

Arrayoptionc=["optionc","optionc","optionc"]

Arrayoptiond=["optiond","optiond","optiond"]

Arraycorrect=["optiona","optionb","optiona"]

success=[true]

答:
```<code>JSONObject jsonResponse = new JSONObject(string);
String[] question = readJsonObject(jsonResponse.getJSONObject("question"));
String[] optiona = readJsonObject(jsonResponse.getJSONObject("optiona"));
String[] optionb = readJsonObject(jsonResponse.getJSONObject("optionb"));
String[] optionc = readJsonObject(jsonResponse.getJSONObject("optionc"));
String[] optiond = readJsonObject(jsonResponse.getJSONObject("optiond"));
String[] correct = readJsonObject(jsonResponse.getJSONObject("correct"));
boolean success = jsonResponse.getBoolean("success");
</code>```

And helper method:

```<code>private String[] readJsonObject(JSONObject jsonObject) throws JSONException {
        String[] result = new String[3];
        result[0] = jsonObject.getString(Integer.toString(1));
        result[1] = jsonObject.getString(Integer.toString(2));
        result[2] = jsonObject.getString(Integer.toString(3));
        return result;
 }
</code>```

Hope it helps.

Body:
this is in my activity for getting 2d array

    Response.Listener<String> responseListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);

                //what to do here

            } catch (JSONException e) {
                e.printStackTrace();
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("Error")
                        .setNegativeButton("Retry", null)
                        .create()
                        .show();

            }
        }
    };

getting this value of "response" on calling it: (i edited this one)
use JSONArray in this code

{
   "0":[],
   "success":[true],
   "question":{
      "1":"question3",
      "2":"question1",
      "3":"question4"
   },
   "optiona":{
      "1":"optiona",
      "2":"optiona",
      "3":"optiona"
   },
   "optionb":{
      "1":"optionb",
      "2":"optionb",
      "3":"optionb"
   },
   "optionc":{
      "1":"optionc",
      "2":"optionc",
      "3":"optionc"
   },
   "optiond":{
      "1":"optiond",
      "2":"optiond",
      "3":"optiond"
   },
   "correct":{
      "1":"optiona",
      "2":"optionb",
      "3":"optiona"
   }
}

want to make arrays like (in android):-

Arrayquestion=["question1","question2","question3"]

Arrayoptiona=["optiona","optiona","optiona"]

Arrayoptionb=["optionb","optionb","optionb"]

Arrayoptionc=["optionc","optionc","optionc"]

Arrayoptiond=["optiond","optiond","optiond"]

Arraycorrect=["optiona","optionb","optiona"]

success=[true]

Body:
JSONObject jsonResponse = new JSONObject(string);
String[] question = readJsonObject(jsonResponse.getJSONObject("question"));
String[] optiona = readJsonObject(jsonResponse.getJSONObject("optiona"));
String[] optionb = readJsonObject(jsonResponse.getJSONObject("optionb"));
String[] optionc = readJsonObject(jsonResponse.getJSONObject("optionc"));
String[] optiond = readJsonObject(jsonResponse.getJSONObject("optiond"));
String[] correct = readJsonObject(jsonResponse.getJSONObject("correct"));
boolean success = jsonResponse.getBoolean("success");

And helper method:

private String[] readJsonObject(JSONObject jsonObject) throws JSONException {
        String[] result = new String[3];
        result[0] = jsonObject.getString(Integer.toString(1));
        result[1] = jsonObject.getString(Integer.toString(2));
        result[2] = jsonObject.getString(Integer.toString(3));
        return result;
 }

Hope it helps.


问:
How can I check who is running my DNS?
I set up cloudflare with ssl and a 301 redirect to ssl this morning. Everything seemed to work, but now, i'm back on http and the redirect is not working. I'm trying to figure out why and the DNS-system is sometimes a bit hard to decipher. I'm using a swedish registrar, Loopia. Loopia in turn passes the DNS-records to cloudflare.

Is there some way to figure out if I even go through cloudflare any more?

答:
To determine which names servers you have set:
    dig NS DOMAIN

This should only return Cloudflare name servers (unless you enabled Cloudflare via your hosting provider's integration). If you see other name servers in addition to the Cloudflare name servers that indicates you left your other names servers in place at the time you setup Cloudflare. To use Cloudflare you'd need to remove all other name servers other than the ones they provide. Other name servers being in place would return non-Cloudflare IPs which would explain the behavior you're seeing.

Title: How can I check who is running my DNS?


问:
how do get number separately
I have number from 1 to 100 in column A1 to A100.

I am trying to achieve two results from data.

I want separately 1,2,3,4,5,6,7,8,9 and another one 10,20,30,40,50,60,70,80,90,100

Please help me

答:
Maybe, in B1:

```<code>=1*(LEN(A1)=1)+2*(RIGHT(A1)="0")
</code>```

double-click the fill handle and sort A:B on ColumnB.

Title: how do get number separately

Body:
Maybe, in B1:

=1*(LEN(A1)=1)+2*(RIGHT(A1)="0")

double-click the fill handle and sort A:B on ColumnB.


问:
Adding dimensions using numpy.reshape()
I have a situation I'm trying to resolve. I have climate model data in an array with 480 monthly entries at the latitude and longitude grid points of this model (the particulars are irrelevant). That is, I have a numpy array with dimensions (480, lat, lon).

I need to create yearly averages at each spatial grid point. The way I would like to do this is by using numpy.reshape() to make a 4D array with dimensions (480/12, 12, lat, lon) (where I group the timesteps into groups of 12 and restack them, as it were). Then I would average along the second axis (np.mean(dat_new, axis = 1)).

The whole thing would be

```<code>dat_new = np.reshape(dat, (dat.shape[0]/12, 12, dat.shape[1], dat.shape[2]))
dat_annual_mean = np.mean(dat_new, axis = 1)
</code>```

My question is: does reshape work this way? Would it rearrange things in the correct order? If not (or even if so) is there another (potentially less clumsy way to do this?)

Thanks.

答:
You should first permute the dimensions so that your data is reshaped in the correct order.

```<code>dat_new=np.reshape(np.transpose(dat,(1,2,0)),
                   (dat.shape[1],dat.shape[2],dat.shape[0]//12, 12))
dat_annual_mean = np.mean(dat_new, axis = 3)
</code>```

i.e. it will give you an array with dimensions (lat, lon, 480/12), which you can transpose further if necessary.

Title: Adding dimensions using numpy.reshape()

Body:
I have a situation I'm trying to resolve. I have climate model data in an array with 480 monthly entries at the latitude and longitude grid points of this model (the particulars are irrelevant). That is, I have a numpy array with dimensions (480, lat, lon).

I need to create yearly averages at each spatial grid point. The way I would like to do this is by using numpy.reshape() to make a 4D array with dimensions (480/12, 12, lat, lon) (where I group the timesteps into groups of 12 and restack them, as it were). Then I would average along the second axis (np.mean(dat_new, axis = 1)).

The whole thing would be

dat_new = np.reshape(dat, (dat.shape[0]/12, 12, dat.shape[1], dat.shape[2]))
dat_annual_mean = np.mean(dat_new, axis = 1)

My question is: does reshape work this way? Would it rearrange things in the correct order? If not (or even if so) is there another (potentially less clumsy way to do this?)

Thanks.

Body:
You should first permute the dimensions so that your data is reshaped in the correct order.

dat_new=np.reshape(np.transpose(dat,(1,2,0)),
                   (dat.shape[1],dat.shape[2],dat.shape[0]//12, 12))
dat_annual_mean = np.mean(dat_new, axis = 3)

i.e. it will give you an array with dimensions (lat, lon, 480/12), which you can transpose further if necessary.


问:
Combine Radiobuttons with Tabs
I've tried to combine tabs with radio buttons in bootstrap v4, but I couldn't make it completely working. After failing to easily adapt that in v4, I've found the following versions for bootstrap v2:

Using radio buttons for tab control using bootstrap

http://bootsnipp.com/snippets/featured/radio-button-tabs

I tried to adapt them to v4, but I couldn't make it fully working. Either the tab does not change or the active state is not maintained anymore.

The general code is presented in the following:

```<code><div class="btn-group" data-toggle="buttons">
  <a id="a_rr_html" href="#html" class="btn btn-primary active" data-toggle="tab"><input type="radio" />HTML</a>
  <a id="a_rr_json" href="#json" class="btn btn-primary" data-toggle="tab"><input type="radio" />JSON</a>
</div>

<div class="tab-content">
  <div class="html tab-pane active" id="html" role="tabpanel">
  </div>
  <div class="tab-pane" id="json" role="tabpanel">
  </div>
</div>
</code>```

If I remove the data-toggle="tab", the radio button's active state is again maintained correctly, but obviously the tabs do not change anymore. When I created a custom function onClick, the bootstrap callback was not called anymore. As far as I could understand it, the combination of both prevents some bootstrap callbacks to work properly which results in the described problems.

答:
I was trying to do something similar. Triggering the tab-pane through radio button. I got the "onclick" triggering to fire using the data-toggle attr BUT the radio button was not getting the ":checked" state. My HTML snippet is below

<form id="selectForm">

                <input type="radio" name="distTravel" value="state" class="custom-control-input"/>

                Travel within State

                <input type="radio" name="distTravel" value="NA" class="custom-control-input"/>

                 Travel within NA

                <input type="radio" name="distTravel" value="World" class="custom-control-input" />

                 International Travel

</form>

        "foo"

        "boo"

        "soo"

```

In the end, I just came up with my own solution. I think you can incorporate this code into yours. I removed the BS4.0 data attr triggers and created a jQuery snippet to trigger hide() and show();

JSFiddle

Title: Combine Radiobuttons with Tabs

Body:
I've tried to combine tabs with radio buttons in bootstrap v4, but I couldn't make it completely working. After failing to easily adapt that in v4, I've found the following versions for bootstrap v2:

Using radio buttons for tab control using bootstrap

http://bootsnipp.com/snippets/featured/radio-button-tabs

I tried to adapt them to v4, but I couldn't make it fully working. Either the tab does not change or the active state is not maintained anymore.

The general code is presented in the following:

  <input type="radio" />HTML
  <input type="radio" />JSON

If I remove the data-toggle="tab", the radio button's active state is again maintained correctly, but obviously the tabs do not change anymore. When I created a custom function onClick, the bootstrap callback was not called anymore. As far as I could understand it, the combination of both prevents some bootstrap callbacks to work properly which results in the described problems.

Body:
I was trying to do something similar. Triggering the tab-pane through radio button. I got the "onclick" triggering to fire using the data-toggle attr BUT the radio button was not getting the ":checked" state. My HTML snippet is below

<form id="selectForm">
    <ul class="nav flex-column">
        <li class="nav-item" >
            <label class="custom-control custom-radio" data-toggle="tab" data-target="#onlyON">
                <input type="radio" name="distTravel" value="state" class="custom-control-input"/>
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">Travel within State</span>
            </label>
        </li>
        <li class="nav-item">
            <label class="custom-control custom-radio" data-toggle="tab" data-target="#onlyNA">
                <input type="radio" name="distTravel" value="NA" class="custom-control-input"/>
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description"> Travel within NA</span>
            </label>
        </li>
        <li class="nav-item">
            <label class="custom-control custom-radio" data-toggle="tab" data-target="#world">
                <input type="radio" name="distTravel" value="World" class="custom-control-input" />
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description"> International Travel</span>
            </label>
        </li>
    </ul>
</form>

<div class="tab-content">
    <div class="card-block tab-pane" id="onlyON" >
        "foo"
    </div>
    <div class="card-block tab-pane" id="onlyNA" >
        "boo"
    </div>
    <div class="card-block tab-pane" id="world" >
        "soo"
    </div>
</div>

In the end, I just came up with my own solution. I think you can incorporate this code into yours. I removed the BS4.0 data attr triggers and created a jQuery snippet to trigger hide() and show();

JSFiddle


问:
PHP to clean-up pasted Microsoft input
I have a site where users can post stuff (as in forums, comments, etc) using a customised implementation of TinyMCE. A lot of them like to copy & paste from Word, which means their input often comes with a plethora of associated MS inline formatting.

I can't just get rid of  as TinyMCE relies on the span tag for some of it's formatting, and I can't (and don't want to) force said users to use TinyMCE's "Paste From Word" feature (which doesn't seem to work that well anyway).

Anyone know of a library/class/function that would take care of this for me? It must be a common problem, though I can't find anything definitive. I've been thinking recently that a series of brute-force regexes looking for MS-specific patterns might do the trick, but I don't want to re-write something that may already be available unless I must.

Also, fixing of curly quotes, em-dashes, etc would be good. I have my own stuff to do this now, but I'd really just like to find one MS-conversion filter to rule them all.

答:
In my case, this worked just fine:

```<code>$text = strip_tags($text, '<p><a><em><span>');
</code>```

Rather than trying to pull out stuff you don't want such as embedded word xml, you can just specify you're allowed tags.

Title: PHP to clean-up pasted Microsoft input

Body:
In my case, this worked just fine:

$text = strip_tags($text, '<p><a><em><span>');

Rather than trying to pull out stuff you don't want such as embedded word xml, you can just specify you're allowed tags.


问:
Writing the summary function for a model
I am trying to write the summary method for a new model function similar to lm model which i have developed. I would like to know as to how to display the call: in summary.

For example:

```<code>#res <- summary(mod)

# res$call
# lm(formula = y ~ x, data = pop_data[[1]])
</code>```

how to write the code to display call text? As above?

答:
Does this help you at all?</p>

```<code>lmcall <- function(formula, data){
  return(as.call(c(quote(lmcall), formula = formula, data = substitute(data))))
}

lmcall(cars$speed ~ cars$dist, data = cars)
#lmcall(formula = cars$speed ~ cars$dist, data = cars)
</code>```

Body:
I am trying to write the summary method for a new model function similar to lm model which i have developed. I would like to know as to how to display the call: in summary.

For example:

#res <- summary(mod)

# res$call
# lm(formula = y ~ x, data = pop_data[[1]])

how to write the code to display call text? As above?

Body:
Does this help you at all?

lmcall <- function(formula, data){
  return(as.call(c(quote(lmcall), formula = formula, data = substitute(data))))
}

lmcall(cars$speed ~ cars$dist, data = cars)
#lmcall(formula = cars$speed ~ cars$dist, data = cars)


问:
TensorFlow: Difference between EVAL and INFER
What is the difference between tf.contrib.learn.ModeKeys.EVAL and tf.contrib.learn.ModeKeys.INFER?

Also, how exactly are these used with the tf.contrib.learn.Estimator class object?

I am attempting to follow this tutorial: https://www.tensorflow.org/tutorials/layers, and I am struggling to understand the purpose of each of these "modes".

API documentation: https://www.tensorflow.org/api_docs/python/tf/contrib/learn/ModeKeys

答: It seems that EVAL differs from INFER in that EVAL is the mode used when model is evaluated during training, where INFER is used when a model is already trained and is used purely to make predictions. For example, in the tutorial you linked, the loss function op is included in the graph when model is used in EVAL or TRAIN mode, but not in INFER mode. Because knowing the value of the loss function when doing training progress evaluation (EVAL mode) is useful, but when you are purely interested in generating predictions (INFER mode) you don't need it.</p>


答:
You can use a Proxy for the array to observe the changes on it. In set, you can check the length of the array and trigger an action:

var lengthToTriggerFunction = 3;
var functionToBeTriggered = function() {
  console.log('Triggered!');
}

var changeHandler = {
  set: function(target, property, value, receiver) {
    target[property] = value;

    if (property === 'length' && target.length === lengthToTriggerFunction) {
       functionToBeTriggered();
    }

    return true;
  }
};

var array = new Proxy([], changeHandler);

array.push(1);
console.log(array.length);

array.push(2);
console.log(array.length);

array.push(3); // function is triggered here
console.log(array.length);

array.push(4);
console.log(array.length);```

Title: Execute only when array's length reaches X elements

Body:
I was wondering if it's possible to execute function only when arrays length is long enough.

I have a setInterval function to repeatedly fetch info from interweb, if a new user appears it will send his id to an array, and I want to execute different function only when this array's length reaches a specific amount.

Thanks in advance!


问:
Outlook Calendar Sync Issue 80070005
I have a SharePoint 2013 calendar that needs unique permissions on it, allowing people who have NOT been granted access to the parent site access to this calendar.  I've broken inheritance on this calendar and granted Read permissions on the calendar to these non site members.  They are able to browse the calendar via Internet Explorer, but if they click the Connect to Outlook button in SharePoint, Outlook prompts for a username/password that can never authenticate.  The calendar is added to Outlook, but any attempts to sync results in an error message:

'Task SharePoint reported error (0x80070005): You do not have permission to view theis SharePoint List... HTTP 401'

I've tried the conventional wisdom of deleting the calendar from Outlook and adding again, but always get the same result.  The only thing that seems to fix the issue is to add the external user to the calendar's parent site as part of the members group.  This gives that external user access to other content in the parent site we want to restrict, so this is not an option.

Any suggestions on how to resolve this issue?

Tks

答: Finally got it figured out.  There are a couple of folders like Site Collection Images and Style Folders that have unique permissions under the calendar parent site.  My external users were not members of these libraries.  As soon as I added them, I was able to add my SharePoint calendar to Outlook.</p>

Title: Outlook Calendar Sync Issue 80070005


问:
WebAPI - multiple GET methods with no parameters
I've been able create whatever endpoints I've wanted as long as the parameters for each one is different:

```<code>public IHttpActionResult GetFightersByWeightClass(string WeightClass)
...

public IHttpActionResult GetFighterByExactName(string NameEquals)
...
</code>```

But as soon as I try to create two differently named functions that share the same parameters I am unable to use both. I have two endpoints that don't require parameters, shown below:

```<code>public class FighterController : ApiController
{
    /// <summary>
    /// Gets all fighters.
    /// </summary>
    /// <returns></returns>
    [ActionName("GetAllFighters")]
    public IEnumerable<Fighter> GetAllFighters()
    {
        return allFighters;
    }

    /// <summary>
    /// Gets all fighters that are currently undefeated.
    /// </summary>
    /// <returns></returns>
    [ActionName("GetAllUndefeatedFighters")]
    public IHttpActionResult GetAllUndefeatedFighters()
    {
        var results = allFighters.FindAll(f => f.MMARecord.Losses == 0);

        if (results == null)
        {
            return NotFound();
        }

        return Ok(results);
    }
}
</code>```

Both URLs return this:

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nGetAllFighters on type MMAAPI.Controllers.FighterController\r\nGetAllUndefeatedFighters on type MMAAPI.Controllers.FighterController","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

Not sure why this is happening they each have their own unique action and function name, so I thought they would work like this...:

http://localhost:55865/api/fighter/GetAllUndefeatedFighters -- Just shows fighters with zero losses

http://localhost:55865/api/fighter/ -- shows all fighters

...but instead neither works. If I remove one of them, they other works and vice versa. So they aren't working when they are both active. Any idea why?

答:
A combination of the two other answers works well for me. (I've changed the names slightly from the question.)

```<code>[RoutePrefix("api/v1/fighters")]
public class FighterController : ApiController
{
    /// <summary>
    /// Gets all fighters.
    /// </summary>
    /// <returns>An enumeration of fighters.</returns>
    [Route(""), HttpGet]
    public IEnumerable<Fighter> GetAllFighters()
    {
        return allFighters;
    }

    /// <summary>
    /// Gets all fighters that are currently undefeated.
    /// </summary>
    /// <returns>An enumeration of fighters.</returns>
    [Route("undefeated"), HttpGet]
    public IEnumerable<Fighter> GetAllUndefeatedFighters()
    {
        return allFighters.FindAll(f => f.MMARecord.Losses == 0);
    }
}
</code>```

As such, your endpoints would be:

GET /api/v1/fighters

GET /api/v1/fighters/undefeated

Body:
I've been able create whatever endpoints I've wanted as long as the parameters for each one is different:

public IHttpActionResult GetFightersByWeightClass(string WeightClass)
...

public IHttpActionResult GetFighterByExactName(string NameEquals)
...

But as soon as I try to create two differently named functions that share the same parameters I am unable to use both. I have two endpoints that don't require parameters, shown below:

public class FighterController : ApiController
{
    ///
    /// Gets all fighters.
    ///
    /// <returns></returns>
    [ActionName("GetAllFighters")]
    public IEnumerable<Fighter> GetAllFighters()
    {
        return allFighters;
    }

    ///
    /// Gets all fighters that are currently undefeated.
    ///
    /// <returns></returns>
    [ActionName("GetAllUndefeatedFighters")]
    public IHttpActionResult GetAllUndefeatedFighters()
    {
        var results = allFighters.FindAll(f => f.MMARecord.Losses == 0);

        if (results == null)
        {
            return NotFound();
        }

        return Ok(results);
    }
}

Both URLs return this:

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nGetAllFighters on type MMAAPI.Controllers.FighterController\r\nGetAllUndefeatedFighters on type MMAAPI.Controllers.FighterController","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

Not sure why this is happening they each have their own unique action and function name, so I thought they would work like this...:

http://localhost:55865/api/fighter/GetAllUndefeatedFighters -- Just shows fighters with zero losses

http://localhost:55865/api/fighter/ -- shows all fighters

...but instead neither works. If I remove one of them, they other works and vice versa. So they aren't working when they are both active. Any idea why?

Body:
A combination of the two other answers works well for me. (I've changed the names slightly from the question.)

[RoutePrefix("api/v1/fighters")]
public class FighterController : ApiController
{
    /// <summary>
    /// Gets all fighters.
    /// </summary>
    /// <returns>An enumeration of fighters.</returns>
    [Route(""), HttpGet]
    public IEnumerable<Fighter> GetAllFighters()
    {
        return allFighters;
    }

    /// <summary>
    /// Gets all fighters that are currently undefeated.
    /// </summary>
    /// <returns>An enumeration of fighters.</returns>
    [Route("undefeated"), HttpGet]
    public IEnumerable<Fighter> GetAllUndefeatedFighters()
    {
        return allFighters.FindAll(f => f.MMARecord.Losses == 0);
    }
}

As such, your endpoints would be:

GET /api/v1/fighters

GET /api/v1/fighters/undefeated