问:
How to change the inputs' onchange event by name or id?
I have a snippet of HTML which is the simple version of my site. The inputs name is related to the row index. So, I am wondering how to change the inputs' onchange event using the jQuery?

For each row, it has its own function related to the row index. For example, for tr index = 0, it has the function Test1(), for tr index = 1, it has the function Test2()...

Cannot simply using the input selector, because there are some other inputs in the page. Only the id and name for the input are unique.

```<code><tr stampId = '1001' index = '0'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '1'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '2'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '3'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
</code>```

Well, maybe I should put my desired result here.

```<code><script>Do something here, then change the onchange events to below.</script>
<tr stampId = '1001' index = '0'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange="Test1();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '1'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange="Test2();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '2'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange="Test3();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '3'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange="Test4();">
        </span>
    </td>
</tr>
</code>```

答:
If you're using jQuery, you shouldnt be using inline onchange event handlers. Also, if you wish to target multiple elements with the same behaviour use a shared class. If you do both those things this becomes trivial using jQuery's index() method:

var functions = {
   Test1: function(){ console.log("TextBox1 changed") },
   Test2: function(){ console.log("TextBox2 changed") },
   Test3: function(){ console.log("TextBox3 changed") },
   Test4: function(){ console.log("TextBox4 changed") }
}

$(document).on('change','.myClass',function(){
    var index = $(this).index();
    functions["Test" + index]();
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass"></code>```

Body:
I have a snippet of HTML which is the simple version of my site. The inputs name is related to the row index. So, I am wondering how to change the inputs' onchange event using the jQuery?

For each row, it has its own function related to the row index. For example, for tr index = 0, it has the function Test1(), for tr index = 1, it has the function Test2()...

Cannot simply using the input selector, because there are some other inputs in the page. Only the id and name for the input are unique.

        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange=" SaveControlState(event,'Text');">

Well, maybe I should put my desired result here.

        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange="Test1();">

        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange="Test2();">

        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange="Test3();">

        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange="Test4();">

Body:
If you're using jQuery, you shouldnt be using inline onchange event handlers. Also, if you wish to target multiple elements with the same behaviour use a shared class. If you do both those things this becomes trivial using jQuery's index() method:

var functions = {
   Test1: function(){ console.log("TextBox1 changed") },
   Test2: function(){ console.log("TextBox2 changed") },
   Test3: function(){ console.log("TextBox3 changed") },
   Test4: function(){ console.log("TextBox4 changed") }
}

$(document).on('change','.myClass',function(){
    var index = $(this).index();
    functions["Test" + index]();
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass">
<input type="text" class="myClass">


来源: stackexchange

问:
css code doesn't apply to button in ionic 2
I am new to ionic and hybrid apps in general. While plugging and playing with a teat app, i don't see any css working. What am I doing wrong?
Here's my files :
test.scss:

```<code>test{

.button-inner {
  width:20% !important;
  margin:30px;
}
}
</code>```

Also, here's the respect test.html file:

```<code><ion-content padding>
<button ion-button round class="button-inner">Submit</button>

</ion-content>
</code>```

and I am referring to these classes in ts file:

```<code>@Component({
  selector: 'test',
  templateUrl: 'test.html',
})
</code>```

Not sure why the button is still taking up the entire width of the screen instead of just 20%. Any ideas?

Thanks

答:
I've had this problem before, I think it's cause of Angular's view encapsulation ( aka shadow root). I've worked around it by doing something like this:

```<code><ion-content padding>
<button ion-button round><span class="button-inner">Submit</span></button>

</ion-content>
</code>```

Not entirely sure if this will give you your desired outcome since I haven't worked much with Ionic.

EDIT

After the conversation in the comments I created a working plnkr with the wanting behavior.

home.ts

```<code>import { Page, NavController } from 'ionic-angular/index';

@Page({
  templateUrl:"home.html"
})
export class HomePage {
  constructor(private nav: NavController) {}
}
</code>```

home.html

```<code><ion-content padding>
  <button ion-button round class="custom-button button-inner">Submit</button>
</ion-content>
</code>```

style.css

```<code>.custom-button {
  width: 20% !important;
  margin: 0 auto;
}
</code>```

Plnkr

ContentLicense: CC BY-SA 3.0

Body:
I am new to ionic and hybrid apps in general. While plugging and playing with a teat app, i don't see any css working. What am I doing wrong?
Here's my files :
test.scss:

test{

.button-inner {
  width:20% !important;
  margin:30px;
}
}

Also, here's the respect test.html file:

<ion-content padding>
<button ion-button round class="button-inner">Submit</button>

</ion-content>

and I am referring to these classes in ts file:

@Component({
  selector: 'test',
  templateUrl: 'test.html',
})

Not sure why the button is still taking up the entire width of the screen instead of just 20%. Any ideas?

Thanks

Body:
I've had this problem before, I think it's cause of Angular's view encapsulation ( aka shadow root). I've worked around it by doing something like this:

<ion-content padding>
<button ion-button round><span class="button-inner">Submit</span></button>

</ion-content>

Not entirely sure if this will give you your desired outcome since I haven't worked much with Ionic.

EDIT

After the conversation in the comments I created a working plnkr with the wanting behavior.

home.ts

import { Page, NavController } from 'ionic-angular/index';

@Page({
  templateUrl:"home.html"
})
export class HomePage {
  constructor(private nav: NavController) {}
}

home.html

<ion-content padding>
  <button ion-button round class="custom-button button-inner">Submit</button>
</ion-content>

style.css

.custom-button {
  width: 20% !important;
  margin: 0 auto;
}

Plnkr


问:
Angular-CLI build file size differences
When build my Angular app, I end up with this out put:

Looking at this you can immediately see that 0.7f787ebcd865a23bb4ea.chunk.js and
vendor.fbdfd024192bddab02d3.bundle.js are quite big. I wanted to double check how big they are and looked up the actual file size in the command line and the finder, which is:

1.8 MB for the 0.xxx.chunck.js

1.1 MB for the vendor.xxx.bundle.js

I thought that it could be the *.js.map files, but running the build in prod mode has a rather small difference on the files:
Can someone explain why I get two different file sizes?

答:
Both of your images show exactly the same sizes, so it's not clear how did you build the bundles the first and the second time.

But regardless of how you built the bundles, to understand why they are so big, you need to know what's inside the bundles. Install Source-MapExplorer and see what's inside.

```<code>npm install -g source-map-explorer
source-map-explorer 0.xxx.chunck.js
</code>```

Title: Angular-CLI build file size differences

Body:
Both of your images show exactly the same sizes, so it's not clear how did you build the bundles the first and the second time.

But regardless of how you built the bundles, to understand why they are so big, you need to know what's inside the bundles. Install Source-MapExplorer and see what's inside.

npm install -g source-map-explorer
source-map-explorer 0.xxx.chunck.js


问:
Get value out of Json return
My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.

Below is my code:

```<code>        this.search = function () {
    var response = $http({
        method: 'GET',
        url: '/api/TalentPool/Search'
    });

    return response;
}

this.search().then(function (response) {
    console.log('conscole: ' + response.data.model)
})

this.search().then(function (response) {
    console.log(response.data.model)
})
</code>```

And below is my mvc method:`

```<code>  List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
            CandidateSearch.model = output;
            CandidateSearch.baseCriteria = criteria;
            return Ok(CandidateSearch);
</code>```

答:
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response

```<code>this.search = function () {
    return $http({
        method: 'GET',
        url: '/api/TalentPool/Search'
    });
}

//resolve the promise like this

this.search().then(function(response){
     console.log(response.data.model)
})
</code>```

Title: Get value out of Json return

Body:
My angularJs function returns response in Json, but I am not been able to get the 'model' part out from it.

Below is my code:

        this.search = function () {
    var response = $http({
        method: 'GET',
        url: '/api/TalentPool/Search'
    });

    return response;
}

this.search().then(function (response) {
    console.log('conscole: ' + response.data.model)
})

this.search().then(function (response) {
    console.log(response.data.model)
})

And below is my mvc method:`

  List<CandidateSearchViewModel> output = CRBuilderObj.ContructResultsViewModel(data);
            CandidateSearch.model = output;
            CandidateSearch.baseCriteria = criteria;
            return Ok(CandidateSearch);

Body:
if you want to access the response of the http request then you have to resolve the promise firs. then access the model property from the response

this.search = function () {
    return $http({
        method: 'GET',
        url: '/api/TalentPool/Search'
    });
}

//resolve the promise like this

this.search().then(function(response){
     console.log(response.data.model)
})


问:
Configurable custom code
Our customer provided source code has portions of code that will be executed based on tool type. A sample code portion is given below. The function has common portions and tool specific(hardware platform) portions. The code is written in C and runs in VxWorks. Addition or deletion of new tool type has code modification. The customer wants addition or deletion new tool type with minimal code change and testing effort

```<code>int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    if (MODEL_CR == type)
    {
        rc = beamoff(recv_text);
    }
    else
    {
        rc = vsp_set(recv_text);
    }

    return(rc);
}
</code>```

Is it the right technique to separate the code to two methods as given below, keep them in separate source files and define separate make files to generate tool specific binary? Is there any better ways to do this?

Tool type MODEL_CR code

```<code>int vsp_recv_tool_speccific(char *const recv_text)
{
    return beamoff(recv_text);
}
</code>```

Tool type MODEL_CV code

```<code>int vsp_recv_tool_speccific(char *const recv_text)
{
    return vsp_set(recv_text);
}
</code>```

Refactored method

```<code>int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    rc = vsp_recv_tool_speccific(recv_text);
}
</code>```

答: Define a shared library for each tool and a configuration file that defines what functions get called for each tool.  Load the shared libraries at startup and provide a signal catcher to reload if the configuration file changes.</p>

Title: Configurable custom code

Body:
Our customer provided source code has portions of code that will be executed based on tool type. A sample code portion is given below. The function has common portions and tool specific(hardware platform) portions. The code is written in C and runs in VxWorks. Addition or deletion of new tool type has code modification. The customer wants addition or deletion new tool type with minimal code change and testing effort

int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    if (MODEL_CR == type)
    {
        rc = beamoff(recv_text);
    }
    else
    {
        rc = vsp_set(recv_text);
    }

    return(rc);
}

Is it the right technique to separate the code to two methods as given below, keep them in separate source files and define separate make files to generate tool specific binary? Is there any better ways to do this?

Tool type MODEL_CR code

int vsp_recv_tool_speccific(char *const recv_text)
{
    return beamoff(recv_text);
}

Tool type MODEL_CV code

int vsp_recv_tool_speccific(char *const recv_text)
{
    return vsp_set(recv_text);
}

Refactored method

int vsp_recv(char *const recv_text)
{
    int rc  = 0;
    const int       type =  get_tool_type();
    // Common Code

    rc = vsp_recv_tool_speccific(recv_text);
}


问:
Register, Modules View in Eclipse IDE for Java?
I dont see how Register, Modules View work in Eclipse Debug View ?. I run a class and have breakpoints. I can see Variables Expressions but why dont Registers and Modules View work ?</p>

答:
To view a particular view in Eclipse:

ALT + SHIFT + Q

Q

Then type the name of the view that you want to see.

Once you have the perspective looking the right way, you can save it by selecting Window->Save Perspective As...

ContentLicense: CC BY-SA 2.5


问:
Style d3 svg line with css
I want to style my d3 line element with CSS. It seems to work just fine for other elements like "rect", "path" or "circle" but for "line" I just can't make it work...

css:

```<code>.line {
   stroke: #000000;
   stroke-width: 0.5;
}
</code>```

js:

```<code>d3.select('.container')
  .append("line")
  .attr("x1", "0")
  .attr("x2", "100")
  .attr("y1", "0")
  .attr("y2", "100")
  //.attr("style", "stroke:#000000;stroke-width:0.5")
</code>```

If I remove the comment in the last line it works, but I don't want to use inline CSS.

Seems to me like you can't set the stroke attribute of specifically a line without using inline css...

Am I missing something?

答:
Remove the dot...

```<code>line {
  stroke: #000000;
  stroke-width: 0.5;
}
</code>```

In CSS, a class uses a dot like .my-class elements have nothing in front of them e.g. line or div and IDs have # like #my-id

Title: Style d3 svg line with css

Body:
I want to style my d3 line element with CSS. It seems to work just fine for other elements like "rect", "path" or "circle" but for "line" I just can't make it work...

css:

.line {
   stroke: #000000;
   stroke-width: 0.5;
}

js:

d3.select('.container')
  .append("line")
  .attr("x1", "0")
  .attr("x2", "100")
  .attr("y1", "0")
  .attr("y2", "100")
  //.attr("style", "stroke:#000000;stroke-width:0.5")

If I remove the comment in the last line it works, but I don't want to use inline CSS.

Seems to me like you can't set the stroke attribute of specifically a line without using inline css...

Am I missing something?

Body:
Remove the dot...

line {
  stroke: #000000;
  stroke-width: 0.5;
}

In CSS, a class uses a dot like .my-class elements have nothing in front of them e.g. line or div and IDs have # like #my-id


问:
How does one for filter for parent child documents that do not have a child document with a given attribute?
I've tried these commands:

{!parent which=type:parent v="(+type:child +event_title:*zz*)" }
returns 103 documents

{!parent which=type:parent v="(+type:child -event_title:*zz*)" }
returns all documents

Total documents are 7000.  I am expecting the second query with -event_title to return
7000-103 = 6897 documents.

However the -event_title returns all documents.  How can I just return parent documents that do not have a child document with a given attribute?

答:
Block join is one-to-many. It is entirely possible that number of(+A +B) + number of(+A -B) > number of (+A), because one parent can have one +A +B child and one +A -B child, contributing to all three counters.

Maybe it's just the case? Imagine that every parent has at least one chid without event_title:*zz*, and 103 parents has also children with event_title:*zz*.


答:
There are a few details I'd like you to clarify (would put into comments on the q, but it is actually easier to remove from here when you update your question).

What is the intended usage of data, insert once and get the counts many times, or your inserts and selects are approx on par?

Do you care about insert/update performance?

What is the engine used for the table? (heck you can do SHOW CREATE TABLE ...)

Do you need the counts to be exact or approximately exact (like 0.1% correct)

Can you use triggers, summary tables, change schema, change RDBMS, etc.. or just add/remove indexes?

Maybe you should explain also what is this table supposed to be? You have record_id with cardinality that matches the number of rows, so is it PK or FK or what is it? Also the cardinality of the date_updated suggests (though not necessarily correct) that it has same values for ~5,000 records on average), so what is that? - it is ok to ask a SQL tuning question with not context, but it is also nice to have some context - especially if redesigning is an option.

In the meantime, I'll suggest you to get this tuning script and check the recommendations it will give you (it's just a general tuning script - but it will inspect your data and stats).

ContentLicense: CC BY-SA 4.0

Title: optimize mysql count query

Body:
Is there a way to optimize this further or should I just be satisfied that it takes 9 seconds to count 11M rows ?

devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "desc record_updates"
+--------------+----------+------+-----+---------+-------+
| Field        | Type     | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| record_id    | int(11)  | YES  | MUL | NULL    |       |
| date_updated | datetime | YES  | MUL | NULL    |       |
+--------------+----------+------+-----+---------+-------+
devuser@xcmst > date; mysql --user=user --password=pass -D marctoxctransformation -e "select count(*) from record_updates where date_updated > '2009-10-11 15:33:22' "; date
Thu Dec  9 11:13:17 EST 2010
+----------+
| count(*) |
+----------+
| 11772117 |
+----------+
Thu Dec  9 11:13:26 EST 2010
devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "explain select count(*) from record_updates where date_updated > '2009-10-11 15:33:22' "
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
| id | select_type | table          | type  | possible_keys                                          | key                                                    | key_len | ref  | rows     | Extra                    |
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
|  1 | SIMPLE      | record_updates | index | idx_marctoxctransformation_record_updates_date_updated | idx_marctoxctransformation_record_updates_date_updated | 9       | NULL | 11772117 | Using where; Using index |
+----+-------------+----------------+-------+--------------------------------------------------------+--------------------------------------------------------+---------+------+----------+--------------------------+
devuser@xcmst > mysql --user=user --password=pass -D marctoxctransformation -e "show keys from record_updates"
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+
| Table          | Non_unique | Key_name                                               | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+
| record_updates |          1 | idx_marctoxctransformation_record_updates_date_updated |            1 | date_updated | A         |        2416 |     NULL | NULL   | YES  | BTREE      |         |
| record_updates |          1 | idx_marctoxctransformation_record_updates_record_id    |            1 | record_id    | A         |    11772117 |     NULL | NULL   | YES  | BTREE      |         |
+----------------+------------+--------------------------------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+


问:
Getting hidden inputs fields and can't even get the page source with selenium and BeautifulSoup
I am trying to get page source. so, i can make query with post requests and retrieve data from result. but, initially i don't even get page source.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup

browser=webdriver.Firefox()

browser.get('url.aspx')

soup=BeautifulSoup(browser.page_source)

print soup.prettify()
</code>```

i am getting following page source:

```<code>...
</script>
  <noscript>
   Please enable JavaScript to view the page content.
  </noscript>
 </head>
 <body onload="challenge()">
  <form action="/corpweb/CorpSearch/CorpSearch.aspx" method="POST">
   <input name="TS019ab495_id" type="hidden" value="3"/>
   <input name="TS019ab495_cr" type="hidden"
value="c4fb95a11ceaf83e82fc10400957ab7c:yvyz:a9qeoPYm:1996871542"/>
   <input name="TS019ab495_76" type="hidden" value="0"/>
   <input name="TS019ab495_md" type="hidden" value="1"/>
   <input name="TS019ab495_rf" type="hidden" value="0"/>
   <input name="TS019ab495_ct" type="hidden" value="0"/>
   <input name="TS019ab495_pd" type="hidden" value="0"/>
  </form>
 </body>
</html>
</code>```

答:
```<code><noscript>
Please enable JavaScript to view the page content.
</noscript>
</code>```

That is going to be a challenge:
https://www.quora.com/Can-beautifulsoup-scrape-javascript-rendered-webpages

In my past I did a lot of work with writing spiders in Perl and javascript was always a challenge if the content we wanted was created by the javascript.  We would have to use some kind of 3rd party tool to read/render/output the javascript to an html file, then simply import that data for parsing.

The link above has a few tools that should do the trick. Good luck!

Body:
I am trying to get page source. so, i can make query with post requests and retrieve data from result. but, initially i don't even get page source.

from selenium import webdriver
from bs4 import BeautifulSoup

browser=webdriver.Firefox()

browser.get('url.aspx')

soup=BeautifulSoup(browser.page_source)

print soup.prettify()

i am getting following page source:

...
</script>

   Please enable JavaScript to view the page content.

  <form action="/corpweb/CorpSearch/CorpSearch.aspx" method="POST">
   <input name="TS019ab495_id" type="hidden" value="3"/>
   <input name="TS019ab495_cr" type="hidden"
value="c4fb95a11ceaf83e82fc10400957ab7c:yvyz:a9qeoPYm:1996871542"/>
   <input name="TS019ab495_76" type="hidden" value="0"/>
   <input name="TS019ab495_md" type="hidden" value="1"/>
   <input name="TS019ab495_rf" type="hidden" value="0"/>
   <input name="TS019ab495_ct" type="hidden" value="0"/>
   <input name="TS019ab495_pd" type="hidden" value="0"/>
  </form>

Body:
<noscript>
Please enable JavaScript to view the page content.
</noscript>

That is going to be a challenge:
https://www.quora.com/Can-beautifulsoup-scrape-javascript-rendered-webpages

In my past I did a lot of work with writing spiders in Perl and javascript was always a challenge if the content we wanted was created by the javascript.  We would have to use some kind of 3rd party tool to read/render/output the javascript to an html file, then simply import that data for parsing.

The link above has a few tools that should do the trick. Good luck!


问:
Can CSS3 Filter be applied to options inside <select> ?
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

```<code>select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
</code>```

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

答:
You can use :hover after the class name:

```<code>select option:hover {
    -webkit-filter: blur(5px);
    filter: blur(5px);
    color: blue; /* Just checking if rule and styles are working */
}
</code>```

Body:
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

Body:
You can use :hover after the class name:

select option:hover {
    -webkit-filter: blur(5px);
    filter: blur(5px);
    color: blue; /* Just checking if rule and styles are working */
}


问:
Is there a Shortcut key to view Table Dependencies SQL
Can we See the table dependencies by using shortcut keys from SQL Query Editor Itself.

I know we can use object explorer and then select the table , right click and then View Dependency .

But I juts want to navigate from Query Editor itself.

答:
If you select a table name in the query window of Sql Server Management Studio
and press ALT + F1 it will display the details of that table.

In the background shortcut key will execute sp_help on your behalf, so in this example it executes: sp_help users, which is much quicker than typing it.


问:
Azure Machine Learning Studio Custom Module Upload Error 0114 : An item with the same key has already been added
When trying to upload a custom R module to Azure Machine Learning Studio what causes the following error.

[ModuleOutput]

```<code>"ErrorId":"BuildCustomModuleFailed","ErrorCode":"0114","ExceptionType":"ModuleException","Message":"Error 0114: Custom module build failed with error(s): An item with the same key has already been added."}} [ModuleOutput] Error: Error 0114: Custom module build failed with error(s): An item with the same key has already been added.
</code>```

I have tried renaming the module so a name that does not exists.

答:
The duplicate key exception is a red herring. Build error 0114 is a general error that occurs if there is a system exception while building the custom module. The real issue my module was compressed using the built in compress folder option in the Mac Finder. To fix this compress the file using the command line interface for zip in Terminal in the following very specific manner.

The following example:

```<code>cd ScoredDatasetMetadata/
zip ScoredDatasetMetadata *
mv ScoredDatasetMetadata.zip ../
</code>```

Builds a zip file with the correct file structure.

Body:
When trying to upload a custom R module to Azure Machine Learning Studio what causes the following error.

[ModuleOutput]

"ErrorId":"BuildCustomModuleFailed","ErrorCode":"0114","ExceptionType":"ModuleException","Message":"Error 0114: Custom module build failed with error(s): An item with the same key has already been added."}} [ModuleOutput] Error: Error 0114: Custom module build failed with error(s): An item with the same key has already been added.

I have tried renaming the module so a name that does not exists.

Body:
The duplicate key exception is a red herring. Build error 0114 is a general error that occurs if there is a system exception while building the custom module. The real issue my module was compressed using the built in compress folder option in the Mac Finder. To fix this compress the file using the command line interface for zip in Terminal in the following very specific manner.

The following example:

cd ScoredDatasetMetadata/
zip ScoredDatasetMetadata *
mv ScoredDatasetMetadata.zip ../

Builds a zip file with the correct file structure.


问:
renaming columns after group by and sum in pandas dataframe
This is my group by command:

```<code>pdf_chart_data1 = pdf_chart_data.groupby('sell').value.agg(['sum']).rename(
    columns={'sum':'valuesum','sell' : 'selltime'}
)
</code>```

I am able to change the column name for value but not for 'sell'.
Please help to resolve this issue.

答:
You cannot rename it, because it is index. You can add as_index=False for return DataFrame or add reset_index:

```<code>pdf_chart_data1=pdf_chart_data.groupby('sell', as_index=False)['value'].sum()
                              .rename(columns={'sum':'valuesum','sell' : 'selltime'})
</code>```

Or:

```<code>pdf_chart_data1=pdf_chart_data.groupby('sell')['value'].sum()
                          .reset_index()
                          .rename(columns={'sum':'valuesum','sell' : 'selltime'})
</code>```

Body:
This is my group by command:

pdf_chart_data1 = pdf_chart_data.groupby('sell').value.agg(['sum']).rename(
    columns={'sum':'valuesum','sell' : 'selltime'}
)

I am able to change the column name for value but not for 'sell'.
Please help to resolve this issue.

Body:
You cannot rename it, because it is index. You can add as_index=False for return DataFrame or add reset_index:

pdf_chart_data1=pdf_chart_data.groupby('sell', as_index=False)['value'].sum()
                              .rename(columns={'sum':'valuesum','sell' : 'selltime'})

Or:

pdf_chart_data1=pdf_chart_data.groupby('sell')['value'].sum()
                          .reset_index()
                          .rename(columns={'sum':'valuesum','sell' : 'selltime'})


问:
Error with place holder on jsx
I have a simple react HTML input component and as it used on different sections/pages, I added some props for styling it and its placeholder. The problem is that sometimes I got an error on the compilation(we are using nextjs).
This the code:

```<code>{placeHolderColor && (<style jsx>{`input::placeholder{color:${placeHolderColor}}`}</style>)}
</code>```

Basically, I'm using an inline If with Logical && Operator inside the render function to check if the prop placeHolderColor exists, and if exist add the style tag.

The error I'm getting:

Warning: Unknown prop jsx on  tag. Remove this prop from the element.

The error only occurs when you reload the page. If you made a change and the hot code reloading run, there is no error. Not sure if the problem is the var inside the literal, the '::placeholder' pseudo-element or what. The code works anyway, and if the placeHolderColor var is defined the style is applied.

Title: Error with place holder on jsx

Body:
I have a simple react HTML input component and as it used on different sections/pages, I added some props for styling it and its placeholder. The problem is that sometimes I got an error on the compilation(we are using nextjs).
This the code:

{placeHolderColor && ()}

Basically, I'm using an inline If with Logical && Operator inside the render function to check if the prop placeHolderColor exists, and if exist add the style tag.

The error I'm getting:

Warning: Unknown prop jsx on  tag. Remove this prop from the element.

The error only occurs when you reload the page. If you made a change and the hot code reloading run, there is no error. Not sure if the problem is the var inside the literal, the '::placeholder' pseudo-element or what. The code works anyway, and if the placeHolderColor var is defined the style is applied.

Body: I got error Warning: Unknown prop 'jsx' on <style> tag. Remove this prop from the element. For details, see FB react-unknown-prop. What does that jsx property in your style tag means? Just remove it?


问:
locking only when modifying vs entire method
When should locks be used? Only when modifying data or when accessing it as well?

```<code>public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}
</code>```

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.

答:
Lock the whole block before you check for the existence of name. Otherwise, in theory, another thread could add it between the check, and your code that adds it.

Actually locking just when you perform the Add really doesn't do anything at all. All that would do is prevent another thread from adding something simultaneously. But since that other thread would have already decided it was going to do the add, it would just try to do it anyway as soon as the lock was released.

Body:
When should locks be used? Only when modifying data or when accessing it as well?

public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.


问:
Link to Google maps with dynamic path
I want to link to Google Maps with a lat & long :

For that, I Used : http://maps.google.com/maps?q=48.819141912303,2.2297863639837

I'm wondering if I can add a Path to this Google Maps ?

I used it in a static map and Can I do that with this Google maps link ?
https://maps.googleapis.com/maps/api/staticmap?path=48.819141912303,2.2297863639837|48.81863290356,2.2312122798508|48.818734654467,2.2313515376389&scale=true&size=600x300&maptype=roadmap&format=png&visual_refresh=true

答:
I don't think that this is possible to open a map with an arbitrary polyline on it. You should use APIs for this purpose.

However, you can open the map with driving directions that pass through specified waypoints.

Just create Maps URLs for directions with origin, destination and waypoints.

For example,

https://www.google.com/maps/dir/?api=1&origin=48.819141912303,2.2297863639837&waypoints=48.81863290356,2.2312122798508&destination=48.818734654467,2.2313515376389&travelmode=walking

Have a look at Maps URLs documentation for further details.

Title: Link to Google maps with dynamic path


问:
How do I change the colour of my button and label on Tkinter?
My task is to create a label and button on Tkinter. The button has to change the label, and I have to change the colour of the button and the label. I have changed the colour of the background but I can't figure out how to do the same for the label and button.</p>

```<code>from tkinter import *
from tkinter import ttk

def change():
    print("change functon called")

def main():
    rootWindow = Tk()
    rootWindow.geometry('400x400')
    rootWindow.configure(bg="red")

    global Label
    label = ttk.Label( rootWindow, text="Hello World!" )
    label.pack()

    button1 = ttk.Button( rootWindow, text="Change Label",
                        command=change)
    button1.pack()

    rootWindow.mainloop()

main()
</code>```

答:
So configuring a buttons colors is a bit different when using tkinter button VS a ttk style button.

For a tkinter button you would use the background = "color" argument like the following:

```<code>button1 = Button( rootWindow, text="Change Label",
                      background = 'black', foreground = "white", command=change)
</code>```

For a ttk button you would configure the style and then use the style = "style name" argument like the following.

```<code>style = ttk.Style()
style.configure("BW.TLabel", foreground="white", background="black")

buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
</code>```

More information on ttk configs can be found here

```<code>from tkinter import *
from tkinter import ttk

def change():
    print("change functon called")

def main():
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!",
                       background = 'black', foreground = "white")
    label.pack()

    button1 = Button( rootWindow, text="Change Label",
                          background = 'black', foreground = "white", command=change)
    button1.pack()

    style = ttk.Style()
    style.configure("BW.TLabel", foreground="white", background="black")

    buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
    buttonTTK.pack()

    rootWindow.mainloop()

main()
</code>```

Result:

Body:
My task is to create a label and button on Tkinter. The button has to change the label, and I have to change the colour of the button and the label. I have changed the colour of the background but I can't figure out how to do the same for the label and button.

from tkinter import *
from tkinter import ttk

def change():
    print("change functon called")

def main():
    rootWindow = Tk()
    rootWindow.geometry('400x400')
    rootWindow.configure(bg="red")

    global Label
    label = ttk.Label( rootWindow, text="Hello World!" )
    label.pack()

    button1 = ttk.Button( rootWindow, text="Change Label",
                        command=change)
    button1.pack()

    rootWindow.mainloop()

main()

Body:
So configuring a buttons colors is a bit different when using tkinter button VS a ttk style button.

For a tkinter button you would use the background = "color" argument like the following:

button1 = Button( rootWindow, text="Change Label",
                      background = 'black', foreground = "white", command=change)

For a ttk button you would configure the style and then use the style = "style name" argument like the following.

style = ttk.Style()
style.configure("BW.TLabel", foreground="white", background="black")

buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)

More information on ttk configs can be found here

from tkinter import *
from tkinter import ttk

def change():
    print("change functon called")

def main():
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!",
                       background = 'black', foreground = "white")
    label.pack()

    button1 = Button( rootWindow, text="Change Label",
                          background = 'black', foreground = "white", command=change)
    button1.pack()

    style = ttk.Style()
    style.configure("BW.TLabel", foreground="white", background="black")

    buttonTTK = ttk.Button( rootWindow, text="TTK BUTTON",style = "BW.TLabel", command=change)
    buttonTTK.pack()

    rootWindow.mainloop()

main()

Result:


问:
Is it possible to extend/insert a CSS property value
My question may be a little confusing, my css skills are moderate at best but none the less I'll do my best to try and explain. So my question is as follows;

Is it possible to insert/extend a CSS property value?

An example of what im trying to achieve can be found within the snippet below;

* {
  margin: 0;
  padding: 0;
}

.wrap {
  width: 100%;
}

.box {
  display: inline-block;
  float:left;
  width: 50%;
  padding-top: 80%;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

/* --- original element... --- */

.original {
  background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

/* --- What I'm After --- */

.sourced {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%), url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="box original"></div>
  <div class="box sourced"></div>
</div></code>```

Some background of my intended application, I have a WP installation running Avada wp theme. Within the theme a div element is built with a css image background, but the nature of this theme minizes the need for heavy coding. This is where I hit a wall as the element can only be overidden with css. But, I want to refrain from doing so as the image is dynamically inserted from the wp image library to keep the images responsive; I.e. desktop size, tablet, mobile, etc.

From what I understand overiding the css would mean hardcoding the URL into the stylesheet breaking the responsitivity.

My Research

I spent some time digging around the web but the solutions I came across seemed more difficult, or a little to hacky for practical use. After further digging I was able to stumble accross this CSS Extend Rule.

However, my understanding of this article is that using @extend would simply chain on a new rule to an exisiting class, providing the rule is computed.

The answer may be super simple, but I have never encountered a need for this before. Any help is much appreciated.

EDIT - THU 8 JUN 2017 09:52

Due to the nature of this project being a little time sensitive I have hardcoded the Property and it's Value, breaking the responsitivity. This will not be a long term fix and I will be sourcing a better solution. To all that arrive late I will be monitoring this question for the forseeable future, so feel free to try to answer.

```<code>/* -- Overide Currently in Use -- */
.post-content #main-hero {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url("https://www.url.com/image") !important;
}
</code>```

答:
If you want to overlay the image with another element with e.g. a gradient or background color, you can 'cheat'

 /* original css */
    .original {
        background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
    }

    /* extra css */
    .original{
        position: relative;
        width: 150px;
        height: 150px;
    }
    .original:before{
        position: absolute;
        content : "I am placed over the image";
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(to bottom, rgba(255, 0, 0, 0.1) 0%, rgba(0, 0, 255, 0.9) 100%);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="original"></div></code>```

Body:
My question may be a little confusing, my css skills are moderate at best but none the less I'll do my best to try and explain. So my question is as follows;

Is it possible to insert/extend a CSS property value?

An example of what im trying to achieve can be found within the snippet below;

* {
  margin: 0;
  padding: 0;
}

.wrap {
  width: 100%;
}

.box {
  display: inline-block;
  float:left;
  width: 50%;
  padding-top: 80%;
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

/* --- original element... --- */

.original {
  background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

/* --- What I'm After --- */

.sourced {
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%), url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
}

Some background of my intended application, I have a WP installation running Avada wp theme. Within the theme a div element is built with a css image background, but the nature of this theme minizes the need for heavy coding. This is where I hit a wall as the element can only be overidden with css. But, I want to refrain from doing so as the image is dynamically inserted from the wp image library to keep the images responsive; I.e. desktop size, tablet, mobile, etc.

From what I understand overiding the css would mean hardcoding the URL into the stylesheet breaking the responsitivity.

My Research

I spent some time digging around the web but the solutions I came across seemed more difficult, or a little to hacky for practical use. After further digging I was able to stumble accross this CSS Extend Rule.

However, my understanding of this article is that using @extend would simply chain on a new rule to an exisiting class, providing the rule is computed.

The answer may be super simple, but I have never encountered a need for this before. Any help is much appreciated.

EDIT - THU 8 JUN 2017 09:52

Due to the nature of this project being a little time sensitive I have hardcoded the Property and it's Value, breaking the responsitivity. This will not be a long term fix and I will be sourcing a better solution. To all that arrive late I will be monitoring this question for the forseeable future, so feel free to try to answer.

/* -- Overide Currently in Use -- */
.post-content #main-hero {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0.3) 100%), url("https://www.url.com/image") !important;
}

Body:
If you want to overlay the image with another element with e.g. a gradient or background color, you can 'cheat'

 /* original css */
    .original {
        background-image: url(http://imageshack.com/a/img631/8360/WuQwuf.jpg);
    }

    /* extra css */
    .original{
        position: relative;
        width: 150px;
        height: 150px;
    }
    .original:before{
        position: absolute;
        content : "I am placed over the image";
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(to bottom, rgba(255, 0, 0, 0.1) 0%, rgba(0, 0, 255, 0.9) 100%);
    }

<div class="original"></div>


问:
Azure ARM JSON template - Add VM to Recovery Services Vault in different Resource Group
I'm trying to add the functionality to add the VM to a recovery services vault to my existing Azure ARM JSON template that I use for deployment.

I've used the code from the following GitHub template and this works if the recovery services vault is in the same resource group as VM but not if its in a different one.

https://github.com/Azure/azure-quickstart-templates/tree/master/101-recovery-services-backup-vms

The code is below:

```<code>{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
    "existingVirtualMachinesResourceGroup": {
        "type": "string",
        "metadata": {
            "description": "Resource group where the virtual machines are located. This can be different than resource group of the vault. "
        }
    },
    "existingVirtualMachines": {
        "type": "array",
        "metadata": {
            "description": "Array of Azure virtual machines. e.g. [\"vm1\",\"vm2\",\"vm3\"]"
        }
    },
    "existingRecoveryServicesVault": {
        "type": "string",
        "metadata": {
            "description": "Recovery services vault name where the VMs will be backed up to. "
        }
    },
    "existingBackupPolicy": {
        "type": "string",
        "defaultValue": "DefaultPolicy",
        "metadata": {
            "description": "Backup policy to be used to backup VMs. Backup POlicy defines the schedule of the backup and how long to retain backup copies. By default every vault comes with a 'DefaultPolicy' which canbe used here."
        }
    }
},
"variables": {
    "backupFabric": "Azure",
    "v2VmType": "Microsoft.Compute/virtualMachines",
    "v2VmContainer": "iaasvmcontainer;iaasvmcontainerv2;",
    "v2Vm": "vm;iaasvmcontainerv2;"
},
"resources": [
    {
        "name": "[concat(parameters('existingRecoveryServicesVault'), '/', variables('backupFabric'), '/', variables('v2VmContainer'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')[copyIndex()]), '/', variables('v2Vm'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')[copyIndex()]))]",
        "apiVersion": "2016-06-01",
        "location": "[resourceGroup().location]",
        "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
        "copy": {
            "name": "v2VmsCopy",
            "count": "[length(parameters('existingVirtualMachines'))]"
        },
        "properties": {
            "protectedItemType": "[variables('v2VmType')]",
            "policyId": "[resourceId('Microsoft.RecoveryServices/vaults/backupPolicies',parameters('existingRecoveryServicesVault'),parameters('existingBackupPolicy') )]",
            "sourceResourceId": "[resourceId(subscription().subscriptionId,parameters('existingVirtualMachinesResourceGroup'),'Microsoft.Compute/virtualMachines',parameters('existingVirtualMachines')[copyIndex()])]"
        }
    }
]
</code>```

}

There is no variable or parameter to define the recovery services vaults resource group.

I've also looked at the following GitHub template that also adds a VM to a recovery services vault but again this doesn't seem to have the ability to use different resource groups.

https://github.com/Azure/azure-quickstart-templates/tree/master/201-recovery-services-backup-classic-resource-manager-vms

I've tried googling but so far I haven't been able to find an answer to this so is it possible?

Thanks

答:
I've found the answer to this if it's useful to anyone else. As already mentioned the recovery services vault will use the same resource group as defined for the template. To be able to define a different template for the RSV this needs to be done using a nested template.

I have used the following nested template to replace the recovery services resource in my original post, the resource group required for the recovery services vault is defined by "resourceGroup": "[parameters('nestedTemplateRecoveryServicesResourceGroup')]",

```<code>{
"apiVersion": "2017-05-10",
        "name": "nestedTemplateRecoveryServices",
        "type": "Microsoft.Resources/deployments",
        "resourceGroup": "[parameters('nestedTemplateRecoveryServicesResourceGroup')]",
        "dependsOn": ["[concat('Microsoft.Compute/virtualMachines/', parameters('vmName'))]"],
        "properties": {
            "mode": "Incremental",
            "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {},
                "variables": {},
                "resources": [
                        {
                        "name": "[concat(parameters('existingRecoveryServicesVault'), '/', variables('backupFabric'), '/', variables('v2VmContainer'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')), '/', variables('v2Vm'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')))]",
                        "apiVersion": "2016-06-01",
                        "location": "[resourceGroup().location]",
                        "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
                        "properties": {
                            "protectedItemType": "[variables('v2VmType')]",
                            "policyId": "[resourceId('Microsoft.RecoveryServices/vaults/backupPolicies',parameters('existingRecoveryServicesVault'),parameters('existingBackupPolicy') )]",
                            "sourceResourceId": "[resourceId(subscription().subscriptionId,parameters('existingVirtualMachinesResourceGroup'),'Microsoft.Compute/virtualMachines',parameters('existingVirtualMachines'))]"
                            }
                        }
                    ]
                },
               "parameters": {},
               "outputs": {}
        }
}
</code>```

Body:
I'm trying to add the functionality to add the VM to a recovery services vault to my existing Azure ARM JSON template that I use for deployment.

I've used the code from the following GitHub template and this works if the recovery services vault is in the same resource group as VM but not if its in a different one.

https://github.com/Azure/azure-quickstart-templates/tree/master/101-recovery-services-backup-vms

The code is below:

{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
    "existingVirtualMachinesResourceGroup": {
        "type": "string",
        "metadata": {
            "description": "Resource group where the virtual machines are located. This can be different than resource group of the vault. "
        }
    },
    "existingVirtualMachines": {
        "type": "array",
        "metadata": {
            "description": "Array of Azure virtual machines. e.g. [\"vm1\",\"vm2\",\"vm3\"]"
        }
    },
    "existingRecoveryServicesVault": {
        "type": "string",
        "metadata": {
            "description": "Recovery services vault name where the VMs will be backed up to. "
        }
    },
    "existingBackupPolicy": {
        "type": "string",
        "defaultValue": "DefaultPolicy",
        "metadata": {
            "description": "Backup policy to be used to backup VMs. Backup POlicy defines the schedule of the backup and how long to retain backup copies. By default every vault comes with a 'DefaultPolicy' which canbe used here."
        }
    }
},
"variables": {
    "backupFabric": "Azure",
    "v2VmType": "Microsoft.Compute/virtualMachines",
    "v2VmContainer": "iaasvmcontainer;iaasvmcontainerv2;",
    "v2Vm": "vm;iaasvmcontainerv2;"
},
"resources": [
    {
        "name": "[concat(parameters('existingRecoveryServicesVault'), '/', variables('backupFabric'), '/', variables('v2VmContainer'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')[copyIndex()]), '/', variables('v2Vm'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')[copyIndex()]))]",
        "apiVersion": "2016-06-01",
        "location": "[resourceGroup().location]",
        "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
        "copy": {
            "name": "v2VmsCopy",
            "count": "[length(parameters('existingVirtualMachines'))]"
        },
        "properties": {
            "protectedItemType": "[variables('v2VmType')]",
            "policyId": "[resourceId('Microsoft.RecoveryServices/vaults/backupPolicies',parameters('existingRecoveryServicesVault'),parameters('existingBackupPolicy') )]",
            "sourceResourceId": "[resourceId(subscription().subscriptionId,parameters('existingVirtualMachinesResourceGroup'),'Microsoft.Compute/virtualMachines',parameters('existingVirtualMachines')[copyIndex()])]"
        }
    }
]

}

There is no variable or parameter to define the recovery services vaults resource group.

I've also looked at the following GitHub template that also adds a VM to a recovery services vault but again this doesn't seem to have the ability to use different resource groups.

https://github.com/Azure/azure-quickstart-templates/tree/master/201-recovery-services-backup-classic-resource-manager-vms

I've tried googling but so far I haven't been able to find an answer to this so is it possible?

Thanks

Body:
I've found the answer to this if it's useful to anyone else. As already mentioned the recovery services vault will use the same resource group as defined for the template. To be able to define a different template for the RSV this needs to be done using a nested template.

I have used the following nested template to replace the recovery services resource in my original post, the resource group required for the recovery services vault is defined by "resourceGroup": "[parameters('nestedTemplateRecoveryServicesResourceGroup')]",

{
"apiVersion": "2017-05-10",
        "name": "nestedTemplateRecoveryServices",
        "type": "Microsoft.Resources/deployments",
        "resourceGroup": "[parameters('nestedTemplateRecoveryServicesResourceGroup')]",
        "dependsOn": ["[concat('Microsoft.Compute/virtualMachines/', parameters('vmName'))]"],
        "properties": {
            "mode": "Incremental",
            "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {},
                "variables": {},
                "resources": [
                        {
                        "name": "[concat(parameters('existingRecoveryServicesVault'), '/', variables('backupFabric'), '/', variables('v2VmContainer'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')), '/', variables('v2Vm'), concat(parameters('existingVirtualMachinesResourceGroup'),';',parameters('existingVirtualMachines')))]",
                        "apiVersion": "2016-06-01",
                        "location": "[resourceGroup().location]",
                        "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
                        "properties": {
                            "protectedItemType": "[variables('v2VmType')]",
                            "policyId": "[resourceId('Microsoft.RecoveryServices/vaults/backupPolicies',parameters('existingRecoveryServicesVault'),parameters('existingBackupPolicy') )]",
                            "sourceResourceId": "[resourceId(subscription().subscriptionId,parameters('existingVirtualMachinesResourceGroup'),'Microsoft.Compute/virtualMachines',parameters('existingVirtualMachines'))]"
                            }
                        }
                    ]
                },
               "parameters": {},
               "outputs": {}
        }
}


问:
R: Need to check relationship between two variables across observations
Take a data frame like mtcars (but much bigger)

I would like to get a list of observations where the value of vs==1 and the value of am != 1. I don't want to have to scroll through a long list of 1s and zeros, but actually get a list of the observations. I could write a loop but is there a more R'ish way of answering that question?

Additional information

My actual example is looking for values in first which are NA while in Grade they are not NA. And this does not seem to work. Does NA get treated special?

```<code>x = subset(spreadgrades, first == NA & Grade == NA)
</code>```

答:
Based on comments and answers, I settled on this:</p>

```<code>subset(spreadgrades, is.na(first) & !is.na(Grade))
</code>```

Body:
Take a data frame like mtcars (but much bigger)

I would like to get a list of observations where the value of vs==1 and the value of am != 1. I don't want to have to scroll through a long list of 1s and zeros, but actually get a list of the observations. I could write a loop but is there a more R'ish way of answering that question?

Additional information

My actual example is looking for values in first which are NA while in Grade they are not NA. And this does not seem to work. Does NA get treated special?

x = subset(spreadgrades, first == NA & Grade == NA)

Body:
Based on comments and answers, I settled on this:

subset(spreadgrades, is.na(first) & !is.na(Grade))


问:
Issue with shiro and ehcache
I am using shiro for authentication along with ehcache.xml for enabling SSO.

My ehcache.xml looks like

```<code><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
         monitoring="autodetect" dynamicConfig="true" name="my-cache">

    <diskStore path="java.io.tmpdir/mycache" />

    <cache name="shiro-activeSessionCache" maxElementsInMemory="1000"
           eternal="true" overflowToDisk="true" memoryStoreEvictionPolicy="LFU">

    </cache>

    <defaultCache maxElementsInMemory="100" eternal="true"
                  overflowToDisk="true" memoryStoreEvictionPolicy="LFU">
    </defaultCache>
</ehcache>
</code>```

I have a factory class like below

```<code>public class SharedEhCacheManagerFactory implements Factory<CacheManager> {

    private String cacheManagerConfigFile = "/ehcache.xml";

    @Override
    public CacheManager getInstance()
    {
        return CacheManager.create(readCacheManagerConfigFileAsInputStream());
    }

    public InputStream readCacheManagerConfigFileAsInputStream()
    {
        InputStream is = getClass().getResourceAsStream(cacheManagerConfigFile);
        return is;
    }
}
</code>```

And my shiro.ini files main section for all webapps is like

```<code>[main]
ehCacheManager = com.nokia.anv.app.security.service.SharedEhCacheManagerFactory
cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManager=$ehCacheManager
securityManager.cacheManager = $cacheManager

sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO

cookie = org.apache.shiro.web.servlet.SimpleCookie
cookie.name = SSOCookie
cookie.path = /
sessionManager.sessionIdCookie = $cookie
sessionManager.sessionIdUrlRewritingEnabled = false
securityManager.sessionManager = $sessionManager
</code>```

I am using apache karaf and this apps comes in a docker container. When I start the container for the first time everything is fine, but if I stop and start the container I am getting the error for most of the appllications like

```<code>javax.servlet.ServletException: java.lang.IllegalStateException: The CacheManager has been shut down. It can no longer be used.
        at org.apache.shiro.web.servlet.AdviceFilter.cleanup(AdviceFilter.java:196)
        at org.apache.shiro.web.filter.authc.AuthenticatingFilter.cleanup(AuthenticatingFilter.java:155)
        at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:148)
        at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
        at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
        at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
        at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
        at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
</code>```

But always two applications are fine. Please let me to what is the issue.

答: I'm guessing something is calling the destroy() method in your CacheManager.  You could add some logging or set a break point to figure how the culprit.

Title: Issue with shiro and ehcache

Body:
I am using shiro for authentication along with ehcache.xml for enabling SSO.

My ehcache.xml looks like

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
         monitoring="autodetect" dynamicConfig="true" name="my-cache">

    <diskStore path="java.io.tmpdir/mycache" />

    <cache name="shiro-activeSessionCache" maxElementsInMemory="1000"
           eternal="true" overflowToDisk="true" memoryStoreEvictionPolicy="LFU">

    </cache>

    <defaultCache maxElementsInMemory="100" eternal="true"
                  overflowToDisk="true" memoryStoreEvictionPolicy="LFU">
    </defaultCache>
</ehcache>

I have a factory class like below

public class SharedEhCacheManagerFactory implements Factory<CacheManager> {

    private String cacheManagerConfigFile = "/ehcache.xml";

    @Override
    public CacheManager getInstance()
    {
        return CacheManager.create(readCacheManagerConfigFileAsInputStream());
    }

    public InputStream readCacheManagerConfigFileAsInputStream()
    {
        InputStream is = getClass().getResourceAsStream(cacheManagerConfigFile);
        return is;
    }
}

And my shiro.ini files main section for all webapps is like

[main]
ehCacheManager = com.nokia.anv.app.security.service.SharedEhCacheManagerFactory
cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManager=$ehCacheManager
securityManager.cacheManager = $cacheManager

sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO

cookie = org.apache.shiro.web.servlet.SimpleCookie
cookie.name = SSOCookie
cookie.path = /
sessionManager.sessionIdCookie = $cookie
sessionManager.sessionIdUrlRewritingEnabled = false
securityManager.sessionManager = $sessionManager

I am using apache karaf and this apps comes in a docker container. When I start the container for the first time everything is fine, but if I stop and start the container I am getting the error for most of the appllications like

javax.servlet.ServletException: java.lang.IllegalStateException: The CacheManager has been shut down. It can no longer be used.
        at org.apache.shiro.web.servlet.AdviceFilter.cleanup(AdviceFilter.java:196)
        at org.apache.shiro.web.filter.authc.AuthenticatingFilter.cleanup(AuthenticatingFilter.java:155)
        at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:148)
        at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
        at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
        at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
        at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
        at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)

But always two applications are fine. Please let me to what is the issue.


问:
Java: Using Array.sort() error - java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
I am trying to write a program for my course that sorts an array of objects.

Does anyone know why I am getting this error? Snippets of code included below!

Student object

```<code>/* Class for storing students */
public class Student {
  private String name;
  private int mark;

  //Constructor
  public Student(String gName, int gMark) {
    name = gName;
    mark = gMark;
  }

  //Get Mark
    public int getMark() {
    return mark;
  }
  //Compare to
   public int compareTo(Student gStudent) {
    return this.mark - (int) gStudent.getMark();
  }
</code>```

}

And putting these students in the array marks (of student objects);

```<code>  //Create array
    Student[] marks = new Student[numberOfMarks];

    //Input for each student
    for (int cItem = 0; cItem < numberOfMarks; cItem++) {
        System.out.print("Please enter student number "+(cItem + 1)+"'s name: ");
        String cName = markScanner.nextLine();
        System.out.print("Please enter "+cName+"'s mark: ");
        int cMark = markScanner.nextInt();
        //Skip line
        markScanner.nextLine();
        marks[cItem] = new Student(cName, cMark);
    }
</code>```

However the sort doesn't seem to work

```<code>//Sorting
Arrays.sort(marks);
</code>```

And produces the error:

```<code>Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    at MarkAnalysis.main(MarkAnalysis.java:33)
</code>```

And produce the error

答:
```<code>public class Student implements Comparable<Student> {
  ...
}
</code>```

Body:
I am trying to write a program for my course that sorts an array of objects.

Does anyone know why I am getting this error? Snippets of code included below!

Student object

/* Class for storing students */
public class Student {
  private String name;
  private int mark;

  //Constructor
  public Student(String gName, int gMark) {
    name = gName;
    mark = gMark;
  }

  //Get Mark
    public int getMark() {
    return mark;
  }
  //Compare to
   public int compareTo(Student gStudent) {
    return this.mark - (int) gStudent.getMark();
  }

}

And putting these students in the array marks (of student objects);

  //Create array
    Student[] marks = new Student[numberOfMarks];

    //Input for each student
    for (int cItem = 0; cItem < numberOfMarks; cItem++) {
        System.out.print("Please enter student number "+(cItem + 1)+"'s name: ");
        String cName = markScanner.nextLine();
        System.out.print("Please enter "+cName+"'s mark: ");
        int cMark = markScanner.nextInt();
        //Skip line
        markScanner.nextLine();
        marks[cItem] = new Student(cName, cMark);
    }

However the sort doesn't seem to work

//Sorting
Arrays.sort(marks);

And produces the error:

Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    at MarkAnalysis.main(MarkAnalysis.java:33)

And produce the error


问:
Android 6.0+ Unable to resume activity , did not call finish() prior to onResume() completing
This my activity,no layout

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onResume() {
    super.onResume();
    if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
        Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
            runNFCTagData(msgs[0].getRecords()[0].getPayload());
            startActivity(new Intent(this, AlarmList.class));
        } else {
            Toast.makeText(this, getResources().getString(R.string.nfc_ndef_not_found), Toast.LENGTH_LONG).show();
        }
    }
}
</code>```

　 Run it on android 6.0+ and it will be broken, you can see Unable to resume activity , did not call finish() prior to onResume()completing', but 6.0- is OK.I find a solution and it worked, but I don`t know why?

This is my solution

　 @Override
    protected void onStart() {
        super.onStart();
        setVisible(true);
    }

答:
You are using API > 21, so you can use the following style on your activity :

```<code>Theme.Translucent.NoTitleBar
</code>```

The trick with "setVisible(true)" is still not needed.

Body:
This my activity,no layout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onResume() {
    super.onResume();
    if (getIntent().getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
        Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {
            NdefMessage[] msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
            runNFCTagData(msgs[0].getRecords()[0].getPayload());
            startActivity(new Intent(this, AlarmList.class));
        } else {
            Toast.makeText(this, getResources().getString(R.string.nfc_ndef_not_found), Toast.LENGTH_LONG).show();
        }
    }
}

　 Run it on android 6.0+ and it will be broken, you can see Unable to resume activity , did not call finish() prior to onResume()completing', but 6.0- is OK.I find a solution and it worked, but I don`t know why?

This is my solution

　 @Override
    protected void onStart() {
        super.onStart();
        setVisible(true);
    }

Body:
You are using API > 21, so you can use the following style on your activity :

Theme.Translucent.NoTitleBar

The trick with "setVisible(true)" is still not needed.


问:
VLOOKUP (or INDEX/MATCH) through multiple columns, but get value from other column
Hope to have a relatively simple question.

I use VLOOKUP every day, for comparing 2 lists of itemnumbers and corresponding stock.

In a new situation itemnumbers are not longer in only one column, but the correct one could be in column A, B or C. While the stock is always in F.

Is it possible with VLOOKUP, or INDEX/MATCH to fill the corresponding stock in the orange cells, according to the itemnumber in one of three columns?

Many thanks in advance, Richard

Body:
Use AGGREGATE:

=INDEX(F:F,AGGRAGATE(15,6,ROW($A$1:$C$9)/($A$1:$C$9=B19),1))


问:
Direct way of telling ifelse to ignore NA
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

```<code>df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA
</code>```

... instead of the desired

```<code>#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

```<code>ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
</code>```

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

```<code>df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

```<code>ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

答:
dplyr::case_when is a convenient alternative to cascading ifelse calls:

library(dplyr)

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))

df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                 b == 1 ~ 'b==1',
                                 c == 1 ~ 'c==1'))
#>    a  b  c equals
#> 1  1 NA NA   a==1
#> 2  1 NA NA   a==1
#> 3 NA  1 NA   b==1
#> 4 NA  1 NA   b==1
#> 5 NA NA  1   c==1
#> 6 NA NA  1   c==1
```

<p>It cascades like <code>ifelse</code>, so if the first condition is true, the first result is returned even if the second and third conditions are true too. If none are true, it returns <code>NA</code>:</p>

<pre class="lang-r prettyprint-override"><code>set.seed(47)
df <- setNames(as.data.frame(matrix(sample(c(1, NA), 30, replace = TRUE), 10)), letters[1:3])

df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                 b == 1 ~ 'b==1',
                                 c == 1 ~ 'c==1'))
#>     a  b  c equals
#> 1  NA  1  1   b==1
#> 2   1 NA NA   a==1
#> 3  NA  1 NA   b==1
#> 4  NA NA  1   c==1
#> 5  NA NA NA   <NA>
#> 6  NA NA  1   c==1
#> 7   1  1  1   a==1
#> 8   1  1  1   a==1
#> 9  NA  1 NA   b==1
#> 10 NA  1 NA   b==1
</code>```

Plus it's fast:

set.seed(47)
df <- setNames(as.data.frame(matrix(sample(c(1, NA), 3 * 1e5, replace = TRUE), ncol = 3)), letters[1:3])

microbenchmark::microbenchmark(
    original = {
        ifelse(df$a == 1 &  !is.na(df$a), "a==1",
               ifelse(df$b == 1 & !is.na(df$b), "b==1",
                      ifelse(df$c == 1 & !is.na(df$c), "c==1", NA)))},
    akrun = {
        v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
        i1 <- !is.na(v1)
        v1[i1] <- paste0(v1[i1], "==1")
    },
    amatsuo_net = {
        ifelse(df$a %in% 1, "a==1",
               ifelse(df$b %in% 1, "b==1",
                      ifelse(df$c %in% 1, "c==1", NA)))
    },
    alistaire = {
        df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                         b == 1 ~ 'b==1',
                                         c == 1 ~ 'c==1'))
    }
)
#> Unit: milliseconds
#>         expr      min       lq      mean    median        uq       max neval
#>     original 81.19896 86.11843 110.93882 123.92463 128.58037 171.11026   100
#>        akrun 27.50351 30.99127  38.98353  32.67991  34.64947  77.98958   100
#>  amatsuo_net 83.75744 88.54095 109.22226 110.40066 129.02168 170.92911   100
#>    alistaire 16.57426 18.91951  21.73293  19.29925  24.30350  33.83180   100
```

Body:
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA

... instead of the desired

#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

Body:
dplyr::case_when is a convenient alternative to cascading ifelse calls:

library(dplyr)

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))

df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                 b == 1 ~ 'b==1',
                                 c == 1 ~ 'c==1'))
#>    a  b  c equals
#> 1  1 NA NA   a==1
#> 2  1 NA NA   a==1
#> 3 NA  1 NA   b==1
#> 4 NA  1 NA   b==1
#> 5 NA NA  1   c==1
#> 6 NA NA  1   c==1

It cascades like ifelse, so if the first condition is true, the first result is returned even if the second and third conditions are true too. If none are true, it returns NA:

set.seed(47)
df <- setNames(as.data.frame(matrix(sample(c(1, NA), 30, replace = TRUE), 10)), letters[1:3])

df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                 b == 1 ~ 'b==1',
                                 c == 1 ~ 'c==1'))
#>     a  b  c equals
#> 1  NA  1  1   b==1
#> 2   1 NA NA   a==1
#> 3  NA  1 NA   b==1
#> 4  NA NA  1   c==1
#> 5  NA NA NA   <NA>
#> 6  NA NA  1   c==1
#> 7   1  1  1   a==1
#> 8   1  1  1   a==1
#> 9  NA  1 NA   b==1
#> 10 NA  1 NA   b==1

Plus it's fast:

set.seed(47)
df <- setNames(as.data.frame(matrix(sample(c(1, NA), 3 * 1e5, replace = TRUE), ncol = 3)), letters[1:3])

microbenchmark::microbenchmark(
    original = {
        ifelse(df$a == 1 &  !is.na(df$a), "a==1",
               ifelse(df$b == 1 & !is.na(df$b), "b==1",
                      ifelse(df$c == 1 & !is.na(df$c), "c==1", NA)))},
    akrun = {
        v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
        i1 <- !is.na(v1)
        v1[i1] <- paste0(v1[i1], "==1")
    },
    amatsuo_net = {
        ifelse(df$a %in% 1, "a==1",
               ifelse(df$b %in% 1, "b==1",
                      ifelse(df$c %in% 1, "c==1", NA)))
    },
    alistaire = {
        df %>% mutate(equals = case_when(a == 1 ~ 'a==1',
                                         b == 1 ~ 'b==1',
                                         c == 1 ~ 'c==1'))
    }
)
#> Unit: milliseconds
#>         expr      min       lq      mean    median        uq       max neval
#>     original 81.19896 86.11843 110.93882 123.92463 128.58037 171.11026   100
#>        akrun 27.50351 30.99127  38.98353  32.67991  34.64947  77.98958   100
#>  amatsuo_net 83.75744 88.54095 109.22226 110.40066 129.02168 170.92911   100
#>    alistaire 16.57426 18.91951  21.73293  19.29925  24.30350  33.83180   100


问:
Calculating difference in time
I'm trying to set the difference (in hours, minutes and seconds) between two dates into a variable. The format is +%y%m%d%H%M%S (for example: 170607162412).

For example: 170607162400 and 170607162410 = 00:00:10

I tried a lot but i couldn't figure it out.

Title: Calculating difference in time

Body:
Use date to put into seconds, then subtract.  Then parse out minutes and seconds:

$ var1=170607162400
$ var2=170607162410
$ var="$var1"
$ date1="20${var:0:2}/${var:2:2}/${var:4:2 {var:6:2}:${var:8:2}:${var:10:2}"
$ var="$var2"
$ date2="20${var:0:2}/${var:2:2}/${var:4:2} ${var:6:2}:${var:8:2}:${var:10:2}"
$ sec1=$( date -d "$date1" '+%s' )
$ echo $sec1
1496867040
$ sec2=$( date -d "$date2" '+%s' )
$ echo $sec2
1496867050
$ dt=$(( sec2 - sec1 ))
$ echo $dt
10
$ min=$(( dt/60 ))
$ sec=$(( dt - 60*min ))
$ minsec=$( printf "%02d:%02d" "$min" "$sec" )
$ echo "$minsec"
00:10

If you need hours, too, change those last lines like so:

$ hrs=$(( dt/3600 ))
$ min=$(( (dt - 3600*hrs) / 60 ))
$ sec=$(( dt - 3600*hrs - 60*min ))
$ hms=$( printf "%d:%02d:%02d" "$hrs" "$min" "$sec" )


问:
Get all children SVG element IDs except specific one using not()
I'm trying to get the IDs of SVG elements except for a specific one being passed to the highlight() function by combining the children() method with the not() method singling out the specific ID.

var allOthers = $(".container").children().not(elem);

I want to affect all other elements' opacity. I tried this way of singling out a specific element ID out of a whole array of them before on some other pr0ject, but I don't know why it says that allOthers is undefined. Am I doing something wrong here?

I made a fiddle.

答:
It is not allOthers which is undefined, it is allOthers.style. You are using vanilla js when you meant to use jQuery, change...

```<code>allOthers.style.opacity = "0.1";
</code>```

for:

```<code>allOthers.css("opacity", "0.1");
</code>```

Body:
It is not allOthers which is undefined, it is allOthers.style. You are using vanilla js when you meant to use jQuery, change...

allOthers.style.opacity = "0.1";

for:

allOthers.css("opacity", "0.1");


问:
Default value for fields
I have problem accessing fields from an object in a python script I did. Basically it boils down to this little piece of code:

```<code>from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')
</code>```

So when in the python console I try to access an element of my enum with:

```<code>Foo.test.foo
</code>```

I would expect it to print me 'bla' which is the value I pass to the constructor (or at least it should print 'works' which would be the default value I've assigned).

What I actually get is

```<code>AttributeError: 'Foo' object has no attribute 'foo'
</code>```

you can probably tell by now that I'm pretty new to python and especially the concept objects in python (I mostly write code in Java which might lead to some missconceptions from my part about the behaviour of objects in python).

What I figured out though is that I can do:

```<code>Foo.test.foo = 'whatever'
</code>```

and assign a value to foo in this way. But when doing this I can also assign a value to a field I haven't even specified in the constructor such as:

```<code>Foo.test.noField = 'shouldn't even exist'
</code>```

and it will work just as fine which I don't understand at all.

I would be really glad about some clarification how objects work in python and/or how I could realize an enum of a class in python.

EDIT: Apparently the code behaves the way I want it to if I remove the inheritance from Enum.

答:
As @jdehesa noted, Enum members are instances of their parent Enum class.  If you need them to also be instances of some other class simply inherit from it as well:

```<code>class Foo(AbstractFoo, Enum):
    test = 'bla', 'tada'
</code>```

Note that you no longer need to call AbstractFoo directly.

Title: Default value for fields

Body:
I have problem accessing fields from an object in a python script I did. Basically it boils down to this little piece of code:

from enum import Enum

class AbstractFoo:
    def __init__(self, foo='works', bar='nope'):
        self.foo = foo
        self.bar = bar

class Foo(Enum):
    test = AbstractFoo('bla', 'tada')

So when in the python console I try to access an element of my enum with:

Foo.test.foo

I would expect it to print me 'bla' which is the value I pass to the constructor (or at least it should print 'works' which would be the default value I've assigned).

What I actually get is

AttributeError: 'Foo' object has no attribute 'foo'

you can probably tell by now that I'm pretty new to python and especially the concept objects in python (I mostly write code in Java which might lead to some missconceptions from my part about the behaviour of objects in python).

What I figured out though is that I can do:

Foo.test.foo = 'whatever'

and assign a value to foo in this way. But when doing this I can also assign a value to a field I haven't even specified in the constructor such as:

Foo.test.noField = 'shouldn't even exist'

and it will work just as fine which I don't understand at all.

I would be really glad about some clarification how objects work in python and/or how I could realize an enum of a class in python.

EDIT: Apparently the code behaves the way I want it to if I remove the inheritance from Enum.

Body:
As @jdehesa noted, Enum members are instances of their parent Enum class.  If you need them to also be instances of some other class simply inherit from it as well:

class Foo(AbstractFoo, Enum):
    test = 'bla', 'tada'

Note that you no longer need to call AbstractFoo directly.


问:
Font Awesome not working in offline mode with jsp
I have searched throughout many articles and i still doesn't know why it's not working on offline mode, when i import a cdn link of cdn instead of lib from fontawesome then it's working just fine

```<code>    <link href="css/font-awesome-4.6.3/css/font-awesome.min.css" rel="stylesheet">
</code>```

p/s: the icon is not showing up, they are all blank +_+

答:
First, in your Cache Manifest, put the actual names of the font files in the folder:

```<code>fa/css/font-awesome.css
fa/fonts/fontawesome-webfont.ttf
fa/fonts/fontawesome-webfont.woff
fa/fonts/fontawesome-webfont.woff2
</code>```

This will make sure the files are deployed with your app.

Next, have a look at font-awesome.css. Notice the file names are referenced like this:

```<code>url('../fonts/fontawesome-webfont.woff2?v=4.7.0')
</code>```

The names do not match the names in the manifest, so the files are not found. You need to modify fontawesome.css: modifying the names in the Cache Manifest will not work. Remove the suffix in names in fontawesome.css to be like this:

```<code>url('../fonts/fontawesome-webfont.woff2')
</code>```

Seems like a bit of a hole in the implementation of Cache Manifest.

Body:
I have searched throughout many articles and i still doesn't know why it's not working on offline mode, when i import a cdn link of cdn instead of lib from fontawesome then it's working just fine

    <link href="css/font-awesome-4.6.3/css/font-awesome.min.css" rel="stylesheet">

p/s: the icon is not showing up, they are all blank +_+

Body:
First, in your Cache Manifest, put the actual names of the font files in the folder:

fa/css/font-awesome.css
fa/fonts/fontawesome-webfont.ttf
fa/fonts/fontawesome-webfont.woff
fa/fonts/fontawesome-webfont.woff2

This will make sure the files are deployed with your app.

Next, have a look at font-awesome.css. Notice the file names are referenced like this:

url('../fonts/fontawesome-webfont.woff2?v=4.7.0')

The names do not match the names in the manifest, so the files are not found. You need to modify fontawesome.css: modifying the names in the Cache Manifest will not work. Remove the suffix in names in fontawesome.css to be like this:

url('../fonts/fontawesome-webfont.woff2')

Seems like a bit of a hole in the implementation of Cache Manifest.


问:
Adding button to each row in react (flux) fixed data table
I'm trying to add button to each row in fixed data table, but I don't know how. My current code:

```<code>var Details = React.createClass({

    getInitialState() {
            return {
              rows: usersStore.getUsersList(),
              filteredRows: null,
              filterBy: null,
            };
          },

           componentWillMount() {
            this._filterRowsBy(this.state.filterBy);
          },

          _rowGetter(rowIndex) {
            return this.state.filteredRows[rowIndex];
          },

          _filterRowsBy(filterBy) {
            var rows = this.state.rows.slice();
            var filteredRows = filterBy ? rows.filter(function(row){
              return row.name.toLowerCase().indexOf(filterBy.toLowerCase()) >= 0
            }) : rows;

            this.setState({
              filteredRows,
              filterBy,
            });
          },

          _onFilterChange(e) {
            this._filterRowsBy(e.target.value);
          },

    render: function () {

        return (

            <div>
                <label>filter by <input onChange={this._onFilterChange} /></label>
                <Table
                 height={200}
                  rowHeight={30}
                  rowGetter={this._rowGetter}
                  rowsCount={this.state.filteredRows.length}
                  width={450}
                  maxHeight={450}
                  headerHeight={40}>
                  <Column
                    label="Name"
                    width={270}
                    dataKey="name"
                  />
                  <Column
                    label="Age"
                    width={100}
                    dataKey="age"
                  />
                  <Column
                    label="Qualification"
                    width={120}
                    dataKey="Qualification"
                  />
                  <Column label="Edit"
                    width={120}>
                    <button type="button" className="btn btn-default" onClick={this.update}>Update</button>
                  </Column>
                </Table>
            </div>
        );
    }
})
</code>```

While using this code it showing datakey is mandatory and if I remove column tags and adding only button in table also its not accepting.

答:
There has been a v6 migration of APIs that deprecated constructs such as the CellRenderer.

https://facebook.github.io/fixed-data-table/v6-migration.html

But the new solution is pretty cool.

That page hints at how to write own custom renderers that
can inject own HTML elements in list columns.

Body:
I'm trying to add button to each row in fixed data table, but I don't know how. My current code:

var Details = React.createClass({

    getInitialState() {
            return {
              rows: usersStore.getUsersList(),
              filteredRows: null,
              filterBy: null,
            };
          },

           componentWillMount() {
            this._filterRowsBy(this.state.filterBy);
          },

          _rowGetter(rowIndex) {
            return this.state.filteredRows[rowIndex];
          },

          _filterRowsBy(filterBy) {
            var rows = this.state.rows.slice();
            var filteredRows = filterBy ? rows.filter(function(row){
              return row.name.toLowerCase().indexOf(filterBy.toLowerCase()) >= 0
            }) : rows;

            this.setState({
              filteredRows,
              filterBy,
            });
          },

          _onFilterChange(e) {
            this._filterRowsBy(e.target.value);
          },

    render: function () {

        return (

                filter by <input onChange={this._onFilterChange} />

                  <Column
                    label="Name"
                    width={270}
                    dataKey="name"
                  />
                  <Column
                    label="Age"
                    width={100}
                    dataKey="age"
                  />
                  <Column
                    label="Qualification"
                    width={120}
                    dataKey="Qualification"
                  />
                  <Column label="Edit"
                    width={120}>
                    <button type="button" className="btn btn-default" onClick={this.update}>Update</button>
                  </Column>

        );
    }
})

While using this code it showing datakey is mandatory and if I remove column tags and adding only button in table also its not accepting.