问:
Name of this type of inheritance semantic
```<code>public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}
</code>```

(Please don't change code. It is working and shows the problem.)

The error is

```<code>Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)
</code>```

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

答:
Encapsulation.

http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Basically you control who has access to the members via accessors ("setters" and "getters"). How the underlying data is layed out remains hidden to the user.

Think of this:

If you would like to rename your X variable (for whatever reasons) in your base class, but there exists 100 classes derived from that base class who accessed it directly.

You would break that code.

```<code>class derived
{
  void DoSomething() { x += 1; } // x renamed, doesn't compile anymore
}
</code>```

Now, with encapsulation, since x cannot accessed directly, we got accessors:

```<code>class derived
{
  void DoSomething() { SetX(GetX() + 1); } // No prob!
}
</code>```

Body:
public class _base
{
    protected int x = 5;
    protected int GetX(_base b) { return b.x; }
}

public class _derived : _base
{
    public int Foo()
    {
        var b = new _base();
        //return b.x;  // <-- this would be illegal
        return GetX(b); // <-- This works and does exactly the same as the line above
    }
}

(Please don't change code. It is working and shows the problem.)

The error is

Cannot access protected member '_base.x' via a qualifier of type '_base'; the qualifier must be of type '_derived' (or derived from it)

Note that because b is of type _base and we are not in base we cannot access it's protected members. I imagine the reason is because _base might be of some other derived type and hence it is not protecting the code but that's not the point. What I'm doing is creating a work around for the above problem using the extra protected methods. This gives me the behavior I want and the protection I want. I wish there were a keyword that allows this kinda access but there isn't. What I'm interested in is if this "pattern" has a name.

(I'm using protected because internal allows anyone in the same assembly access)

Body:
Encapsulation.

http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Basically you control who has access to the members via accessors ("setters" and "getters"). How the underlying data is layed out remains hidden to the user.

Think of this:

If you would like to rename your X variable (for whatever reasons) in your base class, but there exists 100 classes derived from that base class who accessed it directly.

You would break that code.

class derived
{
  void DoSomething() { x += 1; } // x renamed, doesn't compile anymore
}

Now, with encapsulation, since x cannot accessed directly, we got accessors:

class derived
{
  void DoSomething() { SetX(GetX() + 1); } // No prob!
}


来源: stackexchange

问:
Color Variables but Alpha Separate
I stored all basic colors in variables for example:

```<code>WHITE = (255, 255, 255)
</code>```

I then use those variables to draw ellipes, but i want different alpha values for those ellipses. I dont want to create variables for all the different alpha values. I tried doing

```<code>pygame.draw.ellipse(self.image, (WHITE, 50), self.rect)
</code>```

But that does not work sadly. Any Solution?

答:
Tuples can be concatenated by addition:

```<code>pygame.draw.ellipse(self.image, WHITE + (50,), self.rect)
</code>```

For example,

```<code>>>> (255, 255, 255) + (50,)
(255, 255, 255, 50)
</code>```

Lists, by the way, behave analogously:

```<code>>>> [255, 255, 255] + [50]
[255, 255, 255, 50]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Color Variables but Alpha Separate

Body:
I stored all basic colors in variables for example:

WHITE = (255, 255, 255)

I then use those variables to draw ellipes, but i want different alpha values for those ellipses. I dont want to create variables for all the different alpha values. I tried doing

pygame.draw.ellipse(self.image, (WHITE, 50), self.rect)

But that does not work sadly. Any Solution?

Body:
Tuples can be concatenated by addition:

pygame.draw.ellipse(self.image, WHITE + (50,), self.rect)

For example,

>>> (255, 255, 255) + (50,)
(255, 255, 255, 50)

Lists, by the way, behave analogously:

>>> [255, 255, 255] + [50]
[255, 255, 255, 50]


问:
Is there a better way to implement the selu activation function for the gpu?
So I'm trying to implement the selu activation in theano from this paper.
My current implementation is:

```<code>def selu(x):
    alpha = 1.6733
    lambda_ = 1.0507
    inds = x <= 0
    selu = (alpha * theano.theano.tensor.exp(x) - alpha)
    x = theano.tensor.set_subtensor(x[inds.nonzero()],selu[inds.nonzero()])
    x = lambda_ * x
    return x
</code>```

Unfortunately I "cannot" use the popular framework Keras so I've gone about trying to implement it myself.
I am not very familiar with techniques needed to make a function gpu friendly and thus I am reaching out for help. Thanks!

答:
It turns a much much faster solution is the following:</p>

```<code>import theano
def selu(x):
    alpha = 1.6733
    lambda_ = 1.0507
    return lambda_ * theano.tensor.nnet.elu(x, alpha=alpha)
</code>```

Body:
So I'm trying to implement the selu activation in theano from this paper.
My current implementation is:

def selu(x):
    alpha = 1.6733
    lambda_ = 1.0507
    inds = x <= 0
    selu = (alpha * theano.theano.tensor.exp(x) - alpha)
    x = theano.tensor.set_subtensor(x[inds.nonzero()],selu[inds.nonzero()])
    x = lambda_ * x
    return x

Unfortunately I "cannot" use the popular framework Keras so I've gone about trying to implement it myself.
I am not very familiar with techniques needed to make a function gpu friendly and thus I am reaching out for help. Thanks!

Body:
It turns a much much faster solution is the following:

import theano
def selu(x):
    alpha = 1.6733
    lambda_ = 1.0507
    return lambda_ * theano.tensor.nnet.elu(x, alpha=alpha)


问:
How to get only first property from JSON file?
I am trying to get only the selected item from this JSON file:

```<code>{
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}
</code>```

For example i need first question and answer to be shown in first
, second question and answer in second
 and the third q & a in the third
.

I am using AJAX to access the file:

```<code>$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $(data.faqs).each(function(index, value) {
        $('#firstQuestion').text("Q: " + value.question);
        $('#firstAnswer').text(value.answer);
        $('#secondQuestion').text("Q: " + value.question);
        $('#secondAnswer').text(value.answer);
        $('#thirdQuestion').text("Q: " + value.question);
        $('#thirdAnswer').text(value.answer);
      });
    }
  });
</code>```

And now I got some result that loops through all the items and gives me the last one but as I already said earlier I need the first question and answer at the first
 and so on.

Can you provide me with some ideas or a solution? I am trying to solve this for about 4 hours now and I have nothing. Any help is greatly appreciated.

答:
This is what you need something like...

var array = {
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}

var faqs = array.faqs;

for(var i = 0; i< faqs.length; i++){
  var div = document.createElement("div");
  div.innerHTML = "Q : "+ faqs[i].question + " Ans: "+faqs[i].answer;
  document.getElementById("main").appendChild(div);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

For your use-case, just place the javascript code in your success call back and var faqs = data.faqs and that should work.

Body:
I am trying to get only the selected item from this JSON file:

{
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}

For example i need first question and answer to be shown in first
, second question and answer in second
 and the third q & a in the third
.

I am using AJAX to access the file:

$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $(data.faqs).each(function(index, value) {
        $('#firstQuestion').text("Q: " + value.question);
        $('#firstAnswer').text(value.answer);
        $('#secondQuestion').text("Q: " + value.question);
        $('#secondAnswer').text(value.answer);
        $('#thirdQuestion').text("Q: " + value.question);
        $('#thirdAnswer').text(value.answer);
      });
    }
  });

And now I got some result that loops through all the items and gives me the last one but as I already said earlier I need the first question and answer at the first
 and so on.

Can you provide me with some ideas or a solution? I am trying to solve this for about 4 hours now and I have nothing. Any help is greatly appreciated.

Body:
This is what you need something like...

var array = {
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}

var faqs = array.faqs;

for(var i = 0; i< faqs.length; i++){
  var div = document.createElement("div");
  div.innerHTML = "Q : "+ faqs[i].question + " Ans: "+faqs[i].answer;
  document.getElementById("main").appendChild(div);
}

<div id="main"></div>

For your use-case, just place the javascript code in your success call back and var faqs = data.faqs and that should work.


问:
Yii2: How to print a gridview?
I am using yii2-export library to print a table.

The table has 600 rows but the user only wants to print the first 20 rows.

The user exports to a PDF file (so then he can print it) but it's big so the PHP server doesn't respond.

I tried printing with the browser (CTRL+P) but it prints buttons and also it so ugly.

答:
Please check batchSize parameter of Export Menu or add pagination and limit filter to dataprovider.

Yii2 dataProvider

Title: Yii2: How to print a gridview?


问:
separate first word in a string in python re
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

```<code>for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)
</code>```

Here are some examples of the strings:

```<code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
</code>```

what I need is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,
</code>```

what I am getting is:

```<code>Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a
</code>```

答:
Code

Option 1

See regex in use here

```<code>(\w+?(?=[(_])).*?_(\w+)
</code>```

Replacement

```<code>$1 $2
</code>```

Option 2

See regex in use here

```<code>([^_\W]+).*?[)_](\w+)
</code>```

Replacement

```<code>$1 $2
</code>```

Results

Input

```<code>Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
Aphis(Aphis)test_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a_test,
</code>```

Output

Option 1

```<code>Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,
</code>```

Option 2

```<code>Aphis _asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis test_asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,
</code>```

Explanation

Option 1

(\w+?(?=[(_])) Capture the following into capture group 1

\w+? Match one or more word characters, but as few as possible

(?=[(_]) Positive lookahead ensuring what follows matches a character in the set (_

.*? Match any character any number of times, but as few as possible

_ Match the underscore character _ literally

(\w+) Capture any word character one or more times into capture group 2

Option 2

([^_\W]+) Capture one or more word characters except _ into capture group 1

.*? Match any character any number of times, but as few as possible

[)_] Match either ) or _ literally

(\w+) Capture one or more word characters into capture group 2

Body:
I need to separate strings into two groups; the first word and the second word or group of words. The words are separated by an underscore and when I use my current code, if there are more than one underscores, it only separates off the last. Here is the code I currently have:

for record in reader:
s = record['trial']
patternsubgen = re.compile(r'(\w+)\(\w+\)\_(\w+)')
source = "Footit"
if patternsubgen.search(s):
    resultsubgen = patternsubgen.search(s)
    genussubgen = resultsubgen.group(1)
    speciessubgen = resultsubgen.group(2)
    subgen = '%s %s' % (genussubgen, speciessubgen)
    #print(subgen)
else:
    pattern = re.compile(r'(\w+)\_(\w+)')
    if pattern.search(s):
        result = pattern.search(s)
        genus = result.group(1)
        species = result.group(2)
        new = '%s %s' % (genus, species)
        print(new)

Here are some examples of the strings:

Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,

what I need is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia canadensis_1a,

what I am getting is:

Aphis asclepiadis,
Cinara 011,
Clydesmithia_canadensis 1a

Body:
Code

Option 1

See regex in use here

(\w+?(?=[(_])).*?_(\w+)

Replacement

$1 $2

Option 2

See regex in use here

([^_\W]+).*?[)_](\w+)

Replacement

$1 $2

Results

Input

Aphis(Aphis)_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a,
Aphis(Aphis)test_asclepiadis, Cinara_011, Clydesmithia_canadensis_1a_test,

Output

Option 1

Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,

Option 2

Aphis _asclepiadis, Cinara 011, Clydesmithia canadensis_1a,
Aphis test_asclepiadis, Cinara 011, Clydesmithia canadensis_1a_test,

Explanation

Option 1

(\w+?(?=[(_])) Capture the following into capture group 1

\w+? Match one or more word characters, but as few as possible

(?=[(_]) Positive lookahead ensuring what follows matches a character in the set (_

.*? Match any character any number of times, but as few as possible

_ Match the underscore character _ literally

(\w+) Capture any word character one or more times into capture group 2

Option 2

([^_\W]+) Capture one or more word characters except _ into capture group 1

.*? Match any character any number of times, but as few as possible

[)_] Match either ) or _ literally

(\w+) Capture one or more word characters into capture group 2


问:
How to put a Floating action button on all screens in Android
I have a requirement to put a floating action button on all screens of the application. I don't define all layout files, instead there any way I can generate dynamically and visible on all screens of the application. </p>

答:
Yes , it's possible.
You could create one activity and multiple fragments with the current layout:

```<code>FrameLayout
-Framelayout container
-Your floating button
</code>```

Then replace fragments in your container layout :).

You have to handle the floating button events in your activity.

Body:
Yes , it's possible.
You could create one activity and multiple fragments with the current layout:

FrameLayout
-Framelayout container
-Your floating button

Then replace fragments in your container layout :).

You have to handle the floating button events in your activity.


问:
Stata Scatter Sort by Y-Axis
I want to plot the average weight (y-axis) by make (x-axis) and sort it so the heaviest make is the leftmost on the x-axis and the lightest is the rightmost on the x-axis. I thought the sort option would work.

```<code>sysuse auto, clear
keep if foreign
sort mpg
gen obsno = _n
scatter weight obsno, xla(1/22) sort(weight)
</code>```

答:
The sort() option is allowed with scatter because one of the possibilities of scatter is to connect points with a line. But it refers only to the order in which points are connected. The default is to connect points in the current sort order of the dataset. In practice the most common example is that observations are in some time order or follow some other sequence but even then scatter would respect the order of a time or other variable only if the data were in the same order -- unless, to complete the circle, a sort order were specified with this option.

You are not asking for any connnection. In that circumstance, sort() remains legal but it is ignored as of no relevance to what you're asking for.

There is no circumstance in which sort() has another effect with scatter and it will not change either axis variable to something else.

A way to get what I think you want is with the undocumented vertical option of graph dot. Some of the small choices here are just my personal idea of what looks good. For example, I have found that the default dotted grid lines often copy poorly to other software, so I use thin light grey continuous lines as a grid.

```<code>sysuse auto, clear
keep if foreign
sort mpg
gen obsno = _n
graph dot (asis) weight, over(obsno, sort(1) descending) vertical ///
linetype(line) lines(lcolor(gs12) lw(vthin)) yla(, ang(h))
</code>```

It's perfectly possible to get a similar graph using scatter, just more work as you have to arrange that the observation numbers become the value labels of a variable defining the sort order.

See also quantile and qplot (Stata Journal).

Title: Stata Scatter Sort by Y-Axis

Body:
I want to plot the average weight (y-axis) by make (x-axis) and sort it so the heaviest make is the leftmost on the x-axis and the lightest is the rightmost on the x-axis. I thought the sort option would work.

sysuse auto, clear
keep if foreign
sort mpg
gen obsno = _n
scatter weight obsno, xla(1/22) sort(weight)

Body:
The sort() option is allowed with scatter because one of the possibilities of scatter is to connect points with a line. But it refers only to the order in which points are connected. The default is to connect points in the current sort order of the dataset. In practice the most common example is that observations are in some time order or follow some other sequence but even then scatter would respect the order of a time or other variable only if the data were in the same order -- unless, to complete the circle, a sort order were specified with this option.

You are not asking for any connnection. In that circumstance, sort() remains legal but it is ignored as of no relevance to what you're asking for.

There is no circumstance in which sort() has another effect with scatter and it will not change either axis variable to something else.

A way to get what I think you want is with the undocumented vertical option of graph dot. Some of the small choices here are just my personal idea of what looks good. For example, I have found that the default dotted grid lines often copy poorly to other software, so I use thin light grey continuous lines as a grid.

sysuse auto, clear
keep if foreign
sort mpg
gen obsno = _n
graph dot (asis) weight, over(obsno, sort(1) descending) vertical ///
linetype(line) lines(lcolor(gs12) lw(vthin)) yla(, ang(h))

It's perfectly possible to get a similar graph using scatter, just more work as you have to arrange that the observation numbers become the value labels of a variable defining the sort order.

See also quantile and qplot (Stata Journal).


问:
Why aren't there quotes in sys.argv when they were used at the command line?
Is this a bug?

```<code>#!/usr/bin/env python3.6
# filename: tmp.py
import sys

print(sys.argv)
</code>```

Invoked:

```<code>python tmp.py find . -name '*.py'
</code>```

Actual output:

```<code>['tmp.py', 'find', '.', '-name', '*.py']
</code>```

Expected output:

```<code>['tmp.py', 'find', '.', '-name', "'*.py'"]
</code>```

Note the lack of quotations within the actual output.

答:
no, because your shell removes the quotes before passing the argument to python (else it would expand the *.py wildcard)

To get what you want you'd need:

```<code>python tmp.py find -name "'*.py'"
</code>```

Note that this behaviour is shell dependent. On windows, since single quotes have no particular meaning, passing '*.py', you would get:

```<code>['tmp.py', 'find', '.', '-name', "'*.py'"]
</code>```

Also note that quote-protected wildcards have no real interest on the python side, since you'd need to strip the quotes to be able to evaluate them with glob.glob

Body:
Is this a bug?

#!/usr/bin/env python3.6
# filename: tmp.py
import sys

print(sys.argv)

Invoked:

python tmp.py find . -name '*.py'

Actual output:

['tmp.py', 'find', '.', '-name', '*.py']

Expected output:

['tmp.py', 'find', '.', '-name', "'*.py'"]

Note the lack of quotations within the actual output.

Body:
no, because your shell removes the quotes before passing the argument to python (else it would expand the *.py wildcard)

To get what you want you'd need:

python tmp.py find -name "'*.py'"

Note that this behaviour is shell dependent. On windows, since single quotes have no particular meaning, passing '*.py', you would get:

['tmp.py', 'find', '.', '-name', "'*.py'"]

Also note that quote-protected wildcards have no real interest on the python side, since you'd need to strip the quotes to be able to evaluate them with glob.glob


问:
R: Transforming a dataset with the variables "country" and "x" to an adjacency matrix by recoding x
suppose I have following data set CL in R:

```<code>country    x
USA        7
Canada     7
Bahamas    6
Cuba       1
Haiti      2
</code>```

Now, what I intend to do is to create an adjacency matrix where the countries are the nodes, and the strength of the ties are the absolute difference of the values of x. For example, the tie between the Bahamas (x=6) and Cuba (x=1) would have a strength of 6-1=5.

Thus, here the network matrix would look like this:

```<code>country USA Canada Bahamas Cuba Haiti
USA      0    0       -1    -6    -5
Canada   0    0       -1    -6    -5
Bahamas  1    1        0    -5    -4
Cuba     6    6        5     0     4
Haiti    5    5        4    -1     0
</code>```

I have been struggling with this problem for quite a long time, and I just can't come to a decent approach to solve this. My actual data set consists of 150 countries, so it would be really troublesome to do this in Excel. So, does anyone have, how to do this in R? Thank you very much!

Here the R code for reproduction:

```<code>country<- c("USA", "Canada", "Bahamas", "Cuba", "Haiti")
x<- c(7,7,6,1,2)

CL<- data.frame(country=country, x=x)
</code>```

答:
```<code>grid <- expand.grid(x, x)
grid$strength <- grid$Var1 - grid$Var2
mat <- matrix(grid$strength, nrow=5, ncol=5, byrow=TRUE)
</code>```

Body:
suppose I have following data set CL in R:

country    x
USA        7
Canada     7
Bahamas    6
Cuba       1
Haiti      2

Now, what I intend to do is to create an adjacency matrix where the countries are the nodes, and the strength of the ties are the absolute difference of the values of x. For example, the tie between the Bahamas (x=6) and Cuba (x=1) would have a strength of 6-1=5.

Thus, here the network matrix would look like this:

country USA Canada Bahamas Cuba Haiti
USA      0    0       -1    -6    -5
Canada   0    0       -1    -6    -5
Bahamas  1    1        0    -5    -4
Cuba     6    6        5     0     4
Haiti    5    5        4    -1     0

I have been struggling with this problem for quite a long time, and I just can't come to a decent approach to solve this. My actual data set consists of 150 countries, so it would be really troublesome to do this in Excel. So, does anyone have, how to do this in R? Thank you very much!

Here the R code for reproduction:

country<- c("USA", "Canada", "Bahamas", "Cuba", "Haiti")
x<- c(7,7,6,1,2)

CL<- data.frame(country=country, x=x)


问:
Couldn't access Kubernetes dashboard on Google Cloud
I am following the instructions as given here.

I used the following command to get a running cluster, in gcloud console I typed: curl -sS https://get.k8s.io | bash as described in the link, after that, I ran the command kubectl cluster-info from that I got:

```<code>kubernetes-dashboard is running at https://35.188.109.36/api/v1/proxy/namespaces/kube-
system/services/kubernetes-dashboard
</code>```

but when I go to that url from firefox, the message that comes is:

```<code>User "system:anonymous" cannot proxy services in the namespace
"kube-system".: "No policy matched."
</code>```

Expected behavior: Should ask for an admin name and password to connect to the dashboard.

答:
Is there a reason why you did not use GKE (Google Kubernetes Engine) which provides the dashboard add-on installed out of the box?

In your case, simply:

the kubernetes-dashboard addon might not be installed (but logs say so, so I think this is not the problem)

network configuration that makes kubectl proxy work might not be there

the curl .. | sh script you used probably did not configure the authentication properly.

I recommend using GKE as this works out of the box. You can find documentation here: https://cloud.google.com/kubernetes-engine/docs/oss-ui

If you still want to use GCE, I recommend running kubectl proxy on your workstation (not your kubernetes nodes) and visiting http://127.0.0.1:8001/ui on your browser to see if it works.

If you get an error about not having enough permissions, you might be using a Kubernetes version new enough that enforces RBAC policies on pods like dashboard which access the API. You can grant those permissions by running:

```<code>kubectl create clusterrolebinding add-on-cluster-admin  \
  --clusterrole=cluster-admin  \
  --serviceaccount=kube-system:default
</code>```

I also recommend trying out GKE UI in Google Cloud Console: https://console.cloud.google.com/kubernetes

ContentLicense: CC BY-SA 4.0

Body:
I am following the instructions as given here.

I used the following command to get a running cluster, in gcloud console I typed: curl -sS https://get.k8s.io | bash as described in the link, after that, I ran the command kubectl cluster-info from that I got:

kubernetes-dashboard is running at https://35.188.109.36/api/v1/proxy/namespaces/kube-
system/services/kubernetes-dashboard

but when I go to that url from firefox, the message that comes is:

User "system:anonymous" cannot proxy services in the namespace
"kube-system".: "No policy matched."

Expected behavior: Should ask for an admin name and password to connect to the dashboard.

Body:
Is there a reason why you did not use GKE (Google Kubernetes Engine) which provides the dashboard add-on installed out of the box?

In your case, simply:

the kubernetes-dashboard addon might not be installed (but logs say so, so I think this is not the problem)

network configuration that makes kubectl proxy work might not be there

the curl .. | sh script you used probably did not configure the authentication properly.

I recommend using GKE as this works out of the box. You can find documentation here: https://cloud.google.com/kubernetes-engine/docs/oss-ui

If you still want to use GCE, I recommend running kubectl proxy on your workstation (not your kubernetes nodes) and visiting http://127.0.0.1:8001/ui on your browser to see if it works.

If you get an error about not having enough permissions, you might be using a Kubernetes version new enough that enforces RBAC policies on pods like dashboard which access the API. You can grant those permissions by running:

kubectl create clusterrolebinding add-on-cluster-admin  \
  --clusterrole=cluster-admin  \
  --serviceaccount=kube-system:default

I also recommend trying out GKE UI in Google Cloud Console: https://console.cloud.google.com/kubernetes


问:
Error filtering template: Warning: getimagesize(): Filename cannot be empty in /vendor/magento/framework/Image/Adapter/AbstractAdapter.php on line 304

Error filtering template: Warning: getimagesize(): Filename cannot be
  empty in /vendor/magento/framework/Image/Adapter/AbstractAdapter.php
  on line 304

This issue is showing on live domain. In local and dev domain this issue is not coming.

Please help me!

Thanks

答:
there is an image that is corrupted
you should find and remove it to have this fixed </p>


问:
fread() run time is taking longer than reported speed
I am attempting to read a large file into R on an EC2 instance. However, I have been experiencing run times which are far longer than the amount of time reported by fread after reading in some of the data.

Below, for instance, I have the verbose=TRUE output of fread when reading in only the first row of data for my csv file. As you can see, the reported run time is much shorter than the actual run time. Do you have any idea why this is happening? Is there any way I will be able to speed up the process so it is more in line with the runtime that fread reports after reading in the data?

```<code>> start_time <- Sys.time()
> fread(file_name_1, nrows=1, verbose=TRUE)
Input contains no \n. Taking this to be a filename to open
File opened, filesize is 68.770914 GB.
Memory mapping ... ok
Detected eol as \n only (no \r afterwards), the UNIX and Mac standard.
Positioned on line 1 after skip or autostart
This line is the autostart and not blank so searching up for the last non-blank ... line 1
Detecting sep ... ','
Detected 55 columns. Longest stretch was from line 1 to line 30
Starting data input on line 1 (either column names or first row of data). First 10 characters: bank_num,b
All the fields on line 1 are character fields. Treating as the column names.
nrow set to nrows passed in (1)
Type codes (point  0): 1114434134111034444411333333333333333333333333333311111
Type codes: 1114434134111034444411333333333333333333333333333311111 (after applying colClasses and integer64)
Type codes: 1114434134111034444411333333333333333333333333333311111 (after applying drop or select (if supplied)
Allocating 55 column slots (55 - 0 dropped)
Read 1 rows and 55 (of 55) columns from 68.771 GB file in 00:00:27
Read 1 rows. Exactly what was estimated and allocated up front
  26.480s (100%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
   0.000s (  0%) Count rows (wc -l)
   0.000s (  0%) Column type detection (100 rows at 10 points)
   0.000s (  0%) Allocation of 1x55 result (xMB) in RAM
   0.000s (  0%) Reading data
   0.000s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.000s (  0%) Coercing data already read in type bumps (if any)
   0.000s (  0%) Changing na.strings to NA
  26.480s        Total
> end_time <- Sys.time()
> end_time - start_time
Time difference of 9.695263 mins
</code>```

答:
Please always state version numbers; e.g. output of sessionInfo(). But I can tell you're probably using the CRAN version.

Please always check NEWS before asking on Stack Overflow.

Item 3 (amongst many other fread improvements) :

Memory maps lazily; e.g. reading just the first 10 rows with nrow=10 is 12s down to 0.01s from cold for a 9GB file. Large files close to your RAM limit may work more reliably too. The progress meter will commence sooner and more consistently.

The latest version from dev can easily be tried with this install command . You wrote EC2, so presumably Linux but any Windows users can use the Windows.zip from dev with no tools needed.

Since you have a 68GB csv, you should definitely benefit greatly from data.table v1.10.5+.  Please update here how you get on with it.

Body:
I am attempting to read a large file into R on an EC2 instance. However, I have been experiencing run times which are far longer than the amount of time reported by fread after reading in some of the data.

Below, for instance, I have the verbose=TRUE output of fread when reading in only the first row of data for my csv file. As you can see, the reported run time is much shorter than the actual run time. Do you have any idea why this is happening? Is there any way I will be able to speed up the process so it is more in line with the runtime that fread reports after reading in the data?

> start_time <- Sys.time()
> fread(file_name_1, nrows=1, verbose=TRUE)
Input contains no \n. Taking this to be a filename to open
File opened, filesize is 68.770914 GB.
Memory mapping ... ok
Detected eol as \n only (no \r afterwards), the UNIX and Mac standard.
Positioned on line 1 after skip or autostart
This line is the autostart and not blank so searching up for the last non-blank ... line 1
Detecting sep ... ','
Detected 55 columns. Longest stretch was from line 1 to line 30
Starting data input on line 1 (either column names or first row of data). First 10 characters: bank_num,b
All the fields on line 1 are character fields. Treating as the column names.
nrow set to nrows passed in (1)
Type codes (point  0): 1114434134111034444411333333333333333333333333333311111
Type codes: 1114434134111034444411333333333333333333333333333311111 (after applying colClasses and integer64)
Type codes: 1114434134111034444411333333333333333333333333333311111 (after applying drop or select (if supplied)
Allocating 55 column slots (55 - 0 dropped)
Read 1 rows and 55 (of 55) columns from 68.771 GB file in 00:00:27
Read 1 rows. Exactly what was estimated and allocated up front
  26.480s (100%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
   0.000s (  0%) Count rows (wc -l)
   0.000s (  0%) Column type detection (100 rows at 10 points)
   0.000s (  0%) Allocation of 1x55 result (xMB) in RAM
   0.000s (  0%) Reading data
   0.000s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.000s (  0%) Coercing data already read in type bumps (if any)
   0.000s (  0%) Changing na.strings to NA
  26.480s        Total
> end_time <- Sys.time()
> end_time - start_time
Time difference of 9.695263 mins


问:
How to know if when using "on duplicate key update" a row was inserted or updated?
We have a database that gets updated everyday at midnight with a cronjob, we get new data from an external XML.

What we do is that we insert all the new content and in case there is a duplicated key we update that field.

```<code>INSERT INTO table (id, col1, col2, col3)
values (id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
ON DUPLICATE KEY UPDATE
col1 = VALUES (col1),
col2 = VALUES (col2),
col3 = VALUES (col3);
</code>```

What we want to know is which rows have actually been inserted, meaning we want to have a list of the new items. is there any query that might return the new inserts? Basically we will need to get all the new ID's and not the number of new insertions.

Thanks

答:
I can say How I did in PHP:

1) Simple query SELECT MAX(id) and remember it to $max_id from table before Insert On Duplicate.

2) Then during the update process collect ID of affected rows (no mater new or existed): $ids[] = mysql_insert_id();

3) Then $inserted_rows = max($ids)-$max_id;

4) Updated rows = count($ids_srt)-$inserted_rows

```<code>$max_id = mysql_query("SELECT MAX(id) from table");
$max_id = mysql_result($max_id, 0);

// !!! prepare here 'insert on duplicate' query in a cycle

$result=mysql_query($query);
$ids[] = mysql_insert_id();

// finish inserting and collecting affected ids and close cycle

$inserted_rows = max($ids)- $max_id;
$updated_rows = count($ids)- $inserted_rows
</code>```

Body:
We have a database that gets updated everyday at midnight with a cronjob, we get new data from an external XML.

What we do is that we insert all the new content and in case there is a duplicated key we update that field.

INSERT INTO table (id, col1, col2, col3)
values (id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
(id_value, val1, val2, val3),
ON DUPLICATE KEY UPDATE
col1 = VALUES (col1),
col2 = VALUES (col2),
col3 = VALUES (col3);

What we want to know is which rows have actually been inserted, meaning we want to have a list of the new items. is there any query that might return the new inserts? Basically we will need to get all the new ID's and not the number of new insertions.

Thanks

Body:
I can say How I did in PHP:

1) Simple query SELECT MAX(id) and remember it to $max_id from table before Insert On Duplicate.

2) Then during the update process collect ID of affected rows (no mater new or existed): $ids[] = mysql_insert_id();

3) Then $inserted_rows = max($ids)-$max_id;

4) Updated rows = count($ids_srt)-$inserted_rows

$max_id = mysql_query("SELECT MAX(id) from table");
$max_id = mysql_result($max_id, 0);

// !!! prepare here 'insert on duplicate' query in a cycle

$result=mysql_query($query);
$ids[] = mysql_insert_id();

// finish inserting and collecting affected ids and close cycle

$inserted_rows = max($ids)- $max_id;
$updated_rows = count($ids)- $inserted_rows


问:
Limit the amount of lines in a multi line asp.net textbox
On my asp.net web page I have a large multi line textbox where I want the user to be able to only fill in a maximum of 5 lines of text. (If the user were to press enter while on the 5th line it would simply not let him.)

The code I have for the textbox:

```<code><asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox1"
             name="TextBox1"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">

</asp:TextBox>
</code>```

I have tried it with the Rows property and several JavaScript functions, with no success.

Is this possible with an asp.net textbox or is there any other type of textbox I could use in this case?

Thanks.

答:
I don't think this is possible with the asp:TextBox without some extra work.  FYI, the "Rows" and "Columns" properties are only a display metrics and won't restrict the number of characters or carriage returns. The MaxLength property is also well documented to be disabled when using "multiline" with an asp:Textbox.

However, you do have a few options shown below.  Note: typically input is validated by length because you don't want it to exceed the field size in the database tables. Hopefully these examples will help.

1) Roll your own Javascript validator.
(this example is limited to validating length, not carriage returns, but you could customize further.)

```<code><asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox1"
             name="TextBox1"
             onkeypress="return EnforceFieldLengthMax(this,10)"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">
        </asp:TextBox>

<script language="javascript">
        function EnforceFieldLengthMax(txt, maxLen)
        {
            if (txt.value.length > (maxLen - 1))
            {
                return false;
            }
        }
    </script>
</code>```

2) Regular Expression validator
(Unfortunately, this won't fire until the control loses focus, so I don't think this one is what you're looking for, but here is an example just in case)**

```<code> <asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox2"
             name="TextBox2"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">
        </asp:TextBox>

<asp:Label AssociatedControlID="txtValidateMe"></asp:Label>

<asp:RegularExpressionValidator ID="TextBox2Validator"
                                ControlToValidate="TextBox2" ErrorMessage="Entry can't exceed 20 characters"
                                ValidationExpression="^[\s\S]{0,20}$" runat="server" Display="Dynamic"  SetFocusOnError="true" />
</code>```

3) Use the HTML TextArea object which does enforce MaxLength

```<code><textarea maxlength="50"></textarea>
</code>```

Body:
On my asp.net web page I have a large multi line textbox where I want the user to be able to only fill in a maximum of 5 lines of text. (If the user were to press enter while on the 5th line it would simply not let him.)

The code I have for the textbox:

<asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox1"
             name="TextBox1"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">

</asp:TextBox>

I have tried it with the Rows property and several JavaScript functions, with no success.

Is this possible with an asp.net textbox or is there any other type of textbox I could use in this case?

Thanks.

Body:
I don't think this is possible with the asp:TextBox without some extra work.  FYI, the "Rows" and "Columns" properties are only a display metrics and won't restrict the number of characters or carriage returns. The MaxLength property is also well documented to be disabled when using "multiline" with an asp:Textbox.

However, you do have a few options shown below.  Note: typically input is validated by length because you don't want it to exceed the field size in the database tables. Hopefully these examples will help.

1) Roll your own Javascript validator.
(this example is limited to validating length, not carriage returns, but you could customize further.)

<asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox1"
             name="TextBox1"
             onkeypress="return EnforceFieldLengthMax(this,10)"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">
        </asp:TextBox>

<script language="javascript">
        function EnforceFieldLengthMax(txt, maxLen)
        {
            if (txt.value.length > (maxLen - 1))
            {
                return false;
            }
        }
    </script>

2) Regular Expression validator
(Unfortunately, this won't fire until the control loses focus, so I don't think this one is what you're looking for, but here is an example just in case)**

 <asp:TextBox textmode="multiline"
             runat="server"
             ID="TextBox2"
             name="TextBox2"
             style="OVERFLOW:hidden; height:165px; width:95%; resize:none;">
        </asp:TextBox>

<asp:Label AssociatedControlID="txtValidateMe"></asp:Label>

<asp:RegularExpressionValidator ID="TextBox2Validator"
                                ControlToValidate="TextBox2" ErrorMessage="Entry can't exceed 20 characters"
                                ValidationExpression="^[\s\S]{0,20}$" runat="server" Display="Dynamic"  SetFocusOnError="true" />

3) Use the HTML TextArea object which does enforce MaxLength

<textarea maxlength="50"></textarea>


问:
When will objects allocated on a thread be freed after the thread completes?
in this code

```<code>    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();
</code>```

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?

答:
The simple answer is eventually: no sooner, no later.

You have no direct control over when garbage will be collected. Provided the instance has no more references to it, the garbage collector will clean it up at some point.

Body:
in this code

    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?


问:
How can I hide my JavaScript functions so that nobody can steal them?

Possible Duplicate:

  How to prevent your JavaScript code from being stolen, copied, and viewed ?

I have a user form that has a submit button. Once clicked, a certain JS function is called and the code does something. I want to hide this so that nobody can see it. What is the best way to do this? I am not using any JS libraries, it is just code that I wrote myself.

Thanks!

答:
Instead of using JavaScript, you could submit the form to the server, and run the same code using PHP or something. If you're manipulating something on the page based on what happens in the JS function, you could do the following:

When the form is submitted, cancel with JS (you're probably already doing this)

Get all the information from the form, do everything that you're comfortable doing on the client side

Make an AJAX call, sending the necessary data to the server, where your now-confidential function can run

Return whatever information you need to return back to the client and make whatever changes you need to make

ContentLicense: CC BY-SA 2.5


问:
Highlighting Text using javascript not working
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

```<code> <html>
<head>
  <script type="text/javascript" src="task2.js"></script>
  <style>
  #poem {
    padding: 10px;
    margin-bottom: 10px;
    color: blue;
    font-size: 1.25em;
    font-family: sans-serif;
    background-color: silver;
    border: 1px dashed black;
    width: 30%;
  }
  </style>
</head>
<body>
<div id="poem">
<h2> How Many, How Much  </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>

<button id="yellow">Click to Highlight </button>
</body>
</html>
</code>```

here is my external js file

```<code>window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}
</code>```

答:
This should work

```<code><script type="text/javascript">
    document.getElementById('some_id').onclick= function() {
        var p = this.parentNode.style;
        p.color = yellow;
    };
</script>
</code>```

Edit: Toggle button

```<code><script type="text/javascript">
        document.getElementById('some_id').onclick= function() {
            var p = this.parentNode.style;
            if (p.color = yellow) p.color = white;
            else p.color = yellow;
        };
    </script>
</code>```

Body:
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

 How Many, How Much

 by Shel Silverstein

 How many slams in an old screen door?

 Depends how loud you shut it.

 How many slices in a bread?

 Depends how thin you cut it.

 How much good inside a day?

 Depends how good you live 'em.

 How much love inside a friend?

 Depends how much you give 'em.

<button id="yellow">Click to Highlight </button>

here is my external js file

window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}

Body:
This should work

<script type="text/javascript">
    document.getElementById('some_id').onclick= function() {
        var p = this.parentNode.style;
        p.color = yellow;
    };
</script>

Edit: Toggle button

<script type="text/javascript">
        document.getElementById('some_id').onclick= function() {
            var p = this.parentNode.style;
            if (p.color = yellow) p.color = white;
            else p.color = yellow;
        };
    </script>


问:
How to achieve row level locking in cassandra
I have a Cassandra cluster setup like Node N1, Node N2 and Node N3

I have a user table, I need to write create a row level locking for it across the nodes in the cluster, So could you please guide me by answering the following questions?

1) What is the maximum level of locking possible in Cassandra?

2) What is lightweight transaction? How much it is possible to achieve row level locking?

3) Is there an alternate way to achieve the row level locking in Cassandra?

答:
There is no transactions in cassandra, there is no locking.  There is however light weight transactions.  They're not great, the performance is worse and there are alot of tradeoffs.

Depending on what the use case is for this lock you could do:

INSERT INTO User (userID, email)
VALUES (‘MyGuid’, ‘user@example.com’)
IF NOT EXISTS;

If the query returns an error/failure you would have to handle that, it won't just fail if someone inserts before you.  A failure also might mean that 1 of your nodes did get the write but not all of them.  LWT don't roll back.


问:
Ruby regex to match a space without a leading comma
How can I match a space without a leading comma?

My use case is I would like to split a string on space without a leading comma e.g. "id 10, 11"

Body:
You need a lookbehind regex:

 'id 10, 11'.split(/(?<=[^,])[ ]/)

Output:

=> ["id", "10, 11"]


问:
Add default value of datetime field in SQL Server to a timestamp
I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.

I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.

答:
This works for me...</p>

```<code>ALTER TABLE [accounts]
 ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
</code>```

Body:
This works for me...

ALTER TABLE [accounts]
 ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;


问:
How to update campaigns content with template in mailchimp
I want to use mailchimp to send mail when something happen automatically  , so i use mailchimp restful api to do this:

```<code>1.Create a campaign with api /campaigns
2.Update the campaign with api /campaigns/{campaign_id}/content
3.Send the campaign
</code>```

in this second step, i found the API /campaigns/{campaign_id}/content can update the campaign's content with plaintext or html easy with http body like this:

{"html": "
The HTML to use for the saved campaign<./p>"}

but i am not sure how to use a template to update the content.
In the API document(https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/content/#), if you want to use template update content, you need fill the template id and template sections, but how do i know the sections in a template?

I try to use the template api to get a template detail information, in the response, the section filed is empty array.

any suggestion? or give me example!

thank you guys

Regard to great developers

答:
Not sure if you ever found an answer, but I am struggling with this API too. The sections can be retrieve from the GetDefaultContent API which will return an MailChimp Response with a sections object. That object, in turn, will have all the sections that you have specified in your template by name and their default content.

I am still trying to figure out the updating part, myself, but hope this helps a bit.

Body:
I want to use mailchimp to send mail when something happen automatically  , so i use mailchimp restful api to do this:

1.Create a campaign with api /campaigns
2.Update the campaign with api /campaigns/{campaign_id}/content
3.Send the campaign

in this second step, i found the API /campaigns/{campaign_id}/content can update the campaign's content with plaintext or html easy with http body like this:

{"html": "
The HTML to use for the saved campaign<./p>"}

but i am not sure how to use a template to update the content.
In the API document(https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/content/#), if you want to use template update content, you need fill the template id and template sections, but how do i know the sections in a template?

I try to use the template api to get a template detail information, in the response, the section filed is empty array.

any suggestion? or give me example!

thank you guys

Regard to great developers


问:
Parsing Human Names and matching them in Ruby
I'm looking for a gem or project that would let me identify that two names are the same person.  For example

J.R. Smith == John R. Smith == John Smith == John Roy Smith == Johnny Smith

I think you get the idea.  I know nothing is going to be 100% accurate but I'd like to get something that at least handles the majority of cases.  I know that last one is probably going to need a database of nicknames.

答:
Something like:

1: Convert names to arrays:

```<code>irb> names.map!{|n|n.scan(/[^\s.]+\.?/)}
["J.", "R.", "Smith"]
["John", "R.", "Smith"]
["John", "Smith"]
["John", "Roy", "Smith"]
["Johnny", "Smith"]
</code>```

2: Some function of identity:

```<code>for a,b in names.combination(2)
    p [(a&b).size,a,b]
end
[2, ["J.", "R.", "Smith"], ["John", "R.", "Smith"]]
[1, ["J.", "R.", "Smith"], ["John", "Smith"]]
[1, ["J.", "R.", "Smith"], ["John", "Roy", "Smith"]]
[1, ["J.", "R.", "Smith"], ["Johnny", "Smith"]]
[2, ["John", "R.", "Smith"], ["John", "Smith"]]
[2, ["John", "R.", "Smith"], ["John", "Roy", "Smith"]]
[1, ["John", "R.", "Smith"], ["Johnny", "Smith"]]
[2, ["John", "Smith"], ["John", "Roy", "Smith"]]
[1, ["John", "Smith"], ["Johnny", "Smith"]]
[1, ["John", "Roy", "Smith"], ["Johnny", "Smith"]]
</code>```

Or instead of & you may use .permutation + .zip + .max to apply some custom function, which determines, are to parts of names identical.

UPD:

```<code>aim = 'Rob Bobbie Johnson'
candidates = [
    "Bob Robbie John",
    "Bobbie J. Roberto",
    "R.J.B.",
]

$synonyms = Hash[ [
    ["bob",["bobbie"]],
    ["rob",["robbie","roberto"]],
] ]

def prepare name
    name.scan(/[^\s.]+\.?/).map &:downcase
end

def mf a,b # magick function
    a.zip(b).map do |i,j|
        next 1 if i == j
        next 0.9 if $synonyms[i].to_a.include?(j) || $synonyms[j].to_a.include?(i)
        next 0.5 if i[/\.$/] && j.start_with?(i.chomp '.')
        next 0.5 if j[/\.$/] && i.start_with?(j.chomp '.')
        -10 # if some part of name appears to be different -
            # it's bad even if another two parts were good
    end.inject :+
end

for c in candidates
    results = prepare(c).permutation.map do |per|
        [mf(prepare(aim),per),per]
    end
    p [results.transpose.first.max,c]
end
</code>```

```<code>[-8.2, "Bob Robbie John"]  # 0.9 + 0.9 - 10 # Johnson != John # I think ..)
[2.4, "Bobbie J. Roberto"] # 1 + 0.9 + 0.5 # Rob == Roberto, Bobbie == Bobbie, Johnson ~~ J.
[1.5, "R.J.B."]            # 0.5 + 0.5 + 0.5
</code>```

Body:
Something like:

1: Convert names to arrays:

irb> names.map!{|n|n.scan(/[^\s.]+\.?/)}
["J.", "R.", "Smith"]
["John", "R.", "Smith"]
["John", "Smith"]
["John", "Roy", "Smith"]
["Johnny", "Smith"]

2: Some function of identity:

for a,b in names.combination(2)
    p [(a&b).size,a,b]
end
[2, ["J.", "R.", "Smith"], ["John", "R.", "Smith"]]
[1, ["J.", "R.", "Smith"], ["John", "Smith"]]
[1, ["J.", "R.", "Smith"], ["John", "Roy", "Smith"]]
[1, ["J.", "R.", "Smith"], ["Johnny", "Smith"]]
[2, ["John", "R.", "Smith"], ["John", "Smith"]]
[2, ["John", "R.", "Smith"], ["John", "Roy", "Smith"]]
[1, ["John", "R.", "Smith"], ["Johnny", "Smith"]]
[2, ["John", "Smith"], ["John", "Roy", "Smith"]]
[1, ["John", "Smith"], ["Johnny", "Smith"]]
[1, ["John", "Roy", "Smith"], ["Johnny", "Smith"]]

Or instead of & you may use .permutation + .zip + .max to apply some custom function, which determines, are to parts of names identical.

UPD:

aim = 'Rob Bobbie Johnson'
candidates = [
    "Bob Robbie John",
    "Bobbie J. Roberto",
    "R.J.B.",
]

$synonyms = Hash[ [
    ["bob",["bobbie"]],
    ["rob",["robbie","roberto"]],
] ]

def prepare name
    name.scan(/[^\s.]+\.?/).map &:downcase
end

def mf a,b # magick function
    a.zip(b).map do |i,j|
        next 1 if i == j
        next 0.9 if $synonyms[i].to_a.include?(j) || $synonyms[j].to_a.include?(i)
        next 0.5 if i[/\.$/] && j.start_with?(i.chomp '.')
        next 0.5 if j[/\.$/] && i.start_with?(j.chomp '.')
        -10 # if some part of name appears to be different -
            # it's bad even if another two parts were good
    end.inject :+
end

for c in candidates
    results = prepare(c).permutation.map do |per|
        [mf(prepare(aim),per),per]
    end
    p [results.transpose.first.max,c]
end

[-8.2, "Bob Robbie John"]  # 0.9 + 0.9 - 10 # Johnson != John # I think ..)
[2.4, "Bobbie J. Roberto"] # 1 + 0.9 + 0.5 # Rob == Roberto, Bobbie == Bobbie, Johnson ~~ J.
[1.5, "R.J.B."]            # 0.5 + 0.5 + 0.5


问:
Creating a Mongoose plugin that supports callbacks AND promises
I have a Mongoose plugin that currently only supports callbacks, I plan on possibly publishing it to npmjs, but I first wanted to make sure that it works just like the existing Mongoose functions/methods, which support callbacks and some built in promises, and you can also specify your own promise library.

I wanted to know what the best way was to implement the same functionality in my library, meaning how can I support both callbacks and promises? I found a similar SO thread, but thats specific to bluebird, which even though I like to use, Id like to not assume it will be used. (Also, that article looks like it might be out-dated, as I couldnt find nodeify in the bluebird api docs

I was thinking I could just do some basic logic to see if a function was provided as one of the parameters, if so, then execute the callback, if not, then return a promise... but im sure theres an easier way to do that.

Also, for the Promises, when I do return a promise, should I use the Promise thats inside the Mongoose object thats handed to the plugins? Meaning:

module.exports = Mongoose => {
    // Just verifying, should I use this?..
    const Promise = Mongoose.Promise

    return Mongoose.model( 'Foobar', new Mongoose.Schema({ /* ... */ }) )
}
```

<h2>Update</h2>

<p>Regarding the last question, about what Promise object to reference when returning promises, I tried using the <code>Mongoose.Promise</code> as stated above, code below:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = Mongoose => {
    const Promise = Mongoose.Promise
    const Schema = Mongoose.Schema

    const fooSchema = new Schema({
        name: Schema.Types.String
    })

    fooSchema.statics.blah = function( ) {
        // Return Mongoose.Promise
        return new Promise( ( res, rej ) => {
            res( 'test' )
        })
    }

    return Mongoose.model( 'Foobar', fooSchema )
}
</code>```

... Which resulted in the error:

```<code>/Users/me/project/node_modules/mongoose/lib/ES6Promise.js:21
  throw 'Can\'t use ES6 promise with mpromise style constructor';
  ^
Can't use ES6 promise with mpromise style constructor
</code>```

So I'm guessing thats not the right way to go... I thought it would be a better idea to return promises using the same promise library Mongoose has configured (Custom, or default..)

I tried to see how Mongoose does it by looking at the findOne function code, but I dont quite see how it returns a promise if theres no callback specified
P.S. Im using Mongoose 4.3.7

Update

Was just tinkering around, but would this be an acceptable method? Or is it bad practice

function tester(foo, cb){
    return new Promise( ( res, rej ) => {
        const result = 'You said ' + foo
        if( typeof cb === 'function' ){
            cb( null, result )
            res() // Is this needed?
        }
        else {
            res( result )
        }
    })
}

tester('foo', (err, data) => {
    if( err )
        console.log('ERROR!',err)
    else
        console.log('Result:',data)
})

tester('bar')
    .then( data => {
        console.log('Result:',data)
    })
    .catch( err => {
        console.log('ERROR!',err)
    })
```

答:
just do this

```<code>mongoose.Promise = global.Promise
</code>```

as simple as that

Body:
I have a Mongoose plugin that currently only supports callbacks, I plan on possibly publishing it to npmjs, but I first wanted to make sure that it works just like the existing Mongoose functions/methods, which support callbacks and some built in promises, and you can also specify your own promise library.

I wanted to know what the best way was to implement the same functionality in my library, meaning how can I support both callbacks and promises? I found a similar SO thread, but thats specific to bluebird, which even though I like to use, Id like to not assume it will be used. (Also, that article looks like it might be out-dated, as I couldnt find nodeify in the bluebird api docs

I was thinking I could just do some basic logic to see if a function was provided as one of the parameters, if so, then execute the callback, if not, then return a promise... but im sure theres an easier way to do that.

Also, for the Promises, when I do return a promise, should I use the Promise thats inside the Mongoose object thats handed to the plugins? Meaning:

module.exports = Mongoose => {
    // Just verifying, should I use this?..
    const Promise = Mongoose.Promise

    return Mongoose.model( 'Foobar', new Mongoose.Schema({ /* ... */ }) )
}

Update

Regarding the last question, about what Promise object to reference when returning promises, I tried using the Mongoose.Promise as stated above, code below:

module.exports = Mongoose => {
    const Promise = Mongoose.Promise
    const Schema = Mongoose.Schema

    const fooSchema = new Schema({
        name: Schema.Types.String
    })

    fooSchema.statics.blah = function( ) {
        // Return Mongoose.Promise
        return new Promise( ( res, rej ) => {
            res( 'test' )
        })
    }

    return Mongoose.model( 'Foobar', fooSchema )
}

... Which resulted in the error:

/Users/me/project/node_modules/mongoose/lib/ES6Promise.js:21
  throw 'Can\'t use ES6 promise with mpromise style constructor';
  ^
Can't use ES6 promise with mpromise style constructor

So I'm guessing thats not the right way to go... I thought it would be a better idea to return promises using the same promise library Mongoose has configured (Custom, or default..)

I tried to see how Mongoose does it by looking at the findOne function code, but I dont quite see how it returns a promise if theres no callback specified
P.S. Im using Mongoose 4.3.7

Update

Was just tinkering around, but would this be an acceptable method? Or is it bad practice

function tester(foo, cb){
    return new Promise( ( res, rej ) => {
        const result = 'You said ' + foo
        if( typeof cb === 'function' ){
            cb( null, result )
            res() // Is this needed?
        }
        else {
            res( result )
        }
    })
}

tester('foo', (err, data) => {
    if( err )
        console.log('ERROR!',err)
    else
        console.log('Result:',data)
})

tester('bar')
    .then( data => {
        console.log('Result:',data)
    })
    .catch( err => {
        console.log('ERROR!',err)
    })

Body:
just do this

mongoose.Promise = global.Promise

as simple as that


问:
How to get only first property from JSON file?
I am trying to get only the selected item from this JSON file:

```<code>{
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}
</code>```

For example i need first question and answer to be shown in first
, second question and answer in second
 and the third q & a in the third
.

I am using AJAX to access the file:

```<code>$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $(data.faqs).each(function(index, value) {
        $('#firstQuestion').text("Q: " + value.question);
        $('#firstAnswer').text(value.answer);
        $('#secondQuestion').text("Q: " + value.question);
        $('#secondAnswer').text(value.answer);
        $('#thirdQuestion').text("Q: " + value.question);
        $('#thirdAnswer').text(value.answer);
      });
    }
  });
</code>```

And now I got some result that loops through all the items and gives me the last one but as I already said earlier I need the first question and answer at the first
 and so on.

Can you provide me with some ideas or a solution? I am trying to solve this for about 4 hours now and I have nothing. Any help is greatly appreciated.

答:
You don't need the loop - if you are uncertain on the length of the array this will not work and you'll need a different solution like @usman-rana posted, but if you don't this should work:</p>

```<code>$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $('#firstQuestion').text("Q: " + data.faqs[0].question);
      $('#firstAnswer').text(data.faqs[0]..answer);
      $('#secondQuestion').text("Q: " + data.faqs[1]..question);
      $('#secondAnswer').text(data.faqs[1].answer);
      $('#thirdQuestion').text("Q: " + data.faqs[2].question);
      $('#thirdAnswer').text(data.faqs[2].answer);
    }
  });
</code>```

Body:
I am trying to get only the selected item from this JSON file:

{
  "faqs": [
    {
      "id": 1,
      "question": "What is Salmon about?",
      "answer": "Building great sites for our amazing clients. Simple."
    },
    {
      "id": 3,
      "question": "What is the location of Salmon Watford?",
      "answer": "Just 2 minutes walk from Watford Junction Train Station"
    },
    {
      "id": 5,
      "question": "Is this the last question?",
      "answer": "Yes. You have done well!"
    }
  ]
}

For example i need first question and answer to be shown in first
, second question and answer in second
 and the third q & a in the third
.

I am using AJAX to access the file:

$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $(data.faqs).each(function(index, value) {
        $('#firstQuestion').text("Q: " + value.question);
        $('#firstAnswer').text(value.answer);
        $('#secondQuestion').text("Q: " + value.question);
        $('#secondAnswer').text(value.answer);
        $('#thirdQuestion').text("Q: " + value.question);
        $('#thirdAnswer').text(value.answer);
      });
    }
  });

And now I got some result that loops through all the items and gives me the last one but as I already said earlier I need the first question and answer at the first
 and so on.

Can you provide me with some ideas or a solution? I am trying to solve this for about 4 hours now and I have nothing. Any help is greatly appreciated.

Body:
You don't need the loop - if you are uncertain on the length of the array this will not work and you'll need a different solution like @usman-rana posted, but if you don't this should work:

$.ajax({
    url: 'faqs.json',
    dataType: 'json',
    type: 'GET',
    cache: true,
    success: function(data) {
      $('#firstQuestion').text("Q: " + data.faqs[0].question);
      $('#firstAnswer').text(data.faqs[0]..answer);
      $('#secondQuestion').text("Q: " + data.faqs[1]..question);
      $('#secondAnswer').text(data.faqs[1].answer);
      $('#thirdQuestion').text("Q: " + data.faqs[2].question);
      $('#thirdAnswer').text(data.faqs[2].answer);
    }
  });


问:
Material for web components Integration with Angular 4
I'm trying to integrate material components for web which is the latest release from Google as the successor of material design Lite. I tried all possible ways but, Couldn't integrate it with angular 4. The example link from Google is also broken. Could anyone please guide me in the integration of the same? A sample project on github or steps to integrate and use the components will be very much helpful.

Thanks in advance.

答:
Material Components for the Web has pretty good documentation for how to integrate with other frameworks, see https://material.io/components/web/docs/framework-integration/.

There are also third party efforts that already provide the integration. You could look at those for inspiration. Or you could actually use them instead of trying to reinvent that wheel again. The main README links to the Blox Material library for Angular integration, see https://blox.src.zone/material#/guides and https://github.com/src-zone/material. (Disclaimer: I am a developer for Blox Material).


问:
Data View Customization in Extension
I have overwritten the data view for a custom graph in an extension, which returns the correct data without issue, both by re-declaring the view, and using the delegate object techniques.  The issue is that when I do, the AllowSelect/AllowDelete modifications on the view in the primary graph stop working, once I comment out the overwrite, the logic works as normal.

Not sure what I'm missing, but any thoughts would be appreciated

Edit: To clarify, on the main graph, without the extension, the data retrieval and Allow... work without issue

```<code>public class FTTicketEntry : PXGraph<FTTicketEntry, UsrFTHeader>
    {
        public PXSelect<UsrFTHeader> FTHeader;
        public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;
</code>```

And with the extension, the data is returned correctly from the modified view, but the Allow... do not work from the main graph, only when entered on the extension

```<code>    public class FTTicketEntryExtension : PXGraphExtension<FTTicketEntry>
    {
        public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>, And<UsrFTGridLabor.projectID, Equal<Current<UsrFTHeader.projectID>>, And<UsrFTGridLabor.taskID, Equal<Current<UsrFTHeader.taskID>>>>>> FTGridLabor;
</code>```

I have also tried the other process on the extension with the same results, the data is filtered correctly, but the Allow... commands fail.

```<code>    public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;
    public virtual IEnumerable fTGridLabor()
    {
        foreach (PXResult<UsrFTGridLabor> record in Base.FTGridLabor.Select())
        {
            UsrFTGridLabor p = (UsrFTGridLabor)record;
            if (p.ProjectID == Base.FTHeader.Current.ProjectID && p.TaskID == Base.FTHeader.Current.TaskID)
            {
                yield return record;
            }
        }
    }
</code>```

My main concern with not wanting to use PXSelectReadOnly, is that there is a status field on the header which drives when certain combinations of the conditions are required and are called on the rowselected events, sometimes all and sometimes none, and the main issue is that I obviously don't want to have to replicate all of the UI logic into the extension, when overwriting the view was the main intent of the extension for the screen.

Appreciate the assistance, and hopefully you see something I'm overlooking or have missed

Thanks

答:
Every BLC instance stores all actual data views and actions within 2 collections: Views and Actions. Whenever, you customize a data view or an action with a BLC extension, the original data view / action gets replaced in the appropriate collection by your custom object declared within the extension class. After the original data view or action was removed from the appropriate collection, it's quite obvious that any change made to the original object will not make any effect, since the original object is not used by the BLC anymore.

The easiest way to access actual object from either of these 2 collections would be as follows: Views["FTGridLabor"].Allow... = value;

Alternatively, you might operate with AllowInsert, AllowUpdate and AllowDelete properties on the cache level: FTGridLabor.Cache.Allow... = value;

By changing AllowXXX properties on the cache level, you completely eliminate the need for setting AllowXXX on the data view, since PXCache.AllowXXX properties have higher priority when compared to identical properties on the data view level:

```<code>public class PXView
{
    ...
    protected bool _AllowUpdate = true;
    public bool AllowUpdate
    {
        get
        {
            if (_AllowUpdate && !IsReadOnly)
            {
                return Cache.AllowUpdate;
            }
            return false;
        }
        set
        {
            _AllowUpdate = value;
        }
    }
    ...
}
</code>```

With all that said, to resolve your issue with UI Logic not applying to modified view, please consider one of the following options:

Set AllowXXX property values in both the original BLC and its extensions via the object obtained from the Views collection:
Views["FTGridLabor"].Allow... = value;

operate with AllowXXX property values on the cache level: FTGridLabor.Cache.Allow... = value;

Title: Data View Customization in Extension

Body:
I have overwritten the data view for a custom graph in an extension, which returns the correct data without issue, both by re-declaring the view, and using the delegate object techniques.  The issue is that when I do, the AllowSelect/AllowDelete modifications on the view in the primary graph stop working, once I comment out the overwrite, the logic works as normal.

Not sure what I'm missing, but any thoughts would be appreciated

Edit: To clarify, on the main graph, without the extension, the data retrieval and Allow... work without issue

public class FTTicketEntry : PXGraph<FTTicketEntry, UsrFTHeader>
    {
        public PXSelect<UsrFTHeader> FTHeader;
        public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;

And with the extension, the data is returned correctly from the modified view, but the Allow... do not work from the main graph, only when entered on the extension

    public class FTTicketEntryExtension : PXGraphExtension<FTTicketEntry>
    {
        public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>, And<UsrFTGridLabor.projectID, Equal<Current<UsrFTHeader.projectID>>, And<UsrFTGridLabor.taskID, Equal<Current<UsrFTHeader.taskID>>>>>> FTGridLabor;

I have also tried the other process on the extension with the same results, the data is filtered correctly, but the Allow... commands fail.

    public PXSelect<UsrFTGridLabor, Where<UsrFTGridLabor.ticketNbr, Equal<Current<UsrFTHeader.ticketNbr>>>> FTGridLabor;
    public virtual IEnumerable fTGridLabor()
    {
        foreach (PXResult<UsrFTGridLabor> record in Base.FTGridLabor.Select())
        {
            UsrFTGridLabor p = (UsrFTGridLabor)record;
            if (p.ProjectID == Base.FTHeader.Current.ProjectID && p.TaskID == Base.FTHeader.Current.TaskID)
            {
                yield return record;
            }
        }
    }

My main concern with not wanting to use PXSelectReadOnly, is that there is a status field on the header which drives when certain combinations of the conditions are required and are called on the rowselected events, sometimes all and sometimes none, and the main issue is that I obviously don't want to have to replicate all of the UI logic into the extension, when overwriting the view was the main intent of the extension for the screen.

Appreciate the assistance, and hopefully you see something I'm overlooking or have missed

Thanks

Body:
Every BLC instance stores all actual data views and actions within 2 collections: Views and Actions. Whenever, you customize a data view or an action with a BLC extension, the original data view / action gets replaced in the appropriate collection by your custom object declared within the extension class. After the original data view or action was removed from the appropriate collection, it's quite obvious that any change made to the original object will not make any effect, since the original object is not used by the BLC anymore.

The easiest way to access actual object from either of these 2 collections would be as follows: Views["FTGridLabor"].Allow... = value;

Alternatively, you might operate with AllowInsert, AllowUpdate and AllowDelete properties on the cache level: FTGridLabor.Cache.Allow... = value;

By changing AllowXXX properties on the cache level, you completely eliminate the need for setting AllowXXX on the data view, since PXCache.AllowXXX properties have higher priority when compared to identical properties on the data view level:

public class PXView
{
    ...
    protected bool _AllowUpdate = true;
    public bool AllowUpdate
    {
        get
        {
            if (_AllowUpdate && !IsReadOnly)
            {
                return Cache.AllowUpdate;
            }
            return false;
        }
        set
        {
            _AllowUpdate = value;
        }
    }
    ...
}

With all that said, to resolve your issue with UI Logic not applying to modified view, please consider one of the following options:

Set AllowXXX property values in both the original BLC and its extensions via the object obtained from the Views collection:
Views["FTGridLabor"].Allow... = value;

operate with AllowXXX property values on the cache level: FTGridLabor.Cache.Allow... = value;


问:
Why is my "docker-compose run" not working properly on windows?
So I am running a script that calls:

```<code>docker-compose run --rm web sh /data/bin/install_test_db.sh
</code>```

and it seems to work fine when running it on ubuntu but when I run it on Windows using Git Bash I get this error:

```<code>sh: 0: Can't open C:/Program Files/Git/data/bin/install_test_db.sh
</code>```

It seems to be trying to run the script on my machine and not the actual container from which I am trying to call it from.

Any ideas on why this is happening?

答:
First, try passing a command to your sh shell:

```<code>docker-compose run --rm web sh -c "/data/bin/install_test_db.sh"
</code>```

Or:

```<code>docker-compose run --rm web "sh -c /data/bin/install_test_db.sh"
</code>```

That will avoid your host shell (the git bash) to interpret an absolute path (starting with '/') as one from the Git installation path.

That will keep /data/... as an argument to be passed to the shell executed in the container.

Note: If you are using Docker for Windows (meaning not VirtualBox, but HyperV), you don't need git bash at all.

Try the same command from a regular CMD (with docker.exe in your %PATH%, which Docker for Windows set for you)

```<code>vonc@VONCAVN7 C:\Users\vonc
> where docker
C:\Program Files\Docker\Docker\Resources\bin\docker.exe
</code>```

If you need Linux-like commands from that same CMD session, then yes, add git paths:

```<code>set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%
</code>```

Body:
So I am running a script that calls:

docker-compose run --rm web sh /data/bin/install_test_db.sh

and it seems to work fine when running it on ubuntu but when I run it on Windows using Git Bash I get this error:

sh: 0: Can't open C:/Program Files/Git/data/bin/install_test_db.sh

It seems to be trying to run the script on my machine and not the actual container from which I am trying to call it from.

Any ideas on why this is happening?

Body:
First, try passing a command to your sh shell:

docker-compose run --rm web sh -c "/data/bin/install_test_db.sh"

Or:

docker-compose run --rm web "sh -c /data/bin/install_test_db.sh"

That will avoid your host shell (the git bash) to interpret an absolute path (starting with '/') as one from the Git installation path.

That will keep /data/... as an argument to be passed to the shell executed in the container.

Note: If you are using Docker for Windows (meaning not VirtualBox, but HyperV), you don't need git bash at all.

Try the same command from a regular CMD (with docker.exe in your %PATH%, which Docker for Windows set for you)

vonc@VONCAVN7 C:\Users\vonc
> where docker
C:\Program Files\Docker\Docker\Resources\bin\docker.exe

If you need Linux-like commands from that same CMD session, then yes, add git paths:

set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%


问:
Have different initial_data fixtures for different stages (testing v. production)
I have an initial_data fixture that I want to load everytime except for production. I already have different settings file for production and non-production deployments.

Any suggestions on how to accomplish this?

Clarification: I do not want test fixtures. Basically, I just need the fixture to be loaded based on a setting change of some sort. I'll be digging into the Django code to see if I could figure out an elegant way to accomplish this.

答:
The easiest way is to use manage.py testserver [fixture ...]

If this is a staging (rather than dev) deployment, though, you may not want to use django's builtin server. In that case, a quick (if hacky) way of doing what you're after is to have the fixtures in an app (called, for example, "undeployed") that is only installed in your non-production settings.


问:
Python function dereferences a pointer but still alters the original list
I was playing around with python for the last few days and I keep getting a weird problem. (For reference, I'm working on project euler's 345.)
So... I'm trying to zero a row and a column of a 2D array, but not the point where they intersect. Now, I understand that there might be a more pythonic way of solving this, but I'm mainly concerned with why the code I have here isn't working.

```<code>def choose(initial_grid,row,col):
  """Return a grid with a given row and column zeroed except where intersect.
  """
  grid = list(initial_grid)                 #FLAG 1
  Special_value = grid[row][col]
  grid[row] = [0]*len(grid[row])
  for i in xrange(len(grid)):
    grid[i][col] = 0
  grid[row][col] = Special_value
  return grid
qwer = [[ 1, 2, 3, 4],
        [ 5, 6, 7, 8],
        [ 9,10,11,12],
        [13,14,15,16]]
print choose(qwer,1,1)
print qwer
</code>```

Anyways, I'd expect the function output to be

```<code>[[1, 0, 3, 4], [0, 6, 0, 0], [9, 0, 11, 12], [13, 0, 15, 16]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
</code>```

But... It isn't. For whatever reason, qwer gets its column 1 cleared. I've tried doing a list copy to dereference the pointer passed by initial_grid, and I've tried using grid = initial_grid[:], but nothing seems to work.

So what's wrong? How do I fix this? And why is this wrong?

答:
list(initial_grid) makes a shallow copy of your list. The inner lists are not copied.

Demo:

```<code>>>> l = [[1, 2], [0, 0]]
>>> c = list(l)
>>> l is c
False
>>> all(x is y for x,y in zip(l, c))
True
>>> c[0][0] = 5
>>> c
[[5, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]
</code>```

If you want a deep copy, use copy.deepcopy. Or for a 2D list, write

```<code>>>> d = [sub[:] for sub in l]
>>> d[0][0] = 7
>>> d
[[7, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]
</code>```

Also, your lingo is off. We don't have pointers in Python. We have names and values.

Body:
I was playing around with python for the last few days and I keep getting a weird problem. (For reference, I'm working on project euler's 345.)
So... I'm trying to zero a row and a column of a 2D array, but not the point where they intersect. Now, I understand that there might be a more pythonic way of solving this, but I'm mainly concerned with why the code I have here isn't working.

def choose(initial_grid,row,col):
  """Return a grid with a given row and column zeroed except where intersect.
  """
  grid = list(initial_grid)                 #FLAG 1
  Special_value = grid[row][col]
  grid[row] = [0]*len(grid[row])
  for i in xrange(len(grid)):
    grid[i][col] = 0
  grid[row][col] = Special_value
  return grid
qwer = [[ 1, 2, 3, 4],
        [ 5, 6, 7, 8],
        [ 9,10,11,12],
        [13,14,15,16]]
print choose(qwer,1,1)
print qwer

Anyways, I'd expect the function output to be

[[1, 0, 3, 4], [0, 6, 0, 0], [9, 0, 11, 12], [13, 0, 15, 16]]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

But... It isn't. For whatever reason, qwer gets its column 1 cleared. I've tried doing a list copy to dereference the pointer passed by initial_grid, and I've tried using grid = initial_grid[:], but nothing seems to work.

So what's wrong? How do I fix this? And why is this wrong?

Body:
list(initial_grid) makes a shallow copy of your list. The inner lists are not copied.

Demo:

>>> l = [[1, 2], [0, 0]]
>>> c = list(l)
>>> l is c
False
>>> all(x is y for x,y in zip(l, c))
True
>>> c[0][0] = 5
>>> c
[[5, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]

If you want a deep copy, use copy.deepcopy. Or for a 2D list, write

>>> d = [sub[:] for sub in l]
>>> d[0][0] = 7
>>> d
[[7, 2], [0, 0]]
>>> l
[[5, 2], [0, 0]]

Also, your lingo is off. We don't have pointers in Python. We have names and values.


问:
Add favicon.ico to asp.net core project using webpack
How to add a favicon.ico to a ASP.Net Core project using Webpack?</p>

答:
The browser will look for the favicon.ico by default in the root location so you just have to add the following line to your webpack.config.js file:

```<code>{ "Locations": [ { "From": "./favicon.ico", "To": "./wwwroot/" }, ] }
</code>```

Once you build and start your project the favicon.ico should have been copied from your original location to the wwwroot.
And you should be able to test it by visiting

http://localhost:5000/favicon.ico

No need to add a link to your HTML files.

Body:
The browser will look for the favicon.ico by default in the root location so you just have to add the following line to your webpack.config.js file:

{ "Locations": [ { "From": "./favicon.ico", "To": "./wwwroot/" }, ] }

Once you build and start your project the favicon.ico should have been copied from your original location to the wwwroot.
And you should be able to test it by visiting

http://localhost:5000/favicon.ico

No need to add a link to your HTML files.


问:
Mulesoft flow timeout
I am designing an api using Mulesoft and I would like to have it return a generic response when it takes more than 10 seconds to respond. Currently I am accomplishing this by using an HTTP connector to call another flow within the api.

```<code><http:request-config name="HTTP_Request_Configuration" host="localhost" port="8081" responseTimeout="10000" doc:name="HTTP Request Configuration"/>
<flow name="Incomming-Flow">
    <!-- get request -->
    <http:request config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" method="POST" doc:name="HTTP"/>
    <catch-exception-strategy doc:name="Catch Exception Strategy">
        <!-- Set payload to generic response when http call times out -->
    </catch-exception-strategy>
</flow>
<flow name="Processing-Flow">
    <http:listener config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" allowedMethods="POST" doc:name="HTTP"/>
    <!--
        processing components go here
     -->
</flow>
</code>```

Is there a better way of stopping a flow and returning a generic response when it has taken too long?

答:
Try this one -

a. Globally for a given application

Add the global element configuration in the application and set the attribute defaultResponseTimeout:

```<code><configuration defaultResponseTimeout="10000" />
</code>```

b. Specifically for a flow

Add the attached TimeoutMessageProcessor to your application and place it before the outbound endpoint:

```<code><custom-processor class="com.mule.support.TimeoutMessageProcessor">
    <spring:property name="timeout" value="10000" />
</custom-processor>
</code>```

Title: Mulesoft flow timeout

Body:
I am designing an api using Mulesoft and I would like to have it return a generic response when it takes more than 10 seconds to respond. Currently I am accomplishing this by using an HTTP connector to call another flow within the api.

<http:request-config name="HTTP_Request_Configuration" host="localhost" port="8081" responseTimeout="10000" doc:name="HTTP Request Configuration"/>
<flow name="Incomming-Flow">

    <http:request config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" method="POST" doc:name="HTTP"/>
    <catch-exception-strategy doc:name="Catch Exception Strategy">

    </catch-exception-strategy>
</flow>
<flow name="Processing-Flow">
    <http:listener config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" allowedMethods="POST" doc:name="HTTP"/>

</flow>

Is there a better way of stopping a flow and returning a generic response when it has taken too long?

Body:
Try this one -

a. Globally for a given application

Add the global element configuration in the application and set the attribute defaultResponseTimeout:

<configuration defaultResponseTimeout="10000" />

b. Specifically for a flow

Add the attached TimeoutMessageProcessor to your application and place it before the outbound endpoint:

<custom-processor class="com.mule.support.TimeoutMessageProcessor">
    <spring:property name="timeout" value="10000" />
</custom-processor>


问:
How to most correctly work with Interfaces?
Is this code correct as a pattern? Which way is better, like this or via Parent class Message.

Or is it better to use only 3 classes and 1 Interface? Where I type something like:

INotification Notify = new SystemMessage();

```<code>public interface INotification { void ShowNotification(String text); }

    class Message : INotification
    {
        static internal Message CurrentMessageType { get; set; }
        public virtual void ShowNotification(string text) {
            if (CurrentMessageType == null) CurrentMessageType = new SystemMessage();
        }
    }

    class SystemMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("SYSTEM: " + text);
        }
    }

    class ConsoleMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("CONSOLE: " + text);
        }
    }

    class NotifyMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("NOTIFY: " + text);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.Write("MSG: ");
                String rsp = Console.ReadLine();
                switch (rsp)
                {
                    case "sys":
                        Message.CurrentMessageType = new SystemMessage();
                        break;
                    case "con":
                        Message.CurrentMessageType = new ConsoleMessage();
                        break;
                    case "not":
                        Message.CurrentMessageType = new NotifyMessage();
                        break;
                    case "exit":
                        return;
                }

                Message.CurrentMessageType.ShowNotification("test message");

            }
        }
    }
</code>```

答:
I don't see why you need many classes, if they all do pretty much the same thing? For such a simple case as this, a good pattern would be KISS :)</p>

```<code>class Message
{
    static internal string CurrentMessageType { get; set; } = "SYSTEM"
    static void ShowNotification(string text) {
        Console.WriteLine(CurrentMessageType + ": " + text);
    }
}

class Program
{
    static void Main(string[] args)
    {
        while(true)
        {
            Console.Write("MSG: ");
            String rsp = Console.ReadLine();
            switch (rsp)
            {
                case "sys":
                    Message.CurrentMessageType = "SYSTEM";
                    break;
                case "con":
                    Message.CurrentMessageType = "CONSOLE";
                    break;
                case "not":
                    Message.CurrentMessageType = "NOTIFY";
                    break;
                case "exit":
                    return;
            }

            Message.ShowNotification("test message");

        }
    }
}
</code>```

Body:
Is this code correct as a pattern? Which way is better, like this or via Parent class Message.

Or is it better to use only 3 classes and 1 Interface? Where I type something like:

INotification Notify = new SystemMessage();

public interface INotification { void ShowNotification(String text); }

    class Message : INotification
    {
        static internal Message CurrentMessageType { get; set; }
        public virtual void ShowNotification(string text) {
            if (CurrentMessageType == null) CurrentMessageType = new SystemMessage();
        }
    }

    class SystemMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("SYSTEM: " + text);
        }
    }

    class ConsoleMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("CONSOLE: " + text);
        }
    }

    class NotifyMessage : Message {
        public override void ShowNotification(string text) {
            Console.WriteLine("NOTIFY: " + text);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.Write("MSG: ");
                String rsp = Console.ReadLine();
                switch (rsp)
                {
                    case "sys":
                        Message.CurrentMessageType = new SystemMessage();
                        break;
                    case "con":
                        Message.CurrentMessageType = new ConsoleMessage();
                        break;
                    case "not":
                        Message.CurrentMessageType = new NotifyMessage();
                        break;
                    case "exit":
                        return;
                }

                Message.CurrentMessageType.ShowNotification("test message");

            }
        }
    }

Body:
I don't see why you need many classes, if they all do pretty much the same thing? For such a simple case as this, a good pattern would be KISS :)

class Message
{
    static internal string CurrentMessageType { get; set; } = "SYSTEM"
    static void ShowNotification(string text) {
        Console.WriteLine(CurrentMessageType + ": " + text);
    }
}

class Program
{
    static void Main(string[] args)
    {
        while(true)
        {
            Console.Write("MSG: ");
            String rsp = Console.ReadLine();
            switch (rsp)
            {
                case "sys":
                    Message.CurrentMessageType = "SYSTEM";
                    break;
                case "con":
                    Message.CurrentMessageType = "CONSOLE";
                    break;
                case "not":
                    Message.CurrentMessageType = "NOTIFY";
                    break;
                case "exit":
                    return;
            }

            Message.ShowNotification("test message");

        }
    }
}