问:
Understanding PIVOT?
Most of the examples that I've seen are more complex, so I guess I posted something simple to fully understand the concept of pivot.

```<code>declare @yt TABLE
(
  Id int,
  Dept varchar(10),
  [Day] int,
  [Counter] int
);

INSERT INTO @yt
(
  ID, Dept, [Day], [Counter]
)
VALUES
    (102, 'DeptA', 20170704, 96),
    (102, 'DeptP', 20170704, 223),
    (103, 'DeptA', 20170704, 84),
    (103, 'DeptW', 20170704, 43);

select *
from
(
  select id, dept, [day], [Counter]
  from @yt
) src
pivot
(
  sum([Counter])
  for Dept in ([DeptA], [DeptP], [DeptW])
) piv;
</code>```

From my understanding, the code within Pivot does the following: 1) aggregates the column selected (sum([counter])), pivots the column in for Dept and then does a group by of the rest of the columns that are not specified (ID and Day).

Would I be able to add two sums? Or is this something beyond the scope of the pivot functionality? The following generates an error:

```<code>declare @yt TABLE
(
  Id int,
  Dept varchar(10),
  [Day] int,
  [Counter] int,
  Sales int
);

INSERT INTO @yt
(
  ID, Dept, [Day], [Counter], Sales
)
VALUES
    (102, 'DeptA', 20170704, 96, 12),
    (102, 'DeptP', 20170704, 223, 5),
    (103, 'DeptA', 20170704, 84, 9),
    (103, 'DeptW', 20170704, 43, 11);

select *
from
(
  select id, dept, [day], [Counter], sales
  from @yt
) src
pivot
(
  sum([Counter]), ([sales])
  for Dept in ([DeptA], [DeptP], [DeptW])
) piv;
</code>```

Wanted to add that this question was helpful in understanding the pivot tables.

答:
You can always prevent the aggregate operation by insuring the rows are unique.
Although an aggregation {SUM|MIN|MAX} must still be present in the syntax, if the rows are unique, it can't ever actually have multiple rows to operate upon.

A bigger question is what you want to have happen if there ARE multiple rows.  In the case below I duplicated 1 source row and you'll see how it appears by running the code.  If you want to ignore additional rows you can just add "where r = 1".

```<code>declare @yt TABLE
(
  [Store] int,
  [Week] int,
  [xCount] int
);

INSERT INTO @yt
(
  [Store],
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

select piv.Store ,
       piv.[1] ,
       piv.[2] ,
       piv.[3]
from
(
  select store, week, xCount,row_number() over(partition by Store,Week order by Store) R
  from @yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;
</code>```

Title: Understanding PIVOT?

Body:
Most of the examples that I've seen are more complex, so I guess I posted something simple to fully understand the concept of pivot.

declare @yt TABLE
(
  Id int,
  Dept varchar(10),
  [Day] int,
  [Counter] int
);

INSERT INTO @yt
(
  ID, Dept, [Day], [Counter]
)
VALUES
    (102, 'DeptA', 20170704, 96),
    (102, 'DeptP', 20170704, 223),
    (103, 'DeptA', 20170704, 84),
    (103, 'DeptW', 20170704, 43);

select *
from
(
  select id, dept, [day], [Counter]
  from @yt
) src
pivot
(
  sum([Counter])
  for Dept in ([DeptA], [DeptP], [DeptW])
) piv;

From my understanding, the code within Pivot does the following: 1) aggregates the column selected (sum([counter])), pivots the column in for Dept and then does a group by of the rest of the columns that are not specified (ID and Day).

Would I be able to add two sums? Or is this something beyond the scope of the pivot functionality? The following generates an error:

declare @yt TABLE
(
  Id int,
  Dept varchar(10),
  [Day] int,
  [Counter] int,
  Sales int
);

INSERT INTO @yt
(
  ID, Dept, [Day], [Counter], Sales
)
VALUES
    (102, 'DeptA', 20170704, 96, 12),
    (102, 'DeptP', 20170704, 223, 5),
    (103, 'DeptA', 20170704, 84, 9),
    (103, 'DeptW', 20170704, 43, 11);

select *
from
(
  select id, dept, [day], [Counter], sales
  from @yt
) src
pivot
(
  sum([Counter]), ([sales])
  for Dept in ([DeptA], [DeptP], [DeptW])
) piv;

Wanted to add that this question was helpful in understanding the pivot tables.

Body:
You can always prevent the aggregate operation by insuring the rows are unique.
Although an aggregation {SUM|MIN|MAX} must still be present in the syntax, if the rows are unique, it can't ever actually have multiple rows to operate upon.

A bigger question is what you want to have happen if there ARE multiple rows.  In the case below I duplicated 1 source row and you'll see how it appears by running the code.  If you want to ignore additional rows you can just add "where r = 1".

declare @yt TABLE
(
  [Store] int,
  [Week] int,
  [xCount] int
);

INSERT INTO @yt
(
  [Store],
  [Week], [xCount]
)
VALUES
    (102, 1, 96),
    (101, 1, 138),
    (105, 1, 37),
    (109, 1, 59),
    (101, 2, 282),
    (102, 2, 212),
    (105, 2, 78),
    (105, 2, 78),
    (109, 2, 97),
    (105, 3, 60),
    (102, 3, 123),
    (101, 3, 220),
    (109, 3, 87);

select piv.Store ,
       piv.[1] ,
       piv.[2] ,
       piv.[3]
from
(
  select store, week, xCount,row_number() over(partition by Store,Week order by Store) R
  from @yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;


来源: stackexchange

问:
Hide specific rows using DataTables plugin?
I have a web page with a table that displays data from a database. There is a main
 being displayed and an additional
 that is hidden and only displays with jquery when the user clicks a button that is on the first main
.

The problem that I am getting is when I use the datatables plugin, it finds all the rows and counts them, so I have 11 rows of data and 11 additional hidden rows under each main row. It then displays at the button of the table "Showing 1 to 10 of 22 entries". I don't want Datatables to count or see the hidden rows. I there a way to fix this problem. All
's have ID's and classes, so I thought there might be a simple way of sorting this data properly.

Also, when I do click the main
 to display the hidden <tr> it does not slide down under the main
 I clicked, instead It goes above all the main
's. Anyone know why?

Datatables Site []>

答:
the query you do to count the rows should use the ":visible" attribute. So your query should look something like:</p>

```<code>var entries = $("tr:visible").length;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
the query you do to count the rows should use the ":visible" attribute. So your query should look something like:

var entries = $("tr:visible").length;

ContentLicense: CC BY-SA 2.5


问:
Tomcat 7 is ignoring cookies?
I'm trying to upgrade from Tomcat 5.5 to Tomcat 7, and almost everything is working -- I just have some cookies that are getting through on Tomcat 5.5, but disappearing on Tomcat 7. That is, Firebug confirms that the cookies are being sent in both cases, but on Tomcat 5.5 they show up in a request.getCookies() call, and in Tomcat 7 they don't. Some cookies still show up (JSESSIONID, for example), but a couple are missing.

This is the same application running on the same server, port, etc, I just shutdown Tomcat 5.5, startup 7, and the cookies no longer get through.

If it's relevant, both Tomcat instances are behind an Apache proxy running on a different server. It doesn't seem like it should be relevant, though, since Apache is clearly able to pass the cookies to Tomcat 5.5.

My guess is it's a security feature of some sort, though I haven't been able to figure out what it would be. The missing cookies are for domain .domain.org, while the cookies that are getting through (like JSESSIONID) are for host subdomain.domain.org (bolded text is just an example, obviously).

I tried setting useHttpOnly to false and crossContext to true in the context, in case it had something to do with one of those, but it didn't help. Besides those two settings, are there any other new features in Tomcat 7 (or Tomcat 6, for that matter) that could lead to it leaving out cookies? And if so, is there a handy workaround?

EDIT: I forgot to mention that it probably doesn't have anything to do with the cookie path -- the cookies that don't work have a path of "/", and the cookies that do work have variously "/", "/application", and "/application/".

答:
I might be late to a party, but I had a similar problem that required a much different solution.

The problem was in login data stored in cookies and then having the keys hard-coded in a file to confirm who is who.  Due to WAR packaging, the paths got lost in a transfer, and the only thing I had to do was to correct the paths to right JSON files on a server.

Therefore, the issue was not in Tomcat but in a way the things got transferred and calls to those things.

Spent half of a day to locate the issue (I thought that there was some setting to be done in Tomcat), but then it was very simple once I realized that paths to a JSON were off.

Title: Tomcat 7 is ignoring cookies?


问:
d3: Appending multiple elements based on integer in data
I am new to d3 and still working out some of the basics.

From what I understand you shouldn't need for loops with d3.

If I have the following data:

```<code>[
  {
    "title": "mine",
    "shapes" : {
      "circle" : 15,
      "square": 20
    }
  },
  {
    "title": "yours",
    "shapes": {
      "circle": 2,
      "square": 18
    }
  }
]
</code>```

how do I append 15 circles and 20 squares?

I know how to append an element for each item in an object, but not how to use an integer in object.

Any guidance would be greatly appreciated!

答:
The point of the d3 data pipeline is to avoid unnecessary explicit looping and procedural code. Looping still has a place.

But let's say you want to be idiomatic, and not loop. Then when you need is d3.range(). It turns an integer bound into a list. E.g. d3.range(4) == [0, 1, 2, 3]. If you're going through a pipeline, have an integer, and need elements for every value up to that integer, the key snippet is:

```<code>g.selectAll('circle')
 .data(d => d3.range(d.shapes.circle))
 .enter()
 .append('circle')
</code>```

which converts the number of circles coming in from your data item to that many circles. Unfortunately, it's not quite that simple in practice. You're processing a multi-level structure, and you probably want to not just produce N different circles, but vary those circles based on some higher-level context. So in practice it's more like:

```<code>g.selectAll('circle')
 .data((d, i) => d3.range(d.shapes.circle)
                   .map(j => [i, j]))
 .enter()
 .append('circle')
</code>```

That is, for the i'th record in your data array, the data fed to create circles combines i with the values of j coming from d3.range().

The full code's a bit longer than fits comfortably here, but here's a live example on Plunker.

Colors are chosen by the order in the input data; shape positioning and opacity are chosen randomly.

Body:
I am new to d3 and still working out some of the basics.

From what I understand you shouldn't need for loops with d3.

If I have the following data:

[
  {
    "title": "mine",
    "shapes" : {
      "circle" : 15,
      "square": 20
    }
  },
  {
    "title": "yours",
    "shapes": {
      "circle": 2,
      "square": 18
    }
  }
]

how do I append 15 circles and 20 squares?

I know how to append an element for each item in an object, but not how to use an integer in object.

Any guidance would be greatly appreciated!

Body:
The point of the d3 data pipeline is to avoid unnecessary explicit looping and procedural code. Looping still has a place.

But let's say you want to be idiomatic, and not loop. Then when you need is d3.range(). It turns an integer bound into a list. E.g. d3.range(4) == [0, 1, 2, 3]. If you're going through a pipeline, have an integer, and need elements for every value up to that integer, the key snippet is:

g.selectAll('circle')
 .data(d => d3.range(d.shapes.circle))
 .enter()
 .append('circle')

which converts the number of circles coming in from your data item to that many circles. Unfortunately, it's not quite that simple in practice. You're processing a multi-level structure, and you probably want to not just produce N different circles, but vary those circles based on some higher-level context. So in practice it's more like:

g.selectAll('circle')
 .data((d, i) => d3.range(d.shapes.circle)
                   .map(j => [i, j]))
 .enter()
 .append('circle')

That is, for the i'th record in your data array, the data fed to create circles combines i with the values of j coming from d3.range().

The full code's a bit longer than fits comfortably here, but here's a live example on Plunker.

Colors are chosen by the order in the input data; shape positioning and opacity are chosen randomly.


问:
How to manually set the color as the second one of the theme in ggplot?
Sorry if my question is somehow confusing, don't hesitate to edit it.

I'm comparing 2 sets of data and I'm now creating plots.

On some plots, I can show both groups and ggplot automatically add some pretty colors, in my case red for the first group, and blue for the second one.

My problem is that on other plots, I have to show either one group or the other, and so the color is always red.

How can I manually ask ggplot to fill my plot with the second color of the theme ?

Here is some dummy code if you like :

```<code>df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")),
                 f2=factor(rbinom(100, 1, 0.45), label=c("young","old")),
                 boxthis=rnorm(100))

#both groups on the graph, 2 colors (red and blue) :
ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot()

#each group on one graph, both the same color (and I'd like one red and one blue)
ggplot(aes(y = boxthis, x = f2, fill = "m"), data = df) + geom_boxplot()
ggplot(aes(y = boxthis, x = f2, fill = "w"), data = df) + geom_boxplot()

#I know the grouping is incorrect, this is just an example where I keep the same df
</code>```

答:
Are facets what you're looking for?  Try this:

```<code>ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) +
    geom_boxplot() +
    facet_grid(~ f1)
</code>```

Link to image

Body:
Sorry if my question is somehow confusing, don't hesitate to edit it.

I'm comparing 2 sets of data and I'm now creating plots.

On some plots, I can show both groups and ggplot automatically add some pretty colors, in my case red for the first group, and blue for the second one.

My problem is that on other plots, I have to show either one group or the other, and so the color is always red.

How can I manually ask ggplot to fill my plot with the second color of the theme ?

Here is some dummy code if you like :

df <- data.frame(f1=factor(rbinom(100, 1, 0.45), label=c("m","w")),
                 f2=factor(rbinom(100, 1, 0.45), label=c("young","old")),
                 boxthis=rnorm(100))

#both groups on the graph, 2 colors (red and blue) :
ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) + geom_boxplot()

#each group on one graph, both the same color (and I'd like one red and one blue)
ggplot(aes(y = boxthis, x = f2, fill = "m"), data = df) + geom_boxplot()
ggplot(aes(y = boxthis, x = f2, fill = "w"), data = df) + geom_boxplot()

#I know the grouping is incorrect, this is just an example where I keep the same df

Body:
Are facets what you're looking for?  Try this:

ggplot(aes(y = boxthis, x = f2, fill = f1), data = df) +
    geom_boxplot() +
    facet_grid(~ f1)

Link to image


问:
get the quotient of two textbox which has an onChange event
I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.

    function sum(){
    var ua = document.getElementById('ua').value;
    var ub = document.getElementById('ub').value;
    var result = parseInt(ua)  + parseInt(ub);
    if (!isNaN(result)) {
    document.getElementById('tu').value = result;
    document.getElementById('tu').dispatchEvent(new Event('change'));
    }
    }
    function suma(){
    var ua = document.getElementById('ua').value;
    var ga = document.getElementById('ga').value;
    var result = parseInt(ua)  * parseInt(ga);
    if (!isNaN(result)) {
    document.getElementById('uu').value = result;
    document.getElementById('uu').dispatchEvent(new Event('change'));
    }
    }
    function sumb(){
    var ub = document.getElementById('ub').value;
    var gb = document.getElementById('gb').value;
    var result = parseInt(ub)  * parseInt(gb);
    if (!isNaN(result)) {
    document.getElementById('a').value = result;
    document.getElementById('a').dispatchEvent(new Event('change'));
    }
    }
    function s(){
    var uu = document.getElementById('uu').value;
    var a = document.getElementById('a').value;
    var result = parseInt(uu)  + parseInt(a);
    if (!isNaN(result)) {
    document.getElementById('tt').value = result;
    document.getElementById('tt').dispatchEvent(new Event('change'));
    }
    }
    function g(){
    var tt = document.getElementById('tt').value;
    var tu = document.getElementById('tu').value;
    var result = parseFloat(tt)  / parseFloat(tu);
    if (!isNaN(result)) {
    document.getElementById('gpa').value = result;
    }
    }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <input type="text"  id="ua" name="ua" size="7" onkeyup="sum();">
    <input type="text"  id="ga" name="ga" size="7" onkeyup="suma();">
    <input type="text"  id="uu" name="uu" size="7" onchange="s();"/>

    <input type="text"  id="ub" name="ub" size="7" onkeyup="sum();">
    <input type="text"  id="ga" name="ga" size="7" onkeyup="sumb();">
    <input type="text"  id="a" name="a" size="7" onchange="s();"/>

    <input type="text" id="tu" name="tu" onchange="g();"/>
    <input type="text" id="tt" name="tt" onchange="g();"/>

    <label>GPA</label>
    <input type="text" id="gpa" /></code>```

答:
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).

That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.

As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?

In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:

var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');

function updateQuotient () {
  var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
  if (!isNaN(result)) {
    resultElement.value = result;
  }
}

dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result"></code>```

Body:
I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.

    function sum(){
    var ua = document.getElementById('ua').value;
    var ub = document.getElementById('ub').value;
    var result = parseInt(ua)  + parseInt(ub);
    if (!isNaN(result)) {
    document.getElementById('tu').value = result;
    document.getElementById('tu').dispatchEvent(new Event('change'));
    }
    }
    function suma(){
    var ua = document.getElementById('ua').value;
    var ga = document.getElementById('ga').value;
    var result = parseInt(ua)  * parseInt(ga);
    if (!isNaN(result)) {
    document.getElementById('uu').value = result;
    document.getElementById('uu').dispatchEvent(new Event('change'));
    }
    }
    function sumb(){
    var ub = document.getElementById('ub').value;
    var gb = document.getElementById('gb').value;
    var result = parseInt(ub)  * parseInt(gb);
    if (!isNaN(result)) {
    document.getElementById('a').value = result;
    document.getElementById('a').dispatchEvent(new Event('change'));
    }
    }
    function s(){
    var uu = document.getElementById('uu').value;
    var a = document.getElementById('a').value;
    var result = parseInt(uu)  + parseInt(a);
    if (!isNaN(result)) {
    document.getElementById('tt').value = result;
    document.getElementById('tt').dispatchEvent(new Event('change'));
    }
    }
    function g(){
    var tt = document.getElementById('tt').value;
    var tu = document.getElementById('tu').value;
    var result = parseFloat(tt)  / parseFloat(tu);
    if (!isNaN(result)) {
    document.getElementById('gpa').value = result;
    }
    }

   <input type="text"  id="ua" name="ua" size="7" onkeyup="sum();">
    <input type="text"  id="ga" name="ga" size="7" onkeyup="suma();">
    <input type="text"  id="uu" name="uu" size="7" onchange="s();"/>

    <input type="text"  id="ub" name="ub" size="7" onkeyup="sum();">
    <input type="text"  id="ga" name="ga" size="7" onkeyup="sumb();">
    <input type="text"  id="a" name="a" size="7" onchange="s();"/>

    <input type="text" id="tu" name="tu" onchange="g();"/>
    <input type="text" id="tt" name="tt" onchange="g();"/>

    GPA
    <input type="text" id="gpa" />

Body:
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).

That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.

As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?

In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:

var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');

function updateQuotient () {
  var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
  if (!isNaN(result)) {
    resultElement.value = result;
  }
}

dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);

<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">


问:
Filter Pandas dataframe row and replace value in column
I got a big list of phone numbers in all sorts of formats:

```<code>df = pd.DataFrame(
    {'phone': ['0123/12345', '0123-23456', '0123/4455-10', '0123-4455-22'],
     'name': ['A-1', 'B-1', 'C/3', 'D/7']})

  name phone
0 A-1  0123/12345
1 B-1  0123-23456
2 C/3  0123/4455-10
3 D/7  0123-4455-22
</code>```

The formats I want are in rows #0 and #2.

When I concentrate on #1, I tried the following:

```<code>df.loc[(df.phone.str.count('-')==1) &
       (df.phone.str.count('/')==0)].apply(lambda x: x.str.replace('-', '/'))
</code>```

And this does the trick on the number, but unfortunately also on the name column:

```<code>  name phone
1 B/1  0123/23456
</code>```

But the name column must not be changed.

So I have two questions:

How can I filter the row and only change the phone column?

How can I go with #3, where I would want to replace the first occurrence of '-' to '/'?

答:
You can use regex replace (str.replace method) on column phone only:

```<code>df['phone'] = df.phone.str.replace("^(\d+)-(.*)$", r"\1/\2")
df
#  name        phone
#0  A-1   0123/12345
#1  B-1   0123/23456
#2  C/3 0123/4455-10
#3  D/7 0123/4455-22
</code>```

Explanation on the regex:

^(\d+)-(.*)$ matches a string that starts with digits and immediately followed by dash which is the case for row #0 and row #2; With back reference, it replaces the first dash with / and for row #1 and row #3, since they don't match the regex, no modification is applied.

Body:
I got a big list of phone numbers in all sorts of formats:

df = pd.DataFrame(
    {'phone': ['0123/12345', '0123-23456', '0123/4455-10', '0123-4455-22'],
     'name': ['A-1', 'B-1', 'C/3', 'D/7']})

  name phone
0 A-1  0123/12345
1 B-1  0123-23456
2 C/3  0123/4455-10
3 D/7  0123-4455-22

The formats I want are in rows #0 and #2.

When I concentrate on #1, I tried the following:

df.loc[(df.phone.str.count('-')==1) &
       (df.phone.str.count('/')==0)].apply(lambda x: x.str.replace('-', '/'))

And this does the trick on the number, but unfortunately also on the name column:

  name phone
1 B/1  0123/23456

But the name column must not be changed.

So I have two questions:

How can I filter the row and only change the phone column?

How can I go with #3, where I would want to replace the first occurrence of '-' to '/'?

Body:
You can use regex replace (str.replace method) on column phone only:

df['phone'] = df.phone.str.replace("^(\d+)-(.*)$", r"\1/\2")
df
#  name        phone
#0  A-1   0123/12345
#1  B-1   0123/23456
#2  C/3 0123/4455-10
#3  D/7 0123/4455-22

Explanation on the regex:

^(\d+)-(.*)$ matches a string that starts with digits and immediately followed by dash which is the case for row #0 and row #2; With back reference, it replaces the first dash with / and for row #1 and row #3, since they don't match the regex, no modification is applied.


问:
Where do I put SQL in my code when using notepad?
Lets say I have some code where I will be using just javascript, html, and css. I would create an outline like this.

```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script  type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
</head>
<style>

</style>
<script>

</script>
<body>
    <button>Create a new table</button>
</body>
</html>
</code>```

But what I want is when the user clicks a button it can create a table using SQL. My question is do I put that code in the script tags() or create separate tags for the SQL part?

答:
umm, there's a certain amount of knowledge to the MySql part needed.

The MySql commands are normally handled by a language called php. Doing it with javascript is rather exotic I think.

There really are a million online tutorials on php/MySql

https://www.w3schools.com/php/php_mysql_connect.asp

Body:
Lets say I have some code where I will be using just javascript, html, and css. I would create an outline like this.

<!DOCTYPE html>

    <button>Create a new table</button>

But what I want is when the user clicks a button it can create a table using SQL. My question is do I put that code in the script tags() or create separate tags for the SQL part?


问:
QWizard: Confirmation on back button
I've created a wizard by subclassing QWizard, and I created pages of my wizard by subclassing QWizardPage.

I would like to show a confirmation dialog when the user press the Back button, and I want my wizard to not go to the previous page if the user press no on the confirmation dialog.

When clicking Next on a QWizard dialog, the virtual function bool validatePage() is called and allows to return false if we don't want to go to the next page (for example when there is an incomplete field).

However, when pressing Back, I don't know any way to say "Don't go back". The virtual function void cleanupPage() is called (I can ask the user confirmation here), but the Wizard will go back anyway.

Is it possible to do so?

Thanks in advance.

答:
I finally achieve what I wanted (not sure this is the best way...) by disconnecting the back button signal, and connecting it to my custom slot.

```<code>MyWizard::MyWizard(QWidget *parent) : QWizard(parent)
{
   // [...]
   connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(onPageChanged(int)));
}

void MyWizard::onPageChanged(int id)
{
    disconnect(button(BackButton), SIGNAL(clicked(bool)), 0, 0);
    connect(button(BackButton), SIGNAL(clicked(bool)), this, SLOT(onBackButtonClicked()));
}

void MyWizard::onBackButtonClicked()
{
    if (currentId() > Page_Intro && !confirmation(tr("Are you sure you want to go back?")))
        return;
    back();
}
</code>```

Note that if you do the connection/disconnection on the Wizard constructor, it does not work (Qt connect it when you pass the first page).

Title: QWizard: Confirmation on back button

Body:
I finally achieve what I wanted (not sure this is the best way...) by disconnecting the back button signal, and connecting it to my custom slot.

MyWizard::MyWizard(QWidget *parent) : QWizard(parent)
{
   // [...]
   connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(onPageChanged(int)));
}

void MyWizard::onPageChanged(int id)
{
    disconnect(button(BackButton), SIGNAL(clicked(bool)), 0, 0);
    connect(button(BackButton), SIGNAL(clicked(bool)), this, SLOT(onBackButtonClicked()));
}

void MyWizard::onBackButtonClicked()
{
    if (currentId() > Page_Intro && !confirmation(tr("Are you sure you want to go back?")))
        return;
    back();
}

Note that if you do the connection/disconnection on the Wizard constructor, it does not work (Qt connect it when you pass the first page).


问:
Where can I find Android source code online?
Where can I browse the source code for any Android Open Source Project (AOSP) application (for example the Contacts application)? Is the only way to clone the entire source repository for all of AOSP?</p>

答:
I've found a way to get only the Contacts application:

```<code>git clone https://android.googlesource.com/platform/packages/apps/Contacts
</code>```

which is good enough for me for now, but doesn't answer the question of browsing the code on the web.

OwnerDisplayName: J. Pablo Fernández

ContentLicense: CC BY-SA 4.0

Body:
I've found a way to get only the Contacts application:

git clone https://android.googlesource.com/platform/packages/apps/Contacts

which is good enough for me for now, but doesn't answer the question of browsing the code on the web.


问:
go concurrency all goroutines are asleep - deadlock
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

```<code>package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}
</code>```

答:
For the sake of having examples here's a slightly modified version of what @eugenioy submitted.  It allows for the use of an unbuffered channel and the reading of values as they come in instead of at the end like a regular for loop.</p>

```<code>package main

import (
    "fmt"
    "sync"
    "time"
)

func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
    // clear one from the sync group
    defer wg.Done()
    // not needed, unless you wanted to slow down the output
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    // variable names don't have underscores in Go
    intSlice := []int{2, 4}

    counter := make(chan int)

    var wg sync.WaitGroup

    for _, item := range intSlice {
        // add one to the sync group, to mark we should wait for one more
        wg.Add(1)
        go addCount(item, counter, &wg)
    }

    // by wrapping wait and close in a go routine I can start reading the channel before its done, I also don't need to know the size of the
    // slice
    go func() {
        wg.Wait()
        close(counter)
    }()

    for item := range counter {
        fmt.Println(item)
    }
}
</code>```

Body:
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}

Body:
For the sake of having examples here's a slightly modified version of what @eugenioy submitted.  It allows for the use of an unbuffered channel and the reading of values as they come in instead of at the end like a regular for loop.

package main

import (
    "fmt"
    "sync"
    "time"
)

func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
    // clear one from the sync group
    defer wg.Done()
    // not needed, unless you wanted to slow down the output
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    // variable names don't have underscores in Go
    intSlice := []int{2, 4}

    counter := make(chan int)

    var wg sync.WaitGroup

    for _, item := range intSlice {
        // add one to the sync group, to mark we should wait for one more
        wg.Add(1)
        go addCount(item, counter, &wg)
    }

    // by wrapping wait and close in a go routine I can start reading the channel before its done, I also don't need to know the size of the
    // slice
    go func() {
        wg.Wait()
        close(counter)
    }()

    for item := range counter {
        fmt.Println(item)
    }
}


问:
How to make postgres.app db accessible to docker container?
I got postgres.app running locally on my Mac and would like my local docker container to be able to connect to it. How do I best do this?

I found this post that suggests to pass the Docker host’s IP address to a container using the --add-host flag (Host port with DB to Docker container). However, my laptop's IP address changes frequently. Isn't there an easier way of doing this? Isn't there an easy way to open a local port to a container?

答:
From your container, try connecting to hostname docker.for.mac.localhost. For example:

```<code>psql -U my_user docker.for.mac.localhost -U my_user my_database
</code>```

From the docs:

The Mac has a changing IP address (or none if you have no network
  access). From 17.06 onwards our recommendation is to connect to the
  special Mac-only DNS name docker.for.mac.localhost which will resolve
  to the internal IP address used by the host.

Note: this requires Docker for Mac >= 17.06.0-ce-mac18, 2017-06-28

Body:
From your container, try connecting to hostname docker.for.mac.localhost. For example:

psql -U my_user docker.for.mac.localhost -U my_user my_database

From the docs:

The Mac has a changing IP address (or none if you have no network
  access). From 17.06 onwards our recommendation is to connect to the
  special Mac-only DNS name docker.for.mac.localhost which will resolve
  to the internal IP address used by the host.

Note: this requires Docker for Mac >= 17.06.0-ce-mac18, 2017-06-28


问:
how to display multiple images from database to blade view, by Laravel 5.3?
I have a multiple images in "Images" column in DB, and I need to display all Images in:

```<code>@foreach(explode(',', $posts->images) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
    <a href="{{ URL::to('img/offers/'.$images)}}"
       class="portfolio-box">
        <img src="{{ URL::to('img/offers/'.$images)}}"
             class="img-responsive" alt="--">
        <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
            <span class="glyphicon glyphicon-zoom-in"
                  style="font-size: 80px"></span>
            </div>
        </div>
    </a>
</div>
@endforeach
</code>```

but it not working because link show like:

```<code>http://localhost:8000/img/offers/["149939592986Dynamic-Web.png"
</code>```

and next image show like:

```<code>http://localhost:8000/img/offers/"149938949479Static-Web.png"]
</code>```

now, what i do to display all images ?

my column in BD show like an array:

```<code>["149938949418Dynamic-Web.png","149938949479Static-Web.png"]
</code>```

thank you.

答:
The reason your example does not work is because you are exploding a json string. What you will have to do is to simple decode it properly, like this:

```<code>@foreach(json_decode($posts->images, true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
    <a href="{{ URL::to('img/offers/'.$images)}}"
       class="portfolio-box">
        <img src="{{ URL::to('img/offers/'.$images)}}"
             class="img-responsive" alt="--">
        <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
            <span class="glyphicon glyphicon-zoom-in"
                  style="font-size: 80px"></span>
            </div>
        </div>
    </a>
</div>
@endforeach
</code>```

This will loop through all your images and display the correct strings like:

```<code>http://localhost:8000/img/offers/149939592986Dynamic-Web.png
</code>```

Body:
I have a multiple images in "Images" column in DB, and I need to display all Images in:

@foreach(explode(',', $posts->images) as $images)

@endforeach

but it not working because link show like:

http://localhost:8000/img/offers/["149939592986Dynamic-Web.png"

and next image show like:

http://localhost:8000/img/offers/"149938949479Static-Web.png"]

now, what i do to display all images ?

my column in BD show like an array:

["149938949418Dynamic-Web.png","149938949479Static-Web.png"]

thank you.

Body:
The reason your example does not work is because you are exploding a json string. What you will have to do is to simple decode it properly, like this:

@foreach(json_decode($posts->images, true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
    <a href="{{ URL::to('img/offers/'.$images)}}"
       class="portfolio-box">
        <img src="{{ URL::to('img/offers/'.$images)}}"
             class="img-responsive" alt="--">
        <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
            <span class="glyphicon glyphicon-zoom-in"
                  style="font-size: 80px"></span>
            </div>
        </div>
    </a>
</div>
@endforeach

This will loop through all your images and display the correct strings like:

http://localhost:8000/img/offers/149939592986Dynamic-Web.png


问:
How to overwrite method from interface?
I have an interface:

```<code>interface ISqlite
{
     DataTable select(SQLiteDatabase db);
}
</code>```

And realization it:

```<code>public DataTable select(ISqlite s) {

    return s.select(driver);

}
</code>```

As you can see method select is described with DataTable type in return.

How do I overwite this method so that it doesn't return a DataTable, but rather an Array or any other type?

I mean the following:

```<code>public Array select(ISqlite s) {

    return s.select(driver);

}
</code>```

答:
Interfaces were created in order to prevent you from doing just that.

Instead, do this:

```<code>interface ISqliteDatatable
{
     DataTable selectDataTable(SQLiteDatabase db);
}
interface ISqliteArray
{
     Array selectArray(SQLiteDatabase db);
}
</code>```

Then when you make a class, decide which interface to implement based on your needs.

This solution is probably still not completely proper, but we don't know your overall design, so any further corrections would be higher level.

Here's how you would implement both:

```<code>public class example : ISqliteArray : ISqliteDataTable
{

    public DataTable selectDataTable(SQLiteDatabase db)
    {
        // Do stuff and return a datatable
    }

    public Array selectArray(SQLiteDatabase db)
    {
        // Do stuff and return an array
    }
}
</code>```

Title: How to overwrite method from interface?

Body:
I have an interface:

interface ISqlite
{
     DataTable select(SQLiteDatabase db);
}

And realization it:

public DataTable select(ISqlite s) {

    return s.select(driver);

}

As you can see method select is described with DataTable type in return.

How do I overwite this method so that it doesn't return a DataTable, but rather an Array or any other type?

I mean the following:

public Array select(ISqlite s) {

    return s.select(driver);

}

Body:
Interfaces were created in order to prevent you from doing just that.

Instead, do this:

interface ISqliteDatatable
{
     DataTable selectDataTable(SQLiteDatabase db);
}
interface ISqliteArray
{
     Array selectArray(SQLiteDatabase db);
}

Then when you make a class, decide which interface to implement based on your needs.

This solution is probably still not completely proper, but we don't know your overall design, so any further corrections would be higher level.

Here's how you would implement both:

public class example : ISqliteArray : ISqliteDataTable
{

    public DataTable selectDataTable(SQLiteDatabase db)
    {
        // Do stuff and return a datatable
    }

    public Array selectArray(SQLiteDatabase db)
    {
        // Do stuff and return an array
    }
}


问:
How to copy the sheet name to a column on the same sheet?
I am using this code:

```<code>Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function
</code>```

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.

答:
```<code>Function wrksht() as String
  wrksht = ActiveSheet.Name
End function
</code>```

UPDATE

```<code>Function DoIt()
  Dim sh As Worksheet

  For Each sh In ActiveWorkbook.Sheets
    sh.Range("A1") = sh.Name
  Next
End Function
</code>```

Body:
I am using this code:

Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function

I am continuously being thrown

run time error '424' object not found

I have a workbook with several sheets, each having a date on it.

I want to populate the first column on every sheet with its sheet name.

Body:
Function wrksht() as String
  wrksht = ActiveSheet.Name
End function

UPDATE

Function DoIt()
  Dim sh As Worksheet

  For Each sh In ActiveWorkbook.Sheets
    sh.Range("A1") = sh.Name
  Next
End Function


问:
Handling In Webdriver Using Chromeoptions
I am facing the error in chrome which is "You Are Using An Unsupported Command-Line Flag –Ignore-Certificate-Errors. Stability And Security Will Suffer." for my below selenium code.

```<code>Public Sub key()
  Dim selenium As New SeleniumWrapper.WebDriver
  selenium.Start "chrome", "https://google.com/"
selenium.stop
End Sub
</code>```

I have searched the same error solution in below link.

http://www.abodeqa.com/tag/how-to-remove-you-are-using-an-unsupported-command-line-flag-ignore-certificate-errors-stability-and-security-will-suffer/

Please explain how can i apply the answer mention in above link into my VBA code.

答:
I could not find documentation for SeleniumWrapper. So, I assumed that SeleniumWrapper.WebDriver.Start doesn't handle any `ChromeOptions' related arguments.

If the above assumption is true, one cannot apply the given solution in C#.

Instead, you may try the following: (I referenced this)

```<code>Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome

...
...

Public Sub key()

  Dim service As OpenQA.Selenium.Chrome.ChromeDriverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService()

  Dim chromeOptions As New OpenQA.Selenium.Chrome.ChromeOptions()
  chromeOptions.AddExcludedArgument("ignore-certifcate-errors")
  chromeOptions.AddArgument("test-type")

  Dim driver As IWebDriver = New ChromeDriver(service, chromeOptions)
  driver.Navigate().GoToUrl("https://google.com/")

  driver.Quit()

End Sub
</code>```

I added couple lines from my experience running Selenium in C#.

Please provide where SeleniumWrapper with its documentation to determine if one can/cannot set ChromeOptions for SeleniumWrapper.

Body:
I am facing the error in chrome which is "You Are Using An Unsupported Command-Line Flag –Ignore-Certificate-Errors. Stability And Security Will Suffer." for my below selenium code.

Public Sub key()
  Dim selenium As New SeleniumWrapper.WebDriver
  selenium.Start "chrome", "https://google.com/"
selenium.stop
End Sub

I have searched the same error solution in below link.

http://www.abodeqa.com/tag/how-to-remove-you-are-using-an-unsupported-command-line-flag-ignore-certificate-errors-stability-and-security-will-suffer/

Please explain how can i apply the answer mention in above link into my VBA code.

Body:
I could not find documentation for SeleniumWrapper. So, I assumed that SeleniumWrapper.WebDriver.Start doesn't handle any `ChromeOptions' related arguments.

If the above assumption is true, one cannot apply the given solution in C#.

Instead, you may try the following: (I referenced this)

Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome

...
...

Public Sub key()

  Dim service As OpenQA.Selenium.Chrome.ChromeDriverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService()

  Dim chromeOptions As New OpenQA.Selenium.Chrome.ChromeOptions()
  chromeOptions.AddExcludedArgument("ignore-certifcate-errors")
  chromeOptions.AddArgument("test-type")

  Dim driver As IWebDriver = New ChromeDriver(service, chromeOptions)
  driver.Navigate().GoToUrl("https://google.com/")

  driver.Quit()

End Sub

I added couple lines from my experience running Selenium in C#.

Please provide where SeleniumWrapper with its documentation to determine if one can/cannot set ChromeOptions for SeleniumWrapper.


问:
Why isn’t my object collected by an autorelease pool?
I wrote an simple demo

```<code>@implementation A

- (void)a{
    NSLog(@"%@",url);
}

-(id)init{
    self = [super init];
    url = [NSURL URLWithString:@"http://xxx.com"];
    return self;
}
@end

A *a = [A new];
while (YES) {
    [NSThread sleepForTimeInterval:0.5];
    [a a];
}
</code>```

but seems it will keep running and never crash.
so when will an autorelease object be releaed?

答:
What do you expect to happen?

You only have one NSURL instance floating about.

The implementation details of NSLog() are just that; implementation details.  It is equally as likely that NSLog() creates its own autorelease pool as it is that NSLog() special cases "%@" such that it just logs the description of the passed object; nothing allocated in the pool.

How are you determining whether or not a crash should happen in the first place?  Given a 1/2 second pause, even if it were to allocate 128 bytes per pass, you'd be looking at -- what -- a few years, nearly a decade?, before it allocates 2GB of memory?

Body:
I wrote an simple demo

@implementation A

- (void)a{
    NSLog(@"%@",url);
}

-(id)init{
    self = [super init];
    url = [NSURL URLWithString:@"http://xxx.com"];
    return self;
}
@end

A *a = [A new];
while (YES) {
    [NSThread sleepForTimeInterval:0.5];
    [a a];
}

but seems it will keep running and never crash.
so when will an autorelease object be releaed?


问:
What is the equivalent of ObjectContext.ApplyCurrentValues for EF
I am using this </p>

```<code> _obj.Entry(update).CurrentValues.SetValues(update);
</code>```

<p>but it is not working not updating </p>

答:
There is no direct equivalent. The closest is something like this:

```<code>var existing = context.Set<YourEntityType>().Find(update.Id); // pass your entity PK
if (existing == null)
    throw new InvalidOperationException(); // something is wrong
context.Entry(existing).CurrentValues.SetValues(update);
</code>```

Basically you locate the existing entity with Find method, which will either locate it in the local cache or retrieve it from the database. In both cases you will end up with entity instance attached to the context. Then you update that instance with the values from the passed object.

Body:
I am using this

 _obj.Entry(update).CurrentValues.SetValues(update);

but it is not working not updating

Body:
There is no direct equivalent. The closest is something like this:

var existing = context.Set<YourEntityType>().Find(update.Id); // pass your entity PK
if (existing == null)
    throw new InvalidOperationException(); // something is wrong
context.Entry(existing).CurrentValues.SetValues(update);

Basically you locate the existing entity with Find method, which will either locate it in the local cache or retrieve it from the database. In both cases you will end up with entity instance attached to the context. Then you update that instance with the values from the passed object.


问:
SQL: Add a new column based on CASE expression and looking up values from another table
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

```<code>ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)
</code>```

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

答:
Do this in two steps:

```<code>ALTER TABLE Portfolio.Trades ADD Multiplier decimal(7,3);

UPDATE T
    SET Multiplier = (CASE WHEN T.Type = 'Equity' Then 1
                           WHEN T.Type = 'Corp' Then 0.1
                           WHEN T.Type = 'Option' Then 100
                           ELSE (SELECT CS.ContractSize
                                 FROM Portfolio.ContractSize CS
                                 WHERE T.Identifier = CS.ContractSize)
                       END)
    FROM Portfolio.Trades T;
</code>```

I am guessing that the ON/correlation condition is incorrect.  If it is correct, you can just do:

```<code>UPDATE T
    SET Multiplier = (CASE WHEN T.Type = 'Equity' Then 1
                           WHEN T.Type = 'Corp' Then 0.1
                           WHEN T.Type = 'Option' Then 100
                           ELSE T.Identifier)
                       END)
    FROM Portfolio.Trades T;
</code>```

Or even just add this as a computed column.

Body:
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

Body:
Do this in two steps:

ALTER TABLE Portfolio.Trades ADD Multiplier decimal(7,3);

UPDATE T
    SET Multiplier = (CASE WHEN T.Type = 'Equity' Then 1
                           WHEN T.Type = 'Corp' Then 0.1
                           WHEN T.Type = 'Option' Then 100
                           ELSE (SELECT CS.ContractSize
                                 FROM Portfolio.ContractSize CS
                                 WHERE T.Identifier = CS.ContractSize)
                       END)
    FROM Portfolio.Trades T;

I am guessing that the ON/correlation condition is incorrect.  If it is correct, you can just do:

UPDATE T
    SET Multiplier = (CASE WHEN T.Type = 'Equity' Then 1
                           WHEN T.Type = 'Corp' Then 0.1
                           WHEN T.Type = 'Option' Then 100
                           ELSE T.Identifier)
                       END)
    FROM Portfolio.Trades T;

Or even just add this as a computed column.


问:
data not being written to csv with Apache Commons
I am trying to run the following code with apache commons, in order to write it a to csv file.  The print statement for the finalResult array shows that it has what I wanted populated in it.  It just does not send the data inside to the designated csv for some reason.

```<code>public void handle(ActionEvent runButton) {
    String csvFile = (userHomeFolder + "/" + fileName.getText() + ".csv");
    FileWriter writer = new FileWriter(csvFile);
    try {

        final Object [] FILE_HEADER = columnHeaders.toArray();
        int modval = 2;
        final String NEW_LINE_SEPARATOR = "\n";
        FileWriter fileWriter;
        CSVPrinter csvFilePrinter;
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        List rowResult = new ArrayList();

        fileWriter = new FileWriter(fileName.getText());
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        try {

            //CREATE CSV FILE HEADER
            System.out.println("File header: " + FILE_HEADER);
            csvFilePrinter.printRecord(FILE_HEADER);

            for(int y = 0; y < finalResult.size(); y++) {

                if(y % modval == 0) {
                    rowResult.add(finalResult.get(y));
                    csvFilePrinter.printRecord(rowResult);
                    System.out.println(rowResult);
                    rowResult.clear();
                }else {
                    //this means it is not the last value in the row
                    rowResult.add(finalResult.get(y));
                    System.out.println("fr: " + finalResult.get(y));
                }

            }

        } catch (Exception e) {
            System.out.println("Error in csvFileWriter");
            e.printStackTrace();

        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e ) {
                System.out.println("Error while flushing/closing");
            }
        }
    }
}
    //below catches any errors for any of the above work
    catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
   }
</code>```

答:
Why do you need dozens of lines of code and a third-party library to do what can be done with printf in probably 5 lines? Create a PrintWriter and write with printf. Done.

```<code>try (PrintWriter pw = new PrintWriter(csvFile)) {
    pw.printf("%s\n", FILE_HEADER);

    for(int i = 0; i < finalResult.size(); i+=2) { // no need to modulo
        pw.printf("%s\n", finalResult.get(i)); // no idea what type finalResult.get(i) is, format it if you need to
    }
}
</code>```

You shouldn't be creating csvFile by hard-coding the file separator /, but that's another issue.

Body:
I am trying to run the following code with apache commons, in order to write it a to csv file.  The print statement for the finalResult array shows that it has what I wanted populated in it.  It just does not send the data inside to the designated csv for some reason.

public void handle(ActionEvent runButton) {
    String csvFile = (userHomeFolder + "/" + fileName.getText() + ".csv");
    FileWriter writer = new FileWriter(csvFile);
    try {

        final Object [] FILE_HEADER = columnHeaders.toArray();
        int modval = 2;
        final String NEW_LINE_SEPARATOR = "\n";
        FileWriter fileWriter;
        CSVPrinter csvFilePrinter;
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        List rowResult = new ArrayList();

        fileWriter = new FileWriter(fileName.getText());
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        try {

            //CREATE CSV FILE HEADER
            System.out.println("File header: " + FILE_HEADER);
            csvFilePrinter.printRecord(FILE_HEADER);

            for(int y = 0; y < finalResult.size(); y++) {

                if(y % modval == 0) {
                    rowResult.add(finalResult.get(y));
                    csvFilePrinter.printRecord(rowResult);
                    System.out.println(rowResult);
                    rowResult.clear();
                }else {
                    //this means it is not the last value in the row
                    rowResult.add(finalResult.get(y));
                    System.out.println("fr: " + finalResult.get(y));
                }

            }

        } catch (Exception e) {
            System.out.println("Error in csvFileWriter");
            e.printStackTrace();

        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e ) {
                System.out.println("Error while flushing/closing");
            }
        }
    }
}
    //below catches any errors for any of the above work
    catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
   }

Body:
Why do you need dozens of lines of code and a third-party library to do what can be done with printf in probably 5 lines? Create a PrintWriter and write with printf. Done.

try (PrintWriter pw = new PrintWriter(csvFile)) {
    pw.printf("%s\n", FILE_HEADER);

    for(int i = 0; i < finalResult.size(); i+=2) { // no need to modulo
        pw.printf("%s\n", finalResult.get(i)); // no idea what type finalResult.get(i) is, format it if you need to
    }
}

You shouldn't be creating csvFile by hard-coding the file separator /, but that's another issue.


问:
Alamofire cache issue
I'm running into a problem with Alamofire where I'm getting the same response for a different request. I use the following method to request:

```<code>        self.ephemeralManager?.request("myurladdress.com", headers: headers)
            .authenticate(user: username, password: password)
            .responseJSON { response in
                print(response)
            }
</code>```

Here is the SessionManager:

```<code>        let configuration = URLSessionConfiguration.ephemeral
        configuration.urlCache = nil
        ephemeralManager = Alamofire.SessionManager(configuration: configuration)
</code>```

When I make the request the first time it works as expected. When I make the request again shortly after, with a different username and password, I get the response data from the previous request. If I restart the app or if I wait a while, the request works as expected.

I assume this is a caching issue but all attempts to clear the cache before I make the request or to turn off caching have failed.

Is there something that I'm missing? I have used Alamofire quite a bit and have never run into this issue.

Alamofire version: 4.1
Xcode version: 8.3.3
Swift version: 3.1
Platform(s) running Alamofire: iOS
macOS version running Xcode: 10.12.5

答:
You can clear the cache before making the alamofire request.

```<code>NSURLCache.sharedURLCache().removeAllCachedResponses()
</code>```

after executing this command then call alamofire request.

Title: Alamofire cache issue

Body:
I'm running into a problem with Alamofire where I'm getting the same response for a different request. I use the following method to request:

        self.ephemeralManager?.request("myurladdress.com", headers: headers)
            .authenticate(user: username, password: password)
            .responseJSON { response in
                print(response)
            }

Here is the SessionManager:

        let configuration = URLSessionConfiguration.ephemeral
        configuration.urlCache = nil
        ephemeralManager = Alamofire.SessionManager(configuration: configuration)

When I make the request the first time it works as expected. When I make the request again shortly after, with a different username and password, I get the response data from the previous request. If I restart the app or if I wait a while, the request works as expected.

I assume this is a caching issue but all attempts to clear the cache before I make the request or to turn off caching have failed.

Is there something that I'm missing? I have used Alamofire quite a bit and have never run into this issue.

Alamofire version: 4.1
Xcode version: 8.3.3
Swift version: 3.1
Platform(s) running Alamofire: iOS
macOS version running Xcode: 10.12.5

Body:
You can clear the cache before making the alamofire request.

NSURLCache.sharedURLCache().removeAllCachedResponses()

after executing this command then call alamofire request.


问:
Can't access ArtifactStagingDirectory variable in MSBuild
During my build process I'm trying to copy a folder to the artifacts folder (\myserver\d$\TFBuild-Agent01\66\a).

So I put this in the .csproj file:

<Target Name="BeforeBuild">
  <Exec
    Command="xcopy.exe  Databases "$(Build.ArtifactStagingDirectory)\Databases" /i /e /y /d" />
</Target>
```

<p>This gets me </p>

<blockquote>
  <p>Error MSB4184: The expression """.ArtifactStagingDirectory" cannot be evaluated. Method 'System.String.ArtifactStagingDirectory' not found*</p>
</blockquote>

<p>Everything I can find online says that $(Build.ArtifactStagingDirectory) is the way to do it.  But it doesn't work.</p>

<p>Building with Visual Studio 2015 on TFS 2015</p>

<p>This doesn't work either:</p>

```<Exec
Command="xcopy.exe  Databases "$($Env:BUILD_ARTIFACTSTAGINGDIRECTORY)\Databases" /i /e /y /d" />
```

<blockquote>
  <p>The expression "$Env:BUILD_ARTIFACTSTAGINGDIRECTORY" cannot be evaluated.*</p>
</blockquote>

<p>This doesn't error, but it looks like %BUILD_ARTIFACTSTAGINGDIRECTORY% gets replaced as an empty string:</p>

``` <Exec Command="xcopy.exe  Databases "%BUILD_ARTIFACTSTAGINGDIRECTORY%\Databases" /i /e /y /d" />
```

答:
OK, I guess that because I'm using Visual Studio to build my solution, I can't access $(Build.StagingDirectory) from the .csproj.  However, it's being passed on the command line to the "Visual Studio Build" build step as a property:

```<code>/p:OutDir="$(Build.StagingDirectory)"
</code>```

So that can be accessed by doing

```<code><Exec Command="xcopy.exe  Databases "$(OutDir)\Databases" /i /e /y /d" />
</code>```

Body:
During my build process I'm trying to copy a folder to the artifacts folder (\myserver\d$\TFBuild-Agent01\66\a).

So I put this in the .csproj file:

<Target Name="BeforeBuild">
  <Exec
    Command="xcopy.exe  Databases "$(Build.ArtifactStagingDirectory)\Databases" /i /e /y /d" />
</Target>

This gets me

Error MSB4184: The expression """.ArtifactStagingDirectory" cannot be evaluated. Method 'System.String.ArtifactStagingDirectory' not found*

Everything I can find online says that $(Build.ArtifactStagingDirectory) is the way to do it.  But it doesn't work.

Building with Visual Studio 2015 on TFS 2015

This doesn't work either:

<Exec
Command="xcopy.exe  Databases "$($Env:BUILD_ARTIFACTSTAGINGDIRECTORY)\Databases" /i /e /y /d" />

The expression "$Env:BUILD_ARTIFACTSTAGINGDIRECTORY" cannot be evaluated.*

This doesn't error, but it looks like %BUILD_ARTIFACTSTAGINGDIRECTORY% gets replaced as an empty string:

 <Exec Command="xcopy.exe  Databases "%BUILD_ARTIFACTSTAGINGDIRECTORY%\Databases" /i /e /y /d" />

Body:
OK, I guess that because I'm using Visual Studio to build my solution, I can't access $(Build.StagingDirectory) from the .csproj.  However, it's being passed on the command line to the "Visual Studio Build" build step as a property:

/p:OutDir="$(Build.StagingDirectory)"

So that can be accessed by doing

<Exec Command="xcopy.exe  Databases &quot;$(OutDir)\Databases&quot; /i /e /y /d" />


问:
Chrome Headless: Get DOM of only visible nodes
I've been looking for a way for Chrome Headless to output only the visible
DOM nodes as a tree.

I'm using the code below to output the entire DOM, but this includes invisible elements.

```<code>Runtime.evaluate({expression: 'document.documentElement.outerHTML'})
</code>```

Is there a way to prune all the invisible nodes?

答:
I'm not sure about doing this as a tree. For that, I think you'd have to get all the nodes and then walk the tree and remove non-visible ones yourself.

This will return a node list.

```<code>Runtime.evaluate({expression: 'document.querySelectorAll("*:visible")'})
</code>```

Body:
I've been looking for a way for Chrome Headless to output only the visible
DOM nodes as a tree.

I'm using the code below to output the entire DOM, but this includes invisible elements.

Runtime.evaluate({expression: 'document.documentElement.outerHTML'})

Is there a way to prune all the invisible nodes?

Body:
I'm not sure about doing this as a tree. For that, I think you'd have to get all the nodes and then walk the tree and remove non-visible ones yourself.

This will return a node list.

Runtime.evaluate({expression: 'document.querySelectorAll("*:visible")'})


问:
Android - Changing item title in bottom navigation bar
I have 2 fragments between which I can navigate with a bottom navigation bar. I also have an overflow menu with an item which shows an edittext dialog.

I want that when I write and validate text in the dialog, the currently displayed fragment's item on the nav bar changes of title. I don't know how to change text of a specific item.

I hope my question is understandable. I have been searching through SO but I didn't find any corresponding answers.

答:
Without any code I can only guess that you setup a ViewPager with the TabLayout method yourTabLayout.setupWithViewPager(yourViewPagerAdapter);.

If it is so, you can simply set a title using
yourTabLayout.getTabAt(position).setText(yourTitle); where position is 0 for first tab and 1 for second tab.
If you post some code I can try to specify my answer on your code and the way you are adding the fragments to your activity.


问:
Efficient way to run a function over the columns of a pandas Dataframe?
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

```<code>import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])
</code>```

And I have query. Query is a Pandas Series.

```<code>query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])
</code>```

Now I want to run the cosine function over every column in corpus and the query.

```<code>for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))
</code>```

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

答:
You could also use the definition of cosine and implement yourself

pandas

```<code>corpus.T.dot(query) / (corpus ** 2).sum() ** .5 / (query ** 2).sum() ** .5

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64
</code>```

numpy

```<code>c = corpus.values
q = query.values

r = c.T.dot(q) / (c ** 2).sum(0) ** .5 / (q ** 2).sum() ** .5

pd.Series(r, corpus.columns)

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64
</code>```

with @Divakar's suggestion

np.einsum

```<code>c = corpus.values
q = query.values

r = (
        np.einsum('ji,j->i', c, q) /
        np.einsum('ij,ij->j', c, c) ** .5 /
        np.einsum('i,i', q, q) ** .5
    )

pd.Series(r, corpus.columns)

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64
</code>```

Body:
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])

And I have query. Query is a Pandas Series.

query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])

Now I want to run the cosine function over every column in corpus and the query.

for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

Body:
You could also use the definition of cosine and implement yourself

pandas

corpus.T.dot(query) / (corpus ** 2).sum() ** .5 / (query ** 2).sum() ** .5

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64

numpy

c = corpus.values
q = query.values

r = c.T.dot(q) / (c ** 2).sum(0) ** .5 / (q ** 2).sum() ** .5

pd.Series(r, corpus.columns)

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64

with @Divakar's suggestion

np.einsum

c = corpus.values
q = query.values

r = (
        np.einsum('ji,j->i', c, q) /
        np.einsum('ij,ij->j', c, c) ** .5 /
        np.einsum('i,i', q, q) ** .5
    )

pd.Series(r, corpus.columns)

d1    0.980581
d2    0.707107
d3    0.288675
d4    0.801784
d5    0.500000
d6    0.894315
dtype: float64


问:
How to escape quotations marks in a hyperlink
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

```<code>."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".
</code>```

答:
If you want to put your HTML code in the echo, you can just regard these HTML code as string and use . to connect them together with your phone variables.</p>

```<code>echo "<a href='imageInfo.php?id=".$image_id."'>LINK</a>";
</code>```

Body:
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".

Body:
If you want to put your HTML code in the echo, you can just regard these HTML code as string and use . to connect them together with your phone variables.

echo "<a href='imageInfo.php?id=".$image_id."'>LINK</a>";


问:
Injecting service into controller throws error
I am unable to inject service into controller. I was able to execute a similar code a year ago and it worked but this time I am having a hard luck.

app.js

```<code>'use strict';
var app = angular.module('product', [
  "ngRoute",
]);
</code>```

main.ctrl.js

```<code>'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);
</code>```

srv.js

```<code>app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});
</code>```

index.html

```<code><!--JS-->
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<!--APP-->
<script type="text/javascript" src="app/app.js"></script>
<!-- ROUTE -->
<script type="text/javascript" src="bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="app/routes/app.route.js"></script>
<!-- SERVICE -->
<script type="text/javascript" src="app/services/srv.js"></script>
<!--CONTROLLER-->
<script type="text/javascript" src="app/controllers/main.ctrl.js"></script>
</code>```

console error

```<code>angular.js:14362
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)
</code>```

Please help.

答:
The only scope you can inject in a service is $rootScope (but given your code, I'm not sure you need a scope at all in the service). Also, you'll probably want to add the service names as strings for minification:

```<code>app.service("srv", ['$http', '$rootScope', function ($http, $rootScope) {
    // ...
}]);
</code>```

Body:
I am unable to inject service into controller. I was able to execute a similar code a year ago and it worked but this time I am having a hard luck.

app.js

'use strict';
var app = angular.module('product', [
  "ngRoute",
]);

main.ctrl.js

'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);

srv.js

app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});

index.html

console error

angular.js:14362
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)

Please help.

Body:
The only scope you can inject in a service is $rootScope (but given your code, I'm not sure you need a scope at all in the service). Also, you'll probably want to add the service names as strings for minification:

app.service("srv", ['$http', '$rootScope', function ($http, $rootScope) {
    // ...
}]);


问:
How to hide control in repeater in asp.net throught java script
How to hide control in repeater in asp.net throught java script</p>

答:
i guess u want to hide your primary key. jusst put this in your repeater</p>

```<code><asp:HiddenField ID="whatever" runat="server" text="any value"/>
or
<... style="display:none;" />
</code>```

Body:
i guess u want to hide your primary key. jusst put this in your repeater

<asp:HiddenField ID="whatever" runat="server" text="any value"/>
or
<... style="display:none;" />


问:
Data transfer from Hive to Google Storage/Big Query
I have some Hive tables in an on-premise hadoop cluster.

I need to transfer the tables to BigQuery in google cloud.

Can you suggest any google tools or any open source tools for the data transfer?

Thanks in advance

答:
BigQuery can import Avro files.

This means you can do something like INSERT overwrite table target_avro_hive_table SELECT * FROM source_hive_table;

You can then load the underlying .avro files into BigQuery via the bq command line tool or using the console UI:

bq load --source_format=AVRO your_dataset.something something.avro


问:
Inputting correct argument won't allow me to break out of while loop
Why can't I break out of the first while loop when I type in joe or Joe?

```<code>joe = ''
password = ''
while joe != 'Joe' or 'joe':
    print('Who are you?')
    joe = input()
while password != 'swordfish' or 'Swordfish':
    if joe == 'joe' or 'Joe':
        print('What is the password? (Hint: its a fish)')
        password = input()

if joe == 'Joe' or 'joe' and password == 'swordfish' or 'Swordfish':
    print('Access Granted')
else:
    print('Access Denied')
</code>```

答:
Try this:</p>

```<code>val = ''
password = ''
while True:
    print('Who are you?')
    val = input()

    if val.lower() == 'joe':
        break
</code>```

Body:
Why can't I break out of the first while loop when I type in joe or Joe?

joe = ''
password = ''
while joe != 'Joe' or 'joe':
    print('Who are you?')
    joe = input()
while password != 'swordfish' or 'Swordfish':
    if joe == 'joe' or 'Joe':
        print('What is the password? (Hint: its a fish)')
        password = input()

if joe == 'Joe' or 'joe' and password == 'swordfish' or 'Swordfish':
    print('Access Granted')
else:
    print('Access Denied')

Body:
Try this:

val = ''
password = ''
while True:
    print('Who are you?')
    val = input()

    if val.lower() == 'joe':
        break


问:
Migrate Google App Engine project to newer version (with Eclipse)
I have a Google Web Toolkit (GWT) application (Java) that is running on Google App Engine. The app is running fine, but i haven't touched the code in a while. Now i need to modify some things, but i can't get Eclipse/AppEngine to deploy the project any more.
I have reinstalled Eclipse, downloaded and installed tge GWT and Google Cloud Platfrom plugins. And the Cloud SDK.

I'm using Eclipse Mars/2 but i am willing to do this from command line of necessary.

My project is now GWT-compiling fine and it runs locally with the development server.

What i fail to do is get the link up with my existing AppEngine project.
The Google Cloud Platform button only proposes "Create New Project" and the "Deploy to App Engine Standard" option is greyed out.
What do i need to configure to link the GWT app to my existing AppEngine project and deploy?

答: If you've installed the Cloud Tools for Eclipse, you should be able to right-click on the project and select Configure > Convert to App Engine Standard Project.  Basically that removes traces of the older GPE configuration and installs the App Engine Standard facet and configures the App Engine runtime libraries.


问:
invoke-webrequest , New-Object -ComObject "InternetExplorer.Application and New-Object net.webclient
i am trying to create task scheduler to get an embed link from a website every hour and i am using powershell to retrieve the info from web.

```<code> $ie = New-Object -ComObject "InternetExplorer.Application"
$ie.navigate("https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6"
while($ie.Busy) {start-sleep -Milliseconds 1000}
$doc = $ie.document.body.getElementsByClassName("formlink") | select href
</code>```

this can help me to get the info.  But this must be in UI. Will failed if run as backend (task scheduler)

```<code>$test = Invoke-WebRequest -Uri https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6
$test.ParsedHtml.body

#or

$test.ParsedHtml.all
</code>```

Invoke-webrequest didnot show to piece if info i looking. the string is in outerHTML. The Classname called Formlink only be found in via "
New-Object -ComObject "InternetExplorer.Application" .

```<code>$webclient = New-Object net.webclient
$webclient.DownloadString("https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6")
</code>```

Same goes to net.webclient

Why is that so??

the info i need is in outerHTML
 with New-Object -ComObject "InternetExplorer.Application"

```<code><td title="" class="vt" style="direction: ltr;" colspan="1"
                           data-original-title=""><a class="linked formlink" href="u_event.do?sys_id=7435d8a0db3b36c020fffd051d961919&sysparm_record_target=incident&sysparm_record_row=1&sy
                           sparm_record_rows=1&sysparm_record_list=123TEXTQUERY321%253Db096b923-92c5-47ad-9a7c-1657847970a6">INC18701854</a></td>
</code>```

===============================
Update to @Jason Boyd : Tried with each request header, it still does not have the output

```<code>User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)

X-P2P-PeerDist: Version=1.1

Accept-Encoding: gzip, deflate, peerdist

Connection: Keep-Alive

Accept: */*

Host: servicenow.xxx.com

X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0

Cache-Control: no-cache

Accept-Language: en-US, en; q=0.8, zh-Hans-SG; q=0.5, zh-Hans; q=0.3
</code>```

And there is one thing, when running

```<code>Invoke-WebRequest -Uri https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6
</code>```

IE didnt open up the full link, it direct to the homepage. https://servicenow.xxx.com/navpage.do

Notice that it has iframe ( same url all page) in the source code.

What else can i try ??

答:
The only difference between a request sent by IE and a request sent with Invoke-WebRequest would be the request headers. My guess is that the site in question responds differently based on the headers. The most likely suspect, I think, is the user-agent header. I would start by investigating what happens if you change the user-agent header sent by PowerShell to the same value as the user-agent header sent by IE. That command would look something like this:

```<code>$YourIEUserAgentHeader = "Put IE's user-agent header here"
Invoke-WebRequest `
    -Uri https://servicenow.dhl.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6 `
    -Headers @{ 'user-agent' = $YourIEUserAgentHeader }
</code>```

If that does not work I would check each of the other headers sent by IE. Your URL, servicenow.dhl.com, does not resolve for me so I cannot test it myself.

Body:
i am trying to create task scheduler to get an embed link from a website every hour and i am using powershell to retrieve the info from web.

 $ie = New-Object -ComObject "InternetExplorer.Application"
$ie.navigate("https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6"
while($ie.Busy) {start-sleep -Milliseconds 1000}
$doc = $ie.document.body.getElementsByClassName("formlink") | select href

this can help me to get the info.  But this must be in UI. Will failed if run as backend (task scheduler)

$test = Invoke-WebRequest -Uri https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6
$test.ParsedHtml.body

#or

$test.ParsedHtml.all

Invoke-webrequest didnot show to piece if info i looking. the string is in outerHTML. The Classname called Formlink only be found in via "
New-Object -ComObject "InternetExplorer.Application" .

$webclient = New-Object net.webclient
$webclient.DownloadString("https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6")

Same goes to net.webclient

Why is that so??

the info i need is in outerHTML
 with New-Object -ComObject "InternetExplorer.Application"

INC18701854

===============================
Update to @Jason Boyd : Tried with each request header, it still does not have the output

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)

X-P2P-PeerDist: Version=1.1

Accept-Encoding: gzip, deflate, peerdist

Connection: Keep-Alive

Accept: */*

Host: servicenow.xxx.com

X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0

Cache-Control: no-cache

Accept-Language: en-US, en; q=0.8, zh-Hans-SG; q=0.5, zh-Hans; q=0.3

And there is one thing, when running

Invoke-WebRequest -Uri https://servicenow.xxx.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6

IE didnt open up the full link, it direct to the homepage. https://servicenow.xxx.com/navpage.do

Notice that it has iframe ( same url all page) in the source code.

What else can i try ??

Body:
The only difference between a request sent by IE and a request sent with Invoke-WebRequest would be the request headers. My guess is that the site in question responds differently based on the headers. The most likely suspect, I think, is the user-agent header. I would start by investigating what happens if you change the user-agent header sent by PowerShell to the same value as the user-agent header sent by IE. That command would look something like this:

$YourIEUserAgentHeader = "Put IE's user-agent header here"
Invoke-WebRequest `
    -Uri https://servicenow.dhl.com/textsearch.do?sysparm_search=b096b923-92c5-47ad-9a7c-1657847970a6 `
    -Headers @{ 'user-agent' = $YourIEUserAgentHeader }

If that does not work I would check each of the other headers sent by IE. Your URL, servicenow.dhl.com, does not resolve for me so I cannot test it myself.


问:
Python Django and Celery periodictasks
I have a personal website that I want to track the price of bitcoin but I want the code to run every five minutes in the back end of the website.

I am very new to Celery so I do not know much of what I am doing. That being said, I have updated my installed_apps, I have imported djcelery and I have done all of the updates to the settings page.

I set up a periodic task through the admin website because it looked pretty straight forward but I have been unable to run the code automatically despite my function being an option as a task.

I am pretty stuck here and any help would be awesome. Thanks.

```<code>def bitcoin():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    request = Request(url)
    response = urlopen(request)
    the_page = response.read()
    data = json.loads(the_page)
    btc_price = data['bpi']['USD']['rate']
    print('According to CoinDesk, the price of bitcoin is: ' +
    str(btc_price))
</code>```

答:
You can checkout the Django celery cron schedules documentation which has a couple examples of creating scheduled tasks.

Below is a trivial example from their docs:

```<code>from celery.schedules import crontab

app.conf.beat_schedule = {
    # Executes every Monday morning at 7:30 a.m.
    'add-every-monday-morning': {
        'task': 'tasks.add',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16),
    },
}
</code>```

Title: Python Django and Celery periodictasks

Body:
I have a personal website that I want to track the price of bitcoin but I want the code to run every five minutes in the back end of the website.

I am very new to Celery so I do not know much of what I am doing. That being said, I have updated my installed_apps, I have imported djcelery and I have done all of the updates to the settings page.

I set up a periodic task through the admin website because it looked pretty straight forward but I have been unable to run the code automatically despite my function being an option as a task.

I am pretty stuck here and any help would be awesome. Thanks.

def bitcoin():
    url = "https://api.coindesk.com/v1/bpi/currentprice.json"
    request = Request(url)
    response = urlopen(request)
    the_page = response.read()
    data = json.loads(the_page)
    btc_price = data['bpi']['USD']['rate']
    print('According to CoinDesk, the price of bitcoin is: ' +
    str(btc_price))

Body:
You can checkout the Django celery cron schedules documentation which has a couple examples of creating scheduled tasks.

Below is a trivial example from their docs:

from celery.schedules import crontab

app.conf.beat_schedule = {
    # Executes every Monday morning at 7:30 a.m.
    'add-every-monday-morning': {
        'task': 'tasks.add',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16),
    },
}


问:
Train a text model to predict true or false
So I am new to the whole machine learning topic but I think I have an interesting problem to solve. I basically just want to know if a sentence conforms to TRUE or FALSE

Here a some sample sentences:

Yes this is me -> TRUE

This was me -> TRUE

Yes true -> TRUE

This was not me -> FALSE

....

Now I would need some hints how I can successfully train a model in e.g. Keras, Caffe or other tools and what kind of principal I should follow.

Thanks for any hints

Update

So from what I understood I need to do natural language classification. I would need to create 2 classes and get the probability for each of the classes back.

Could something like https://github.com/Russell91/nlpcaffe be useful?

答:
If my understanding is correct, you want to categorize various kinds of responses into true/false, which are perhaps responses to questions as part of a conversation.

For this scenario, you should be creating/having a dataset with a large number of examples for both true and false classes and train a binary text classifier. You can read up on SVM and Naive Bayes which are very good for text classification and easily implementable using Scikit-Learn.


问:
How to stub a method that is called in initialize method
I want to stub a method that is called in initialize method.

There is a class Company like this:

```<code>class Company
  def initialize(code: code, driver: driver)
    @driver = driver
    @code = code
    navigate_to_search_result
  end

  def navigate_to_search_result
    # do something
  end
end
</code>```

And I want to stub the method navigate_to_search_result.

```<code>before(:each) do
  company = Company.new(code: 7220, driver: Selenium::WebDriver.for(:phantomjs))
  allow(company).to receive(:navigate_to_search_result){ true }
end
</code>```

But this code fails because navigate_to_search_result is already executed by initializing.

How can I stub method like this?

Body:
I want to stub a method that is called in initialize method.

There is a class Company like this:

class Company
  def initialize(code: code, driver: driver)
    @driver = driver
    @code = code
    navigate_to_search_result
  end

  def navigate_to_search_result
    # do something
  end
end

And I want to stub the method navigate_to_search_result.

before(:each) do
  company = Company.new(code: 7220, driver: Selenium::WebDriver.for(:phantomjs))
  allow(company).to receive(:navigate_to_search_result){ true }
end

But this code fails because navigate_to_search_result is already executed by initializing.

How can I stub method like this?


问:
select all checkboxes of a form
In my rails application, i am displaying some records. I am using pagination for records..
i have a javascript function to select all the checkboxes associated with a record..But it selects checkboxes of only current page. I want to have a feature where i can select all the checboxes of current page and then move to next page selec there and then submit all of them together.</p>

答:
I'd say hopping between pages and selecting everything is way too tedious and extremely error prone.

Have your "Check all" function submit something like a yourform[check_all]=true parameter to your controller (via ajax or plain HTTP POST) and have your controller handle the requested action on all relevant records.

Title: select all checkboxes of a form


问:
Append element from another page?
Given this HTML:

index.html:

```<code><div class="tile" data-tilename="test">
    <div class="tileHeader">Tile Name</div>
</div>
</code>```

tile-content.html:

```<code><div id="test-tile" class="tileContent">
       <!-- lots of stuff here. -->
</div>
</code>```

How can I arrive at the following?

```<code><div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div class="tileContent">
       //lots of stuff here.
    </div>
</div>
</code>```

Currently all these are created dynamically, so here is my current code:

```<code>let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('<div>').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);
</code>```

The last two lines above were inspired by this solution.  Unfortunately it adds an extra
 which I would like to avoid:

```<code><div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div> <!-- I don't want this -->
        <div class="tileContent">
           <!-- lots of stuff here. -->
        </div>
    <div>
</div>
</code>```

How can I arrive at the desired solution?

There are a couple similar questions, but none that I found have solutions and my situation is slightly different (dynamically created elements).

答:
You are telling it to give that extra div on this line:

```<code>let $elTileContent = $('<div>).load('tile-content.html #' + tile.name + '-tile')
</code>```

You would need to do the load on the element with the tile class first and then duse the .prepend instead of append for the header div element so it stacks above the loaded content div.

Title: Append element from another page?

Body:
Given this HTML:

index.html:

Tile Name

tile-content.html:

How can I arrive at the following?

Tile Name

       //lots of stuff here.

Currently all these are created dynamically, so here is my current code:

let $elTile = $('
', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('
', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('
').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);

The last two lines above were inspired by this solution.  Unfortunately it adds an extra
 which I would like to avoid:

Tile Name

How can I arrive at the desired solution?

There are a couple similar questions, but none that I found have solutions and my situation is slightly different (dynamically created elements).

Body:
You are telling it to give that extra div on this line:

let $elTileContent = $('<div>).load('tile-content.html #' + tile.name + '-tile')

You would need to do the load on the element with the tile class first and then duse the .prepend instead of append for the header div element so it stacks above the loaded content div.


问:
Hyperledger Fabric Bluemix cp-web us.blockchain.ibm.com.cert unknown authority
The application has been running fine on Bluemix for several months. Then it stopped accepting logins. I restarted it and now get errors on this certificate: HL v. 0.6. I double-checked and have the same certificate still showing at cp-web github. Maybe the certificate has expired? Maybe stricter enforcement on Bluemix now disallows self-signed certificates?

2017-06-21T10:18:35.54-0400 [APP/0] OUT   msg: 'Certificate has not
  been signed by a trusted authority. [x509: certificate signed by
  unknown authority (possibly because of "x509: ECDSA verification
  failure" while trying to verify candidate authority certificate
  "eca")]' }

2017-06-21T10:18:17.32-0400 [APP/0] OUT chain_setup.js Deployment
  request:
  {"fcn":"init","args":["IGNORE","ME"],"chaincodePath":"chaincode/","certificatePath
  ":"/certs/peer/cert.pem"}

答:
When using Hyperledger Fabric version 0.6.1, certificates expire after 90 days.  There is an Hyperledger Fabric issue that documents that certificates are only valid for this length of time.  This issue indicates that there are not plans to change this for Hyperledger Fabric version 0.6.1.

When using Hyperledger Fabric version 0.6.1, the administrator of the blockchain network would have to take action to renew the certificates.  When the blockchain network is running on Bluemix, a support ticket should be opened and an administrative action can be taken to renew the certificates.

After renewing certificates, the user will need to run a query or invoke of the chaincode from every peer so the chaincode will start.  The chaincode stops during the certificate renewal process since the peers have to be restarted.