问:
Java Creating Instance of BufferedImage Freezes Program
I'm experiencing something really strange, and I don't know what's causing it at all. This is the problematic line of code:

```<code>BufferedImage out = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);
</code>```

Upon calling this, all threads freeze and everything stops. I've tried putting this in its own thread and the main thread, the same thing occurs. I am using LWJGL3, so that might be an issue, but I don't see how it could be.

Edit: Does not occur in a blank project without LWJGL in or out of -XstartOnFirstThread

答:
Ok! I found the solution. Turns out, all it takes is the following JVM argument: -Djava.awt.headless=true You also have to make sure that you aren't running it in the main thread, you have to do it outside of the thread where GLFW is initialized.

All of this only applies if you are running LWJGL on Mac, Linux and Windows don't have this issue.

Body:
I'm experiencing something really strange, and I don't know what's causing it at all. This is the problematic line of code:

BufferedImage out = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);

Upon calling this, all threads freeze and everything stops. I've tried putting this in its own thread and the main thread, the same thing occurs. I am using LWJGL3, so that might be an issue, but I don't see how it could be.

Edit: Does not occur in a blank project without LWJGL in or out of -XstartOnFirstThread


来源: stackexchange

问:
Spring Data Neo4j 4 limitations?
I am evaluating if I should use Spring Data Neo4j 4 or directly use the native APIs that Neo4j has. Is it possible to get the full potential of Neo4j when using Spring Data Neo4j 4 or will it limit my future usage of Neo4j?

I see the benefit with that POJO simplifies the storage of objects in the database.

答:
There are 2 "native" APIs

There is the Java API, that you can access in unmanaged extensions or when using Neo4j as embedded

Neo4j java driver (a.k.a. Bolt) - this what Neo itself promotes the most

OGM (and therefore SDN) supports both embedded and bolt, with new features of Bolt being covered shortly after being released.

There are some features of the embedded database that can't be used (at least not directly, you may use them through user-defined procedures/functions).  E.g. traversals etc..

You should also consider other aspects of your use case, like performance, if your domain model matches the graph model etc..

ContentLicense: CC BY-SA 3.0

Title: Spring Data Neo4j 4 limitations?


问:
Finding First day of week via php

Possible Duplicate:

  Get first day of week in PHP?

Hi,

I want to find first and last date of current week and last week.
Similarly I want to find first and last date of current month and last month.

This has to be done in PHP. Please help.

答:
Here's a function for the first and last day of the week:

```<code>function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
</code>```

It can probably be adapted to do month as well, but I wanted to get my answer in! :)

ContentLicense: CC BY-SA 2.5

Title: Finding First day of week via php

Body:
Here's a function for the first and last day of the week:

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));

It can probably be adapted to do month as well, but I wanted to get my answer in! :)


问:
Converting into date-time format in pandas?
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

```<code>2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00
</code>```

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

答:
Let's say I have two strings 2017-06-06 and 1944-06-06 and I wanted to get the difference (what Python calls a timedelta) between the two.

First, I'll need to import datetime. Then I'll need to get both of those strings into datetime objects:

```<code>>>> a = datetime.datetime.strptime('2017-06-06', '%Y-%m-%d')
>>> b = datetime.datetime.strptime('1944-06-06', '%Y-%m-%d')
</code>```

That will give us two datetime objects that can be used in arithmetic functions that will return a timedelta object:

```<code>>>> c = abs((a-b).days)
</code>```

This will give us 26663, and days is the largest resolution that timedelta supports: documentation

Body:
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

Body:
Let's say I have two strings 2017-06-06 and 1944-06-06 and I wanted to get the difference (what Python calls a timedelta) between the two.

First, I'll need to import datetime. Then I'll need to get both of those strings into datetime objects:

>>> a = datetime.datetime.strptime('2017-06-06', '%Y-%m-%d')
>>> b = datetime.datetime.strptime('1944-06-06', '%Y-%m-%d')

That will give us two datetime objects that can be used in arithmetic functions that will return a timedelta object:

>>> c = abs((a-b).days)

This will give us 26663, and days is the largest resolution that timedelta supports: documentation


问:
Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?
I am following this article on RazorGenerator and it say's that I must add references to:

System.Web.Helpers.dll

System.Web.WebPages.dll

System.Web.Razor.dll

The only one I can see when I do Add Reference is System.Web.Razor, but I don't know where the other ones are.

答: As for VS2017 I didn't find it in "extensions", there's a Nuget package called "microsoft-web-helpers" that seems to be equivalent to System.Web.Helpers.</p>


问:
How to create a new column with sub string based on a column with long string using ifelse and grepl?
First view rows of the column ac$summary

```<code>    1
    during a demonstration flight, a u.s. army flyer flown by orville wright nose-dived into the ground from a height of approximately 75 feet, killing lt. thomas e. selfridge who was a passenger. this was the first recorded airplane fatality in history. one of two propellers separated in flight, tearing loose the wires bracing the rudder and causing the loss of control of the aircraft. orville wright suffered broken ribs, pelvis and a leg. selfridge suffered a crushed skull and died a short time later.
    2
    first u.s. dirigible akron exploded just offshore at an altitude of 1,000 ft. during a test flight.
    3
    the first fatal airplane accident in canada occurred when american barnstormer, john m. bryant, california aviator was killed.
    4
    the airship flew into a thunderstorm and encountered a severe downdraft crashing 20 miles north of helgoland island into the sea. the ship broke in two and the control car immediately sank drowning its occupants.
    5
    hydrogen gas which was being vented was sucked into the forward engine and ignited causing the airship to explode and burn at 3,000 ft..
    6
    crashed into trees while attempting to land after being shot down by british and french aircraft.
    7
    exploded and burned near neuwerk island, when hydrogen gas, being vented, was ignited by lightning.
    8
    crashed near the black sea, cause unknown.
    9
    shot down by british aircraft crashing in flames.
    10
    shot down in flames by the british 39th home defence squadron.
    11
    crashed in a storm.
    12
    shot down by british anti-aircraft fire and aircraft and crashed into the north sea.
    13
    caught fire and crashed.
</code>```

I want to make ac$sumnew column based on ac$summary

I wrote following code, but it's not returning the desired output
    both & and | were used. When | was used, results were irregular. Sometimes right, sometimes wrong.

```<code>    ac$sumnew = ifelse(grepl("missing & crashed",ac$Summary),"missing and crashed",
        ifelse(grepl("shot | crashed",ac$Summary),"shot down and crashed",
        ifelse(grepl("struck | lightening",ac$Summary),"struck by lightening and crashed",
         ifelse(grepl("struck | bird & crashed",ac$Summary),"struck by bird and crashed",
         ifelse(grepl("exploded | crashed",ac$Summary),"exploded and crashed",
         ifelse(grepl("engine | failure",ac$Summary),"engine failure",
         ifelse(grepl("fog | crashed",ac$Summary),"crashed due to heavy fog",
         ifelse(grepl("fire | crashed",ac$Summary),"caught fire and crashed",
         ifelse(grepl("shot",ac$Summary),"shot down",
         ifelse(grepl("crashed",ac$Summary),"Crashed",
         ifelse(grepl("shot",ac$Summary),"Shot down",
         ifelse(grepl("disappeared",ac$Summary),"Disappeared",
         ifelse(grepl("struck | obstacle | crashed ",ac$Summary),"struck by obstacle and Crashed",
         ifelse(grepl("crashed",ac$Summary),"crashed",
         ifelse(grepl("exploded",ac$Summary),"exploded",
         ifelse(grepl("fire",ac$Summary),"caught fire","others"))))))))))))))))
</code>```

For example if the plane has been shot, it should return "shot down"

if it's just crashed, output should return "crashed"

if it is both missing and crashed it should return "missing and crashed"

I cannot get this part correctly using & and | also

output obtained shown below

```<code>1
others
2
exploded and crashed
3
others
4
others
5
engine failure
6
shot down and crashed
7
exploded and crashed
8
Crashed
9
shot down and crashed
10
shot down and crashed
11
Crashed
12
missing and crashed
13
missing and crashed
14
missing and crashed
15
Crashed
16
shot down and crashed
17
shot down and crashed
</code>```

答:
I think you have a hierarchy problem. R tests these sequentially, so you have to arrange it the appropriate way. Here is a link to help with that: https://www.programiz.com/r-programming/if-else-statement.

```<code>ac$new  <-ifelse(apply(sapply(c("struck","bird","crash"), grepl, as.character(s$s)), 1, all) ,"struck by bird and crashed",
          ifelse(apply(sapply(c("struck","obstacle","crash"), grepl, as.character(s$s)), 1, all) ,"struck by obstacle and Crashed",
          ifelse(apply(sapply(c("miss" , "crash"), grepl, as.character(s$s)), 1, all) ,"missing and crashed",
          ifelse(apply(sapply(c("shot" , "crash"), grepl, as.character(s$s)), 1, all) ,"shot down and crashed",
          ifelse(apply(sapply(c("struck","lightening"), grepl, as.character(s$s)), 1, all) ,"struck by lightening and crashed",
          ifelse(apply(sapply(c("explode","crash"), grepl, as.character(s$s)), 1 , all) ,"exploded and crashed",
          ifelse(apply(sapply(c("engine|failure"), grepl, as.character(s$s)), 1 , all) ,"engine failure",
          ifelse(apply(sapply(c("fog","crash"), grepl, as.character(s$s)) , 1, all) ,"crashed due to heavy fog",
          ifelse(apply(sapply(c("fire","crash"), grepl, as.character(s$s)), 1, all) ,"caught fire and crashed",
          ifelse(apply(sapply("shot", grepl, as.character(s$s)), 1, all) ,"shot down",
          ifelse(apply(sapply("crash", grepl, as.character(s$s)), 1, all), "crashed",
          ifelse(apply(sapply("explode", grepl, as.character(s$s)), 1, all), "exploded",
          ifelse(apply(sapply("fire", grepl, as.character(s$s)), 1, all),"caught fire",
          ifelse(apply(sapply("disappear", grepl, as.character(s$s)), 1, all), "Disappeared","others"))))))))))))))
</code>```

Now, this works by checking for all words in the c(), and then equating the value to ac$new, except engine|failure. Also, because we are working with words, you want to use the simplest stem word present to check for all variations: so for example, instead of using "missing", you should use "miss".

I got

```<code>1                   others
2                 exploded
3                   others
4                  crashed
5           engine failure
6    shot down and crashed
7                 exploded
8                  crashed
9    shot down and crashed
10               shot down
11                 crashed
12   shot down and crashed
13 caught fire and crashed
</code>```

Some words don't match above because I did check for all words. The reason I checked for all words is because you had single words identified in the latter part of your "ifelse" chain. I did do an eyeball test, and I think mine is correct based on checking for all words.

Btw, this is tedious, especially if you want to expand the list. You may want to use something like,

```<code>ac <- data.frame(s = as.character(t), word.que = seq(1, length(t), by = 1))

ac$word.count <- sapply(gregexpr(" ", ac$s), length) + 1

new.mat <- data.frame(word.que = rep.int(ac$word.que, ac$word.count), word = unlist(strsplit(as.character(ac$s), split = " ")))
words.of.interest <- c("struck|bird|crash|obstacle|miss|shot|struck|lightening|explode|engine|failure|fog|fire|disappear")
new.mats<- new.mat %>%
           mutate(word = gsub("\\,", "", gsub("\\.", "", word))) %>%
           mutate(word.interest = ifelse(grepl(words.of.interest, as.character(word)), 1, 0)) %>%
           filter(word.interest == 1) %>%
           group_by(word.que) %>%
           summarise(word.list = paste0(unique(word), collapse = "; ")) %>%
           full_join(ac, by = "word.que" ) %>%
           arrange(word.que) %>%
           mutate(word.list = ifelse(is.na(word.list), 'other', word.list))
</code>```

This will create a more efficient search list for you to construct by. The result is

```<code>   word.que           word.list
1         1               other
2         2            exploded
3         3               other
4         4            crashing
5         5     engine; explode
6         6       crashed; shot
7         7            exploded
8         8             crashed
9         9      shot; crashing
10       10                shot
11       11             crashed
12       12 shot; fire; crashed
13       13       fire; crashed
</code>```

As well as your text variable and word.count. This may be more efficient in the long run as well.

Body:
First view rows of the column ac$summary

    1
    during a demonstration flight, a u.s. army flyer flown by orville wright nose-dived into the ground from a height of approximately 75 feet, killing lt. thomas e. selfridge who was a passenger. this was the first recorded airplane fatality in history. one of two propellers separated in flight, tearing loose the wires bracing the rudder and causing the loss of control of the aircraft. orville wright suffered broken ribs, pelvis and a leg. selfridge suffered a crushed skull and died a short time later.
    2
    first u.s. dirigible akron exploded just offshore at an altitude of 1,000 ft. during a test flight.
    3
    the first fatal airplane accident in canada occurred when american barnstormer, john m. bryant, california aviator was killed.
    4
    the airship flew into a thunderstorm and encountered a severe downdraft crashing 20 miles north of helgoland island into the sea. the ship broke in two and the control car immediately sank drowning its occupants.
    5
    hydrogen gas which was being vented was sucked into the forward engine and ignited causing the airship to explode and burn at 3,000 ft..
    6
    crashed into trees while attempting to land after being shot down by british and french aircraft.
    7
    exploded and burned near neuwerk island, when hydrogen gas, being vented, was ignited by lightning.
    8
    crashed near the black sea, cause unknown.
    9
    shot down by british aircraft crashing in flames.
    10
    shot down in flames by the british 39th home defence squadron.
    11
    crashed in a storm.
    12
    shot down by british anti-aircraft fire and aircraft and crashed into the north sea.
    13
    caught fire and crashed.

I want to make ac$sumnew column based on ac$summary

I wrote following code, but it's not returning the desired output
    both & and | were used. When | was used, results were irregular. Sometimes right, sometimes wrong.

    ac$sumnew = ifelse(grepl("missing & crashed",ac$Summary),"missing and crashed",
        ifelse(grepl("shot | crashed",ac$Summary),"shot down and crashed",
        ifelse(grepl("struck | lightening",ac$Summary),"struck by lightening and crashed",
         ifelse(grepl("struck | bird & crashed",ac$Summary),"struck by bird and crashed",
         ifelse(grepl("exploded | crashed",ac$Summary),"exploded and crashed",
         ifelse(grepl("engine | failure",ac$Summary),"engine failure",
         ifelse(grepl("fog | crashed",ac$Summary),"crashed due to heavy fog",
         ifelse(grepl("fire | crashed",ac$Summary),"caught fire and crashed",
         ifelse(grepl("shot",ac$Summary),"shot down",
         ifelse(grepl("crashed",ac$Summary),"Crashed",
         ifelse(grepl("shot",ac$Summary),"Shot down",
         ifelse(grepl("disappeared",ac$Summary),"Disappeared",
         ifelse(grepl("struck | obstacle | crashed ",ac$Summary),"struck by obstacle and Crashed",
         ifelse(grepl("crashed",ac$Summary),"crashed",
         ifelse(grepl("exploded",ac$Summary),"exploded",
         ifelse(grepl("fire",ac$Summary),"caught fire","others"))))))))))))))))

For example if the plane has been shot, it should return "shot down"

if it's just crashed, output should return "crashed"

if it is both missing and crashed it should return "missing and crashed"

I cannot get this part correctly using & and | also

output obtained shown below

1
others
2
exploded and crashed
3
others
4
others
5
engine failure
6
shot down and crashed
7
exploded and crashed
8
Crashed
9
shot down and crashed
10
shot down and crashed
11
Crashed
12
missing and crashed
13
missing and crashed
14
missing and crashed
15
Crashed
16
shot down and crashed
17
shot down and crashed

Body:
I think you have a hierarchy problem. R tests these sequentially, so you have to arrange it the appropriate way. Here is a link to help with that: https://www.programiz.com/r-programming/if-else-statement.

ac$new  <-ifelse(apply(sapply(c("struck","bird","crash"), grepl, as.character(s$s)), 1, all) ,"struck by bird and crashed",
          ifelse(apply(sapply(c("struck","obstacle","crash"), grepl, as.character(s$s)), 1, all) ,"struck by obstacle and Crashed",
          ifelse(apply(sapply(c("miss" , "crash"), grepl, as.character(s$s)), 1, all) ,"missing and crashed",
          ifelse(apply(sapply(c("shot" , "crash"), grepl, as.character(s$s)), 1, all) ,"shot down and crashed",
          ifelse(apply(sapply(c("struck","lightening"), grepl, as.character(s$s)), 1, all) ,"struck by lightening and crashed",
          ifelse(apply(sapply(c("explode","crash"), grepl, as.character(s$s)), 1 , all) ,"exploded and crashed",
          ifelse(apply(sapply(c("engine|failure"), grepl, as.character(s$s)), 1 , all) ,"engine failure",
          ifelse(apply(sapply(c("fog","crash"), grepl, as.character(s$s)) , 1, all) ,"crashed due to heavy fog",
          ifelse(apply(sapply(c("fire","crash"), grepl, as.character(s$s)), 1, all) ,"caught fire and crashed",
          ifelse(apply(sapply("shot", grepl, as.character(s$s)), 1, all) ,"shot down",
          ifelse(apply(sapply("crash", grepl, as.character(s$s)), 1, all), "crashed",
          ifelse(apply(sapply("explode", grepl, as.character(s$s)), 1, all), "exploded",
          ifelse(apply(sapply("fire", grepl, as.character(s$s)), 1, all),"caught fire",
          ifelse(apply(sapply("disappear", grepl, as.character(s$s)), 1, all), "Disappeared","others"))))))))))))))

Now, this works by checking for all words in the c(), and then equating the value to ac$new, except engine|failure. Also, because we are working with words, you want to use the simplest stem word present to check for all variations: so for example, instead of using "missing", you should use "miss".

I got

1                   others
2                 exploded
3                   others
4                  crashed
5           engine failure
6    shot down and crashed
7                 exploded
8                  crashed
9    shot down and crashed
10               shot down
11                 crashed
12   shot down and crashed
13 caught fire and crashed

Some words don't match above because I did check for all words. The reason I checked for all words is because you had single words identified in the latter part of your "ifelse" chain. I did do an eyeball test, and I think mine is correct based on checking for all words.

Btw, this is tedious, especially if you want to expand the list. You may want to use something like,

ac <- data.frame(s = as.character(t), word.que = seq(1, length(t), by = 1))

ac$word.count <- sapply(gregexpr(" ", ac$s), length) + 1

new.mat <- data.frame(word.que = rep.int(ac$word.que, ac$word.count), word = unlist(strsplit(as.character(ac$s), split = " ")))
words.of.interest <- c("struck|bird|crash|obstacle|miss|shot|struck|lightening|explode|engine|failure|fog|fire|disappear")
new.mats<- new.mat %>%
           mutate(word = gsub("\\,", "", gsub("\\.", "", word))) %>%
           mutate(word.interest = ifelse(grepl(words.of.interest, as.character(word)), 1, 0)) %>%
           filter(word.interest == 1) %>%
           group_by(word.que) %>%
           summarise(word.list = paste0(unique(word), collapse = "; ")) %>%
           full_join(ac, by = "word.que" ) %>%
           arrange(word.que) %>%
           mutate(word.list = ifelse(is.na(word.list), 'other', word.list))

This will create a more efficient search list for you to construct by. The result is

   word.que           word.list
1         1               other
2         2            exploded
3         3               other
4         4            crashing
5         5     engine; explode
6         6       crashed; shot
7         7            exploded
8         8             crashed
9         9      shot; crashing
10       10                shot
11       11             crashed
12       12 shot; fire; crashed
13       13       fire; crashed

As well as your text variable and word.count. This may be more efficient in the long run as well.


问:
change selected value dropdown reactjs
I'm using a dropdown box with ReactJS and I'm using the default values that I get from "this.state.whoIsChecked.allowDestroyAll". But when I use it as default value, I can't change the value anymore. Here follows the code I'm using:</p>

```<code><select
className="form-control"
id="ada"
value={this.state.whoIsChecked.allowDestroyAll}>
    <option>true</option>
    <option>false</option>
</select>
</code>```

答:
You need to add an onChange event with the controlled input and update the state in order to change the value after providing a value to Option field like

```<code>handleChange(e) {
     var whoIsChecked = {...this.state.whoIsChecked}
     whoIsChecked.allowDestroyAll = e.target.value
     this.setState({whoIsChecked})
}

render( ) {
 return <select
    className="form-control"
    id="ada"
    onChange={(e) => this.handleChange(e)}
    value={this.state.whoIsChecked.allowDestroyAll}>
        <option value="true">true</option>
        <option value="false">false</option>
    </select>
}
</code>```

class App extends React.Component {
state= {
    whoIsChecked: {
        allowDestroyAll: "true"
    }
}
handleChange(e) {
         var whoIsChecked = {...this.state.whoIsChecked}
         whoIsChecked.allowDestroyAll = e.target.value
         this.setState({whoIsChecked}, ()=> {console.log(this.state)})

    }

    render( ) {
     return <select
        className="form-control"
        id="ada"
        onChange={(e) => this.handleChange(e)}
        value={this.state.whoIsChecked.allowDestroyAll}>
            <option value="true">true</option>
            <option value="false">false</option>
        </select>
    }

}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Title: change selected value dropdown reactjs

Body:
I'm using a dropdown box with ReactJS and I'm using the default values that I get from "this.state.whoIsChecked.allowDestroyAll". But when I use it as default value, I can't change the value anymore. Here follows the code I'm using:

<select
className="form-control"
id="ada"
value={this.state.whoIsChecked.allowDestroyAll}>
    <option>true</option>
    <option>false</option>
</select>

Body:
You need to add an onChange event with the controlled input and update the state in order to change the value after providing a value to Option field like

handleChange(e) {
     var whoIsChecked = {...this.state.whoIsChecked}
     whoIsChecked.allowDestroyAll = e.target.value
     this.setState({whoIsChecked})
}

render( ) {
 return <select
    className="form-control"
    id="ada"
    onChange={(e) => this.handleChange(e)}
    value={this.state.whoIsChecked.allowDestroyAll}>
        <option value="true">true</option>
        <option value="false">false</option>
    </select>
}

class App extends React.Component {
state= {
    whoIsChecked: {
        allowDestroyAll: "true"
    }
}
handleChange(e) {
         var whoIsChecked = {...this.state.whoIsChecked}
         whoIsChecked.allowDestroyAll = e.target.value
         this.setState({whoIsChecked}, ()=> {console.log(this.state)})

    }

    render( ) {
     return <select
        className="form-control"
        id="ada"
        onChange={(e) => this.handleChange(e)}
        value={this.state.whoIsChecked.allowDestroyAll}>
            <option value="true">true</option>
            <option value="false">false</option>
        </select>
    }

}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
ForEach() : Why can't use break/continue inside
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

```<code>lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);
</code>```

Error:

"No enclosing loop out of which to
break or continue"

答:
To iterate only part of the items and emulate the break perfectly, you can use FirstOrDefault:

```<code>lstTemp.FirstOrDefault(i=>
 {
   if (i == 3)
       return true;

   //do stuff

   return false;
 }
);
</code>```

For list with 100000 items, if the 10th item is 3 it will iterate only 10 times, using the Where solution will work, but iterate the whole list first.

ContentLicense: CC BY-SA 4.0

Body:
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to
break or continue"

Body:
To iterate only part of the items and emulate the break perfectly, you can use FirstOrDefault:

lstTemp.FirstOrDefault(i=>
 {
   if (i == 3)
       return true;

   //do stuff

   return false;
 }
);

For list with 100000 items, if the 10th item is 3 it will iterate only 10 times, using the Where solution will work, but iterate the whole list first.


问:
execute if statement if a value found in a multidimensional array
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

```<code>$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}
</code>```

答:
If a match is not found, it will return false. You want a strict equality check:

```<code>if ($match !== false) {
    echo 'a match found !';
}
</code>```

You are correct--since 0 is falsy, you'll never get into the if block if the value is the first in the array. So you must check if the return value is specifically false, not just falsy.

You can see examples of this in the PHP documentation regarding array_search.

Body:
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}

Body:
If a match is not found, it will return false. You want a strict equality check:

if ($match !== false) {
    echo 'a match found !';
}

You are correct--since 0 is falsy, you'll never get into the if block if the value is the first in the array. So you must check if the return value is specifically false, not just falsy.

You can see examples of this in the PHP documentation regarding array_search.


问:
How to convert this query from MySQL to SQL Server?
Here is the source table:

```<code>+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
</code>```

Here is the result table:

```<code>+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+
</code>```

I have the MySQL version query, how to convert it to SQL server version? I tried to do the declare but I have no idea how to update the value of the variables.

```<code>SELECT Score, ranking AS Rank
FROM
(
SELECT
    Score,
    CASE
        WHEN @dummy = Score
        THEN @ranking := @ranking
        ELSE @ranking := @ranking + 1
    END as ranking,
    @dummy := Score
FROM Scores, (SELECT @ranking := 0, @dummy := -1) init
ORDER BY Score DESC
)AS Result
</code>```

答:
Your code is a MySQL work-around for the ANSI standard DENSE_RANK() function (as explained by Sean Lange in a comment).  The code simply looks like:

```<code>SELECT s.*, DENSE_RANK() OVER (ORDER BY Score DESC) as rank
FROM Scores s
ORDER BY Score DESC;
</code>```

Incidentally, the MySQL code itself is not really accurate.  The following is much safer:

```<code>SELECT Score, ranking AS Rank
FROM (SELECT Score,
             (@rn := if(@dummy = Score, @rn,
                             if(@dummy := Score, @rn + 1, @rn + 1)
                            )
             ) as ranking
      FROM Scores CROSS JOIN
           (SELECT @rn := 0, @dummy := -1) init
      ORDER BY Score DESC
     ) s;
</code>```

The key difference is that all the assignments to variables occur in a single expression.  MySQL does not guarantee the order of evaluations of expressions in a SELECT, so you should not use @dummy in one expression and then assign it in another.

Body:
Here is the source table:

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

Here is the result table:

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

I have the MySQL version query, how to convert it to SQL server version? I tried to do the declare but I have no idea how to update the value of the variables.

SELECT Score, ranking AS Rank
FROM
(
SELECT
    Score,
    CASE
        WHEN @dummy = Score
        THEN @ranking := @ranking
        ELSE @ranking := @ranking + 1
    END as ranking,
    @dummy := Score
FROM Scores, (SELECT @ranking := 0, @dummy := -1) init
ORDER BY Score DESC
)AS Result

Body:
Your code is a MySQL work-around for the ANSI standard DENSE_RANK() function (as explained by Sean Lange in a comment).  The code simply looks like:

SELECT s.*, DENSE_RANK() OVER (ORDER BY Score DESC) as rank
FROM Scores s
ORDER BY Score DESC;

Incidentally, the MySQL code itself is not really accurate.  The following is much safer:

SELECT Score, ranking AS Rank
FROM (SELECT Score,
             (@rn := if(@dummy = Score, @rn,
                             if(@dummy := Score, @rn + 1, @rn + 1)
                            )
             ) as ranking
      FROM Scores CROSS JOIN
           (SELECT @rn := 0, @dummy := -1) init
      ORDER BY Score DESC
     ) s;

The key difference is that all the assignments to variables occur in a single expression.  MySQL does not guarantee the order of evaluations of expressions in a SELECT, so you should not use @dummy in one expression and then assign it in another.


问:
Join data frames based on item presence in a transaction
I have two data frames that I am trying to merge. The first table is a list of items and associated data such as:

```<code>items <- data.frame(
  item_code = c(1111, 2222, 3333, 4444),
  item_category = c("cata","catb","catc","catd")
  )
</code>```

And the second is a list of transactions:

```<code>transactions <- data.frame(
  tran_code = c('aaaa', 'bbbb', 'cccc', 'dddd'),
  tran_items = c("1111,1111,2222","3333,2222","1111,4444,4444","3333")
  )
</code>```

I am trying to create a column containing in each cell a list of transactions that the item appears in, like so:

```<code>view(final_df)

item_code item_category in_trans
1111      "cata"        "aaaa,cccc"
2222      "catb"        "aaaa,bbbb"
3333      "catc"        "bbbb,dddd"
4444      "catd"        "cccc"
</code>```

Can anyone provide suggestions on how to achieve this?

答:
Using the splitstackshape and data.table packages:

```<code>library(splitstackshape) # this will also load the 'data.table'-package

setDT(items)
setDT(transactions)

items[unique(cSplit(transactions, 'tran_items', ',', 'long')), on = .(item_code = tran_items),
      ][, .(in_trans = toString(tran_code)), by = .(item_code, item_category)]
</code>```

gives:

```<code>   item_code item_category   in_trans
1:      1111          cata aaaa, cccc
2:      2222          catb aaaa, bbbb
3:      3333          catc bbbb, dddd
4:      4444          catd       cccc
</code>```

Using the tidyverse, you could do:

```<code>library(dplyr)
library(tidyr)

items %>%
  left_join(., transactions %>%
              separate_rows(tran_items) %>%
              distinct() %>%
              group_by(tran_items = as.numeric(tran_items)) %>%
              summarise(in_tran = toString(tran_code)),
            by = c('item_code' = 'tran_items'))
</code>```

Body:
I have two data frames that I am trying to merge. The first table is a list of items and associated data such as:

items <- data.frame(
  item_code = c(1111, 2222, 3333, 4444),
  item_category = c("cata","catb","catc","catd")
  )

And the second is a list of transactions:

transactions <- data.frame(
  tran_code = c('aaaa', 'bbbb', 'cccc', 'dddd'),
  tran_items = c("1111,1111,2222","3333,2222","1111,4444,4444","3333")
  )

I am trying to create a column containing in each cell a list of transactions that the item appears in, like so:

view(final_df)

item_code item_category in_trans
1111      "cata"        "aaaa,cccc"
2222      "catb"        "aaaa,bbbb"
3333      "catc"        "bbbb,dddd"
4444      "catd"        "cccc"

Can anyone provide suggestions on how to achieve this?

Body:
Using the splitstackshape and data.table packages:

library(splitstackshape) # this will also load the 'data.table'-package

setDT(items)
setDT(transactions)

items[unique(cSplit(transactions, 'tran_items', ',', 'long')), on = .(item_code = tran_items),
      ][, .(in_trans = toString(tran_code)), by = .(item_code, item_category)]

gives:

   item_code item_category   in_trans
1:      1111          cata aaaa, cccc
2:      2222          catb aaaa, bbbb
3:      3333          catc bbbb, dddd
4:      4444          catd       cccc

Using the tidyverse, you could do:

library(dplyr)
library(tidyr)

items %>%
  left_join(., transactions %>%
              separate_rows(tran_items) %>%
              distinct() %>%
              group_by(tran_items = as.numeric(tran_items)) %>%
              summarise(in_tran = toString(tran_code)),
            by = c('item_code' = 'tran_items'))


问:
SqlDataReader displaying like fields
When I try to display only distinct values in my DB with SqlDataReader, it is still showing duplicate columns.

```<code>string State = ddlState.SelectedItem.Value;
string City = ddlCities.SelectedItem.Text;

SqlConnection con = new SqlConnection("Data Source=--myDB--;Database=--MyconnectionString--");

SqlCommand cmd = new SqlCommand("Select distinct State, City, ExchangeType, Boid, Bex, Npa, Nxx from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);

if (!string.IsNullOrEmpty(ddlCities.SelectedItem.Text))
{
    exchangesheet.Visible = true;

    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        this.STATE.Text = rdr["State"].ToString();
        this.CITY.Text = rdr["City"].ToString();
        this.ExchangeType.Text = rdr["ExchangeType"].ToString();
        this.BOID.Text += rdr["Boid"].ToString() + ", ";
        this.BEX.Text += rdr["Bex"].ToString() + ", ";
        this.NPA.Text += rdr["Npa"].ToString() + ", ";
        this.NXX.Text += rdr["Nxx"].ToString() + ", ";
    }

    con.Close();
}
else
{
    exchangesheet.Visible = false;
}
</code>```

All queries with += are resulting in duplicate data in the labels, even though I have specified only distinct data to be shown in the SqlCommand query. I apologize if I am not explaining correctly but any help or direction will be much appreciated.

Results when searching a specific state:

```<code>BOID: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
BEX: 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205,
NPA: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
NXX: 212, 214, 226, 238, 244, 250, 251, 252, 254, 262, 263, 278, 279, 290, 298, 307, 313, 314, 320, 321, 322, 323, 324, 326, 328, 380, 397, 402, 403, 408, 414, 421, 423, 437, 444, 445, 453, 458, 502, 520, 533, 536, 545, 558, 583, 591, 592, 595, 599, 682, 714, 731, 733, 776, 780, 781, 783, 786, 787, 788, 791, 798, 801, 802, 803, 808, 822, 823, 824, 833, 836, 841, 854, 856, 868, 870, 871, 873, 876, 879, 913, 916, 917, 923, 925, 929, 930, 933, 939, 940, 941, 942, 943, 945, 949, 951, 956, 957, 967, 968, 969, 970, 972, 977, 978, 979, 980, 981, 982, 983, 985, 987, 988, 989, 991, 995,
</code>```

答:
Assuming that for some reason you can't afford to make multiple queries to the DB, and that your result data set is  small. This might be faster if your server round trip is long or your DBA will hate you for spamming him with 6 table scans etc.
You could perform the actual distinct in your code.

```<code>        con.Open();
        var hsNxx = new HashSet<int>();
        var hsBex = new HashSet<int>();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {

            while (rdr.Read())
            {
                hsBex.Add((int)rdr["Bex"]);
                hsNxx.Add((int)rdr["Nxx"]);

            }

        }

        con.Close();
        string distinctBex =hsBex.Count == 1 ? hsBex.First().ToString() : hsBex.Select(f => f.ToString()).Aggregate((x, y) => x + "," + y);
        this.BEX.Text = distinctBex;
</code>```

Assumed the columns are ints.
You could also implement the Text to be changed only once and not mutated every row with +=

As a side note I recommend warpping IDisposables of connection/reader/command in a using clause

Title: SqlDataReader displaying like fields

Body:
When I try to display only distinct values in my DB with SqlDataReader, it is still showing duplicate columns.

string State = ddlState.SelectedItem.Value;
string City = ddlCities.SelectedItem.Text;

SqlConnection con = new SqlConnection("Data Source=--myDB--;Database=--MyconnectionString--");

SqlCommand cmd = new SqlCommand("Select distinct State, City, ExchangeType, Boid, Bex, Npa, Nxx from TAS where StateId=" + "'" + State + "'" + " AND City=" + "'" + City + "'", con);

if (!string.IsNullOrEmpty(ddlCities.SelectedItem.Text))
{
    exchangesheet.Visible = true;

    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        this.STATE.Text = rdr["State"].ToString();
        this.CITY.Text = rdr["City"].ToString();
        this.ExchangeType.Text = rdr["ExchangeType"].ToString();
        this.BOID.Text += rdr["Boid"].ToString() + ", ";
        this.BEX.Text += rdr["Bex"].ToString() + ", ";
        this.NPA.Text += rdr["Npa"].ToString() + ", ";
        this.NXX.Text += rdr["Nxx"].ToString() + ", ";
    }

    con.Close();
}
else
{
    exchangesheet.Visible = false;
}

All queries with += are resulting in duplicate data in the labels, even though I have specified only distinct data to be shown in the SqlCommand query. I apologize if I am not explaining correctly but any help or direction will be much appreciated.

Results when searching a specific state:

BOID: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
BEX: 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205, 9205,
NPA: 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
NXX: 212, 214, 226, 238, 244, 250, 251, 252, 254, 262, 263, 278, 279, 290, 298, 307, 313, 314, 320, 321, 322, 323, 324, 326, 328, 380, 397, 402, 403, 408, 414, 421, 423, 437, 444, 445, 453, 458, 502, 520, 533, 536, 545, 558, 583, 591, 592, 595, 599, 682, 714, 731, 733, 776, 780, 781, 783, 786, 787, 788, 791, 798, 801, 802, 803, 808, 822, 823, 824, 833, 836, 841, 854, 856, 868, 870, 871, 873, 876, 879, 913, 916, 917, 923, 925, 929, 930, 933, 939, 940, 941, 942, 943, 945, 949, 951, 956, 957, 967, 968, 969, 970, 972, 977, 978, 979, 980, 981, 982, 983, 985, 987, 988, 989, 991, 995,

Body:
Assuming that for some reason you can't afford to make multiple queries to the DB, and that your result data set is  small. This might be faster if your server round trip is long or your DBA will hate you for spamming him with 6 table scans etc.
You could perform the actual distinct in your code.

        con.Open();
        var hsNxx = new HashSet<int>();
        var hsBex = new HashSet<int>();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {

            while (rdr.Read())
            {
                hsBex.Add((int)rdr["Bex"]);
                hsNxx.Add((int)rdr["Nxx"]);

            }

        }

        con.Close();
        string distinctBex =hsBex.Count == 1 ? hsBex.First().ToString() : hsBex.Select(f => f.ToString()).Aggregate((x, y) => x + "," + y);
        this.BEX.Text = distinctBex;

Assumed the columns are ints.
You could also implement the Text to be changed only once and not mutated every row with +=

As a side note I recommend warpping IDisposables of connection/reader/command in a using clause


问:
TFS GIT - How to commit only certain files?
I am new to using Git in TFS.

Say I have 10 files that I modified, however I would only like to commit 2 of those files.

Previously with TFS I could include/exclude what file(s) I wanted to check in.

What would the equivalent be in Git?

Would I Stage my 2 files I want to commit and check those in?  Or would I stage the 8 files and commit my 2 changes?

答:
The equivalent in Visual Studio using Git with TFS would be include -> staged.

Here's the link to Microsoft's documentation.


问:
iPhone: Memory leak in this code?
I am using two objects i.e., pagesUrl and pagesXmlParser in the code and after their use, im releasing those two objects. Its running well but its showing them in memory leaks. when i tried to verify it, i checked the reference count of those objects and its showing '1' even after the objects are released. can any one help me out how to remove that leak and how to release those particular objects in the following code.

```<code>-(void)loadPagesForChapter:(NSString *)path{
// have to parse the pages xml for this chapter

  NSURL *pagesUrl = [[NSURL alloc] initFileURLWithPath:[self pagesXmlPath:path]];

  NSXMLParser *pagesXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:pagesUrl];

  PagesAccumulator *pageLoader = [[PagesAccumulator alloc] init];
  pagesXmlParser.delegate = pageLoader;

  [pagesXmlParser parse];

// parsing pages done
// get the pages array
self.arrayOfPages = pageLoader.arrayOfPages;

    [pageLoader release];
[pagesXmlParser release];
[pagesUrl release];
NSLog(@"pagesurl retain count is:%d",[pagesUrl retainCount]);
    NSLog(@"pagesxmlparser retain count is:%d",[pagesXmlParser retainCount]);
}
</code>```

Thanks in advance for any assistance.

答:
Ignore the retain counts

Just because an object has a retain count > 0 doesn't mean that it's not also autoreleased :)

Your code looks fine to me.

If it's really a leak I would look at your implementation of PageLoader to see if there is a retain in one of the NSXMLParserDelegate methods that's preventing the parser being released (which would cause the URL to leak as well).

Title: iPhone: Memory leak in this code?

Body:
I am using two objects i.e., pagesUrl and pagesXmlParser in the code and after their use, im releasing those two objects. Its running well but its showing them in memory leaks. when i tried to verify it, i checked the reference count of those objects and its showing '1' even after the objects are released. can any one help me out how to remove that leak and how to release those particular objects in the following code.

-(void)loadPagesForChapter:(NSString *)path{
// have to parse the pages xml for this chapter

  NSURL *pagesUrl = [[NSURL alloc] initFileURLWithPath:[self pagesXmlPath:path]];

  NSXMLParser *pagesXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:pagesUrl];

  PagesAccumulator *pageLoader = [[PagesAccumulator alloc] init];
  pagesXmlParser.delegate = pageLoader;

  [pagesXmlParser parse];

// parsing pages done
// get the pages array
self.arrayOfPages = pageLoader.arrayOfPages;

    [pageLoader release];
[pagesXmlParser release];
[pagesUrl release];
NSLog(@"pagesurl retain count is:%d",[pagesUrl retainCount]);
    NSLog(@"pagesxmlparser retain count is:%d",[pagesXmlParser retainCount]);
}

Thanks in advance for any assistance.


答:
You are using the controlled element, using the value property (means controlling the value of selectfield by the state variable), you need to define the onchange method to update that state value otherwise selectfield will become read-only.

Write it like this:

```<code><select
    className="form-control"
    id="ada"
    value={this.state.whoIsChecked.allowDestroyAll}
    onChange={this.change}
>
    <option value='true'>true</option>
    <option value='false'>false</option>
</select>

change = (e) => {
    let whoIsChecked = Object.assign({}, this.state.whoIsChecked)
    whoIsChecked.allowDestroyAll = e.target.value;
    this.setState({whoIsChecked});
}
</code>```

Note: You need to assign the unique value to each option.

Title: change selected value dropdown reactjs

Body:
You are using the controlled element, using the value property (means controlling the value of selectfield by the state variable), you need to define the onchange method to update that state value otherwise selectfield will become read-only.

Write it like this:

<select
    className="form-control"
    id="ada"
    value={this.state.whoIsChecked.allowDestroyAll}
    onChange={this.change}
>
    <option value='true'>true</option>
    <option value='false'>false</option>
</select>

change = (e) => {
    let whoIsChecked = Object.assign({}, this.state.whoIsChecked)
    whoIsChecked.allowDestroyAll = e.target.value;
    this.setState({whoIsChecked});
}

Note: You need to assign the unique value to each option.


问:
using an expression to show or hide rectangle based on a parameter value (SSRS)
Trying to show/hide a couple of rectangles in SSRS based on an expression which uses the value of a parameter in the report. See the screenshots for more details. When the '-Cover pages' label is picked I want it to display the rectangle but I consistently get the following errors. It can't seem to convert and read the parameter expression no matter what I do.

The expression I'm trying to use is:

```<code>=iif(Parameters!specparam.Value="-Cover Pages",true,false)
</code>```

答:
Your comment is very close. Apply this expression to the Hidden property of the rectangle:

```<code>=IIF( Parameters!specparam.Label.Equals("-Cover Pages"), FALSE, TRUE )
</code>```

You'll notice I have switched around the FALSE and TRUE as you don't want the rectangle to hide when the parameter matches.

Edit:
As you're dealing with a multivalue parameter, you can use a combination of Array.IndexOf and Split to check if your value is one of the selected parameters.
Apply this expression to the Hidden property of your rectangle:

```<code>=IIF( Array.IndexOf( Split( Parameters!specparam.Value, "," ), "-Cover Pages" ) > -1, FALSE, TRUE )
</code>```

Body:
Trying to show/hide a couple of rectangles in SSRS based on an expression which uses the value of a parameter in the report. See the screenshots for more details. When the '-Cover pages' label is picked I want it to display the rectangle but I consistently get the following errors. It can't seem to convert and read the parameter expression no matter what I do.

The expression I'm trying to use is:

=iif(Parameters!specparam.Value="-Cover Pages",true,false)

Body:
Your comment is very close. Apply this expression to the Hidden property of the rectangle:

=IIF( Parameters!specparam.Label.Equals("-Cover Pages"), FALSE, TRUE )

You'll notice I have switched around the FALSE and TRUE as you don't want the rectangle to hide when the parameter matches.

Edit:
As you're dealing with a multivalue parameter, you can use a combination of Array.IndexOf and Split to check if your value is one of the selected parameters.
Apply this expression to the Hidden property of your rectangle:

=IIF( Array.IndexOf( Split( Parameters!specparam.Value, "," ), "-Cover Pages" ) > -1, FALSE, TRUE )


问:
Why does my Tkinter Python code not work as I expected?
Here is the code:

```<code>from tkinter import *

def main():
    pw = ''
    passwordCorrect = False

    window = Tk()

    instructionLabel = Label(window,text='Enter your password:')
    entryBox = Entry(window)
    def checkPassword():
        if entryBox.get() == 'password':
            global passwordCorrect
            passwordCorrect = True

    confirmButton = Button(window,text='Confirm',command=checkPassword)

    instructionLabel.pack()
    entryBox.pack()
    confirmButton.pack()
    window.mainloop()

    if passwordCorrect:
        print('Access granted')
    else:
        print('Access denied')
main()
</code>```

When I close the window I always get the message 'Access denied' (expecting 'Access granted'), even if I enter 'password' into the entry box and press the button. What am I missing? Much obliged.

答:
You forgot to make passwordCorrect global in your main function. Your main function has its own local passwordCorrect variable that's different from the global one.

If you're using python 3, you can alternatively change global passwordCorrect to nonlocal passwordCorrect so that the checkPassword function uses the variable defined in main.

Body:
Here is the code:

from tkinter import *

def main():
    pw = ''
    passwordCorrect = False

    window = Tk()

    instructionLabel = Label(window,text='Enter your password:')
    entryBox = Entry(window)
    def checkPassword():
        if entryBox.get() == 'password':
            global passwordCorrect
            passwordCorrect = True

    confirmButton = Button(window,text='Confirm',command=checkPassword)

    instructionLabel.pack()
    entryBox.pack()
    confirmButton.pack()
    window.mainloop()

    if passwordCorrect:
        print('Access granted')
    else:
        print('Access denied')
main()

When I close the window I always get the message 'Access denied' (expecting 'Access granted'), even if I enter 'password' into the entry box and press the button. What am I missing? Much obliged.


答:
To stage all the files for commit from root of your repository you execute git add . There are following 2 ways by which you can stage specific files for commit:

Go to the directory from which files are to be staged for commit e.g. C:\git\repository\{path-to-directory} and execute git add .

Stage files one by one from the root of your directory as git add {file-path}

Once these files have been staged for commit, you can execute git commit -m. This will commit only 2 staged files.

Title: TFS GIT - How to commit only certain files?

Body:
I am new to using Git in TFS.

Say I have 10 files that I modified, however I would only like to commit 2 of those files.

Previously with TFS I could include/exclude what file(s) I wanted to check in.

What would the equivalent be in Git?

Would I Stage my 2 files I want to commit and check those in?  Or would I stage the 8 files and commit my 2 changes?


问:
Powershell: Querying multiple strings and outputting to both user and file
I've been given the duty of validating installation of an update across many hosts. This validation is performed by querying for a string of an error code that signifies success. I would like this output to both appear in the shell and also be written to a file.

```<code>$computerList = @($userInput)
foreach ($_ in $computerList){
        get-content -tail 20 ("filepath") `
        | where {$_| select-string "All steps complete!"} `
        | where {$_| select-string "Output Error = 0 "} `
        | out-file C:\users\me\Desktop\validation_log.txt -append
        }
</code>```

I based the multiple string "grep"-ing off of an online article,
However, this doesn't write the desired strings to the out-file path, nor does it display in console.

Can anyone please explain the best method for querying multiple strings and then outputting those to a file?

答:
Your example is more complex than necessary.

You could just chain the Select-String. And Tee-Object is the way to go if you want to output something to both file and down the pipeline:

```<code>PS C:\temp> Get-Content -LiteralPath ".\input.txt"
All steps complete!
All steps complete! Output Error = 0
asdf

PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps" | Select-String -Pattern "Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete! Output Error = 0

PS C:\temp> Get-Content -LiteralPath ".\output.txt"
All steps complete! Output Error = 0
</code>```

The above behaves like an logical "and" for each pattern. If you want to "or" the patterns you could use the fact that the pattern is a regular expression:

```<code>PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps|Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete!
All steps complete! Output Error = 0
</code>```

Also notice that Select-String outputs Microsoft.PowerShell.Commands.MatchInfo objects and not strings. You will probably get unwanted newlines in your output if you pipe these directly to Tee-Object. I therefore convert these to strings in the Foreach-Object

Body:
I've been given the duty of validating installation of an update across many hosts. This validation is performed by querying for a string of an error code that signifies success. I would like this output to both appear in the shell and also be written to a file.

$computerList = @($userInput)
foreach ($_ in $computerList){
        get-content -tail 20 ("filepath") `
        | where {$_| select-string "All steps complete!"} `
        | where {$_| select-string "Output Error = 0 "} `
        | out-file C:\users\me\Desktop\validation_log.txt -append
        }

I based the multiple string "grep"-ing off of an online article,
However, this doesn't write the desired strings to the out-file path, nor does it display in console.

Can anyone please explain the best method for querying multiple strings and then outputting those to a file?

Body:
Your example is more complex than necessary.

You could just chain the Select-String. And Tee-Object is the way to go if you want to output something to both file and down the pipeline:

PS C:\temp> Get-Content -LiteralPath ".\input.txt"
All steps complete!
All steps complete! Output Error = 0
asdf

PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps" | Select-String -Pattern "Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete! Output Error = 0

PS C:\temp> Get-Content -LiteralPath ".\output.txt"
All steps complete! Output Error = 0

The above behaves like an logical "and" for each pattern. If you want to "or" the patterns you could use the fact that the pattern is a regular expression:

PS C:\temp> Get-Content -LiteralPath ".\input.txt" | Select-String -Pattern "All steps|Output Error" | ForEach-Object {$_.ToString()} | Tee-Object -FilePath ".\output.txt" -Append
All steps complete!
All steps complete! Output Error = 0

Also notice that Select-String outputs Microsoft.PowerShell.Commands.MatchInfo objects and not strings. You will probably get unwanted newlines in your output if you pipe these directly to Tee-Object. I therefore convert these to strings in the Foreach-Object


问:
java read a web page using url
how to read next page of the same URL

the  URL of the page contain many pages i read the first page using

```<code>URL(url).openStream()
</code>```

but it just reading the first page

for example this site i read the first page how can i read the second culture.gov.uk/news/news_stories/6832.aspx

答:
Next page will have some link.

You can parse HTML and collect all the links and then you can filter out which is the next link for this page and then read it same way.

Here is the example that will list all the links from given page. - using JSOUP

Note: It is certainly ill-legal to do this for some sites.

Title: java read a web page using url

Body:
how to read next page of the same URL

the  URL of the page contain many pages i read the first page using

URL(url).openStream()

but it just reading the first page

for example this site i read the first page how can i read the second culture.gov.uk/news/news_stories/6832.aspx


问:
Efficiently joining IP ranges in BigQuery
I have a table of IP addresses and a table of IP address ranges (start ip, end ip) that I'd like to join together. I've been able to make this work with the following query:

```<code>SELECT * FROM `ips` i
JOIN `ranges`  a
ON NET.SAFE_IP_FROM_STRING(i.ip)
BETWEEN NET.SAFE_IP_FROM_STRING(a.start_ip)
AND NET.SAFE_IP_FROM_STRING(a.end_ip)
</code>```

The problem I'm having is that it scales really badly. To do it for 10 IPs takes around 8 seconds, 100 takes 30 seconds, and 1000 takes a few minutes. I'd like to be able to do this for tens of millions of rows. (I have tried writing the output of NET.SAFE_IP_FROM_STRING to the ranges table, but it only speeds things up by around 10%, and doesn't help with scaling).

The ranges don't overlap, so for every row in the input table I expect 0 or 1 rows in the output table. A LATERAL JOIN would let me do that and almost certainly speed things up, but I don't think BigQuery supports them. Is there any other way to make this query faster and scalable?

答:
After reviewing the article at https://cloudplatform.googleblog.com/2014/03/geoip-geolocation-with-google-bigquery.html that was linked to in Felipe's answer I was able to put something together that is incredibly fast and scales really well. As Felipe alluded to, the trick is to do a direct join on a prefix (I went with /16), and then filter with a between. I'm pre-processing the ranges to split anything larger than a /16 into multiple blocks. I then overwrite the table with this query, which adds some additional fields:

```<code>SELECT *,
NET.SAFE_IP_FROM_STRING(start_ip) AS start_b,
NET.SAFE_IP_FROM_STRING(end_ip) AS end_b,
NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(start_ip), 16) as prefix
</code>```

The join query then looks something like this:

```<code>SELECT * FROM `ips` i
JOIN `ranges`  a
ON a.prefix = NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(i.ip), 16)
WHERE NET.SAFE_IP_FROM_STRING(i.ip) BETWEEN a.start_b AND a.end_b
</code>```

Joining 10 million IPs to 1 million ranges now takes less than 30 seconds at billing tier 1!

Body:
I have a table of IP addresses and a table of IP address ranges (start ip, end ip) that I'd like to join together. I've been able to make this work with the following query:

SELECT * FROM `ips` i
JOIN `ranges`  a
ON NET.SAFE_IP_FROM_STRING(i.ip)
BETWEEN NET.SAFE_IP_FROM_STRING(a.start_ip)
AND NET.SAFE_IP_FROM_STRING(a.end_ip)

The problem I'm having is that it scales really badly. To do it for 10 IPs takes around 8 seconds, 100 takes 30 seconds, and 1000 takes a few minutes. I'd like to be able to do this for tens of millions of rows. (I have tried writing the output of NET.SAFE_IP_FROM_STRING to the ranges table, but it only speeds things up by around 10%, and doesn't help with scaling).

The ranges don't overlap, so for every row in the input table I expect 0 or 1 rows in the output table. A LATERAL JOIN would let me do that and almost certainly speed things up, but I don't think BigQuery supports them. Is there any other way to make this query faster and scalable?

Body:
After reviewing the article at https://cloudplatform.googleblog.com/2014/03/geoip-geolocation-with-google-bigquery.html that was linked to in Felipe's answer I was able to put something together that is incredibly fast and scales really well. As Felipe alluded to, the trick is to do a direct join on a prefix (I went with /16), and then filter with a between. I'm pre-processing the ranges to split anything larger than a /16 into multiple blocks. I then overwrite the table with this query, which adds some additional fields:

SELECT *,
NET.SAFE_IP_FROM_STRING(start_ip) AS start_b,
NET.SAFE_IP_FROM_STRING(end_ip) AS end_b,
NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(start_ip), 16) as prefix

The join query then looks something like this:

SELECT * FROM `ips` i
JOIN `ranges`  a
ON a.prefix = NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(i.ip), 16)
WHERE NET.SAFE_IP_FROM_STRING(i.ip) BETWEEN a.start_b AND a.end_b

Joining 10 million IPs to 1 million ranges now takes less than 30 seconds at billing tier 1!


问:
How to implement function with multiple invocations
How do I implement a adder function in javascript which can be invoked like

```<code>adder(1,2)(5,6,2)(4,9,10,11)(6,7).....()
</code>```

The function should accept any number of arguments and add them all together. The function can be invoked in following ways.

```<code>adder(2,3,5) // prints 10
adder(2,3)(5) // prints 10
adder(2)(3)(5) //prints 10
</code>```

What is best possible way to implement this function using closures?

答:
```<code>function add(...values){
 this.value=(this.value||0)+values.reduce((a,b)=>a+b),0);
 return add.bind(this);
}
</code>```

You need a way to pass the value out of your function, i put the value into the context:

```<code>add(1,2,3)(4,5);
alert(value);
</code>```

Body:
How do I implement a adder function in javascript which can be invoked like

adder(1,2)(5,6,2)(4,9,10,11)(6,7).....()

The function should accept any number of arguments and add them all together. The function can be invoked in following ways.

adder(2,3,5) // prints 10
adder(2,3)(5) // prints 10
adder(2)(3)(5) //prints 10

What is best possible way to implement this function using closures?

Body:
function add(...values){
 this.value=(this.value||0)+values.reduce((a,b)=>a+b),0);
 return add.bind(this);
}

You need a way to pass the value out of your function, i put the value into the context:

add(1,2,3)(4,5);
alert(value);


问:
Does Java automatically save an 'evaluate' statement in a predefined Java variable?
Say I perform a simple add/concatenation statement:

```<code>variable + newInput
</code>```

Without setting the calculated value to a new variable, as in:

```<code>variable = variable + newInput
</code>```

or

```<code>variable += newInput
</code>```

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

```<code>Print(_)
</code>```

Is there anything like this in Java?

答:
More than just not saving the result, Java will outright refuse to compile your program if it contains such a line, precisely because the result would be unsaved and unusable if it was allowed:

```<code>public class Main
{
    public static void main(String[] args)
    {
        1+2;
    }
}
</code>```

Result:

```<code>Main.java:5: error: not a statement
        1+2;
         ^
1 error
</code>```

Java does not allow arbitrary expressions as statements, and addition expressions are not considered valid Java statements.

The expressions that are allowed as statements by themselves are listed in the JLS:

```<code>ExpressionStatement:
  StatementExpression ;

StatementExpression:
  Assignment
  PreIncrementExpression
  PreDecrementExpression
  PostIncrementExpression
  PostDecrementExpression
  MethodInvocation
  ClassInstanceCreationExpression
</code>```

Assignment, increment, decrement, method calls, and new Whatever(), all things with side effects or potential side effects. Barring possible side effects of an implicit toString() call, + cannot have side effects, so to catch probable errors, Java forbids addition expressions from being statements.

Body:
Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?

Body:
More than just not saving the result, Java will outright refuse to compile your program if it contains such a line, precisely because the result would be unsaved and unusable if it was allowed:

public class Main
{
    public static void main(String[] args)
    {
        1+2;
    }
}

Result:

Main.java:5: error: not a statement
        1+2;
         ^
1 error

Java does not allow arbitrary expressions as statements, and addition expressions are not considered valid Java statements.

The expressions that are allowed as statements by themselves are listed in the JLS:

ExpressionStatement:
  StatementExpression ;

StatementExpression:
  Assignment
  PreIncrementExpression
  PreDecrementExpression
  PostIncrementExpression
  PostDecrementExpression
  MethodInvocation
  ClassInstanceCreationExpression

Assignment, increment, decrement, method calls, and new Whatever(), all things with side effects or potential side effects. Barring possible side effects of an implicit toString() call, + cannot have side effects, so to catch probable errors, Java forbids addition expressions from being statements.


问:
Ionic 2 Page Unresponsive
Find below a page in Ionic 2 that pulls data from a service and immediately becomes unresonsive, I can not click on anything both on a device, simulator even on browser.

home.html

```<code><ion-header>
  <ion-navbar hideBackButton="true" danger>
    <button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Shoppa</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="cards-bg social-cards">

  <ion-card *ngFor="let campaign of campaigns">

    <ion-item>
      <ion-avatar item-left>
        <img [src]="campaign.image">
      </ion-avatar>
      <h2>{{campaign.name}}</h2>
      <p>July 5, 2016</p>
    </ion-item>

    <img [src]="campaign.image">

    <ion-card-content>
      <p>{{campaign.description}}</p>
    </ion-card-content>

    <ion-row>
      <ion-col>
        <button primary clear small (click)="likeCampaign(campaign)" disabled= {{buttonDisabled}}>
          <ion-icon name='thumbs-up'></ion-icon>
          <div>{{campaign.likes.length}} Likes</div>
        </button>
      </ion-col>
      <ion-col>
        <button primary clear small (click)="shareCampaign(campaign)">
          <ion-icon ios="ios-share" md="md-share"></ion-icon>
          <div>{{campaign.share.length}} Shares</div>
        </button>
      </ion-col>
      <ion-col>
        <button primary clear small (click)="optInToCampaign(campaign)">
          <ion-icon name='person-add'></ion-icon>
          <div>{{campaign.wantin.length}} Opt In</div>
        </button>
      </ion-col>
    </ion-row>

  </ion-card>

</ion-content>

<style>
  .social-cards ion-col {
    padding: 0;
  }
</style>
</code>```

home.ts

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Toast, SocialSharing } from 'ionic-native';

import { CampaignProvider } from '../../providers/campaign-provider/campaign-provider';
import { UserProvider } from '../../providers/user-provider/user-provider';

@Component({
  templateUrl: 'build/pages/home/home.html',
  providers: [CampaignProvider]
})

export class HomePage {
  campaignOject: {name?:string, image?:string, description?: string, likes?: number, shares?:number, wantin?:number } = {};
  campaigns = [];
  like:{email?:string, campaignid?:string} ={};
  buttonDisabled:boolean;
  user:{email?: string} = {};

  constructor(public navCtrl: NavController, private campaignProvider: CampaignProvider, private userProvider: UserProvider) {
    this.buttonDisabled = null;

    this.user.email = userProvider.GetLocalObject("user");
    this.getCampaigns();
  }

  ionViewWillEnter(){
    console.log('Entered into the view');
  }

  ionViewDidEnter(){
    console.log('Page was fully loaded');
  }

  getCampaigns(){
    console.log(this.user);

    this.campaignProvider.GetUserCampaigns(this.user).subscribe(
        data => {
        console.log(data.result);
        console.log(data.message);
        this.campaigns = data.result;
      },
        err => {
        console.log(err);
      },
      () => console.log('Pulling data')
    )
  }

  likeCampaign(campaign){
    console.log(campaign.name + ' has been liked');

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage
    //campaign.email = 'kolexinfos@gmail.com';

    console.log(this.like);
    this.campaignProvider.LikeCampaigns(this.like).subscribe(
      data => {
        console.log(data.result);
        this.buttonDisabled = true;
        Toast.show(campaign.name + " liked", "short", 'bottom').subscribe(
            toast => {
            console.log(toast);
          }
        );

      },
      err => {
        console.log(err);
      },
      () => console.log(campaign.name + ' campaign was liked.')
    )
    this.getCampaigns();
  }

  optInToCampaign(campaign){
    console.log(campaign.name + ' has been opted into' );

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage

    this.campaignProvider.WantInCampaign(this.like).subscribe(
        data => {
        console.log(data.result);
          Toast.show(campaign.name + " opted in to", "short", 'bottom').subscribe(
              toast => {
              console.log(toast);
            }
          );
      },
        err => {
        console.log(err);
      },
      () => console.log(campaign.name + ' campaign was liked.')
    )

    this.getCampaigns();
  }

  shareCampaign(campaign){
    console.log(campaign.name + ' has been shared');

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage

    SocialSharing.share(campaign.description, campaign.name,campaign.image).then(() =>{
      console.log("Success");

        this.campaignProvider.ShareCampaign(campaign).subscribe(
            data => {
            console.log(data.result);
              Toast.show(campaign.name + " shared", "short", 'bottom').subscribe(
                  toast => {
                  console.log(toast);
                }
              );
          },
            err => {
            console.log(err);
          },
          () => console.log(campaign.name + ' campaign was shared.')
        )

    }).catch(() => {
      console.log("Error");
    });

    this.getCampaigns();
  }

}
</code>```

Console Log

```<code>Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
Native: tried calling Splashscreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
ionViewWillEnter called
kolexinfos@mail.com
swiper initEvents attach
Object {email: "kolexinfos@mail.com"}
Username for user [object Object]
Entered into the view
Object {email: "kolexinfos@mail.com"}
Username for user [object Object]
Entered into the view
Page was fully loaded
[Object, Object, Object]
Successfully pulled the Campaigns
Pulling data
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.
[Object, Object, Object]
Successfully pulled the Campaigns
Pulling data
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.
</code>```

答:
I would try calling this.getCampaigns(); inside an ionViewDidLoad(){}. This should ensure that all providers are instantiated before trying to access them.

Another issue that can come up due to the asynchronous nature of such scenarios would be if the value is emitted before the subscription has taken place. In some previous such scenarios of mine I would subscribe inside an ngOnInit(){}. This a lifecycle hook of Angular and I'm not exactly sure what the equivalent hook is for Ionic.

Title: Ionic 2 Page Unresponsive

Body:
Find below a page in Ionic 2 that pulls data from a service and immediately becomes unresonsive, I can not click on anything both on a device, simulator even on browser.

home.html

<ion-header>
  <ion-navbar hideBackButton="true" danger>
    <button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Shoppa</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="cards-bg social-cards">

  <ion-card *ngFor="let campaign of campaigns">

    <ion-item>
      <ion-avatar item-left>

      </ion-avatar>

{{campaign.name}}

July 5, 2016

    </ion-item>

    <ion-card-content>

{{campaign.description}}

    </ion-card-content>

    <ion-row>
      <ion-col>
        <button primary clear small (click)="likeCampaign(campaign)" disabled= {{buttonDisabled}}>
          <ion-icon name='thumbs-up'></ion-icon>

{{campaign.likes.length}} Likes

        </button>
      </ion-col>
      <ion-col>
        <button primary clear small (click)="shareCampaign(campaign)">
          <ion-icon ios="ios-share" md="md-share"></ion-icon>

{{campaign.share.length}} Shares

        </button>
      </ion-col>
      <ion-col>
        <button primary clear small (click)="optInToCampaign(campaign)">
          <ion-icon name='person-add'></ion-icon>

{{campaign.wantin.length}} Opt In

        </button>
      </ion-col>
    </ion-row>

  </ion-card>

</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Toast, SocialSharing } from 'ionic-native';

import { CampaignProvider } from '../../providers/campaign-provider/campaign-provider';
import { UserProvider } from '../../providers/user-provider/user-provider';

@Component({
  templateUrl: 'build/pages/home/home.html',
  providers: [CampaignProvider]
})

export class HomePage {
  campaignOject: {name?:string, image?:string, description?: string, likes?: number, shares?:number, wantin?:number } = {};
  campaigns = [];
  like:{email?:string, campaignid?:string} ={};
  buttonDisabled:boolean;
  user:{email?: string} = {};

  constructor(public navCtrl: NavController, private campaignProvider: CampaignProvider, private userProvider: UserProvider) {
    this.buttonDisabled = null;

    this.user.email = userProvider.GetLocalObject("user");
    this.getCampaigns();
  }

  ionViewWillEnter(){
    console.log('Entered into the view');
  }

  ionViewDidEnter(){
    console.log('Page was fully loaded');
  }

  getCampaigns(){
    console.log(this.user);

    this.campaignProvider.GetUserCampaigns(this.user).subscribe(
        data => {
        console.log(data.result);
        console.log(data.message);
        this.campaigns = data.result;
      },
        err => {
        console.log(err);
      },
      () => console.log('Pulling data')
    )
  }

  likeCampaign(campaign){
    console.log(campaign.name + ' has been liked');

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage
    //campaign.email = 'kolexinfos@gmail.com';

    console.log(this.like);
    this.campaignProvider.LikeCampaigns(this.like).subscribe(
      data => {
        console.log(data.result);
        this.buttonDisabled = true;
        Toast.show(campaign.name + " liked", "short", 'bottom').subscribe(
            toast => {
            console.log(toast);
          }
        );

      },
      err => {
        console.log(err);
      },
      () => console.log(campaign.name + ' campaign was liked.')
    )
    this.getCampaigns();
  }

  optInToCampaign(campaign){
    console.log(campaign.name + ' has been opted into' );

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage

    this.campaignProvider.WantInCampaign(this.like).subscribe(
        data => {
        console.log(data.result);
          Toast.show(campaign.name + " opted in to", "short", 'bottom').subscribe(
              toast => {
              console.log(toast);
            }
          );
      },
        err => {
        console.log(err);
      },
      () => console.log(campaign.name + ' campaign was liked.')
    )

    this.getCampaigns();
  }

  shareCampaign(campaign){
    console.log(campaign.name + ' has been shared');

    this.like.email = 'kolexinfos@gmail.com';
    this.like.campaignid = campaign._id;
    //TODO: Pick the User Email from localstorage

    SocialSharing.share(campaign.description, campaign.name,campaign.image).then(() =>{
      console.log("Success");

        this.campaignProvider.ShareCampaign(campaign).subscribe(
            data => {
            console.log(data.result);
              Toast.show(campaign.name + " shared", "short", 'bottom').subscribe(
                  toast => {
                  console.log(toast);
                }
              );
          },
            err => {
            console.log(err);
          },
          () => console.log(campaign.name + ' campaign was shared.')
        )

    }).catch(() => {
      console.log("Error");
    });

    this.getCampaigns();
  }

}

Console Log

Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
Native: tried calling StatusBar.styleDefault, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
Native: tried calling Splashscreen.hide, but Cordova is not available. Make sure to include cordova.js or run in a device/simulator
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
ionViewWillEnter called
kolexinfos@mail.com
swiper initEvents attach
Object {email: "kolexinfos@mail.com"}
Username for user [object Object]
Entered into the view
Object {email: "kolexinfos@mail.com"}
Username for user [object Object]
Entered into the view
Page was fully loaded
[Object, Object, Object]
Successfully pulled the Campaigns
Pulling data
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.
[Object, Object, Object]
Successfully pulled the Campaigns
Pulling data
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/shoprite.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/deola.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.
Mixed Content: The page at 'https://ide.c9.io/kolexinfos/shoppa' was loaded over HTTPS, but requested an insecure image 'http://preptitude.com.ng/shoppa/nike.jpg'. This content should also be served over HTTPS.


问:
iOS – Run/Debug/Install builds over Wi-Fi
We have iPad and iPhone devices, but short of wires. Is there any way that we can install/debug the builds over Wi-Fi in iOS?

I know the way in Android, but not of iOS.

答:
(Before you read make sure your running IOS 11 and Xcode 9!) Connect your device (Via USB), once you do go on 'Add Additional Simulators' (See image 2 at the bottom), and tick 'connect via network' (See Image One). Once XCode proccesses this, disconnect the device (via USB) and it should now appear with a globe next to it (See image 2)! Also make sure the device and computer are on the same network!

Image 1

Image 2


问:
ShortCut URL Redirect
To get straight to the point.

I have this URL: http://example.com/?open=encyclopedia&letter=s&term=storm and I want this shortcut URL - http://example.com/storm - to redirect to the first URL: http://example.com/?open=encyclopedia&letter=s&term=storm

I have around 1.000 encyclopedic terms and I want this redirection to work for each term entered. For Example: if a visitor enters http://example.com/Storm to automatically be redirected to the page here: http://example.com/?open=encyclopedia&letter=s&term=storm OR http://example.com/Dried_Plant to http://example.com/?open=encyclopedia&letter=d&term=dried+plant

I prefer some htaccess solution to this, if possible.
If not, give what you can give.
I have no example code for this, since I do not know where to start from.

答:
I suggest you redirect it all to your page encyclopedia. And then consider with php what you can do with it (like finding the first letter or change with _ or others)

You can use:

```<code>RewriteEngine on
# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ encyclopedia?term=%{REQUEST_URI} [NE,L]
</code>```

With correct first letter (letter=), change the last line with:

```<code>RewriteRule ^(.) encyclopedia?letter=$1&term=%{REQUEST_URI} [NE,L]
</code>```

Title: ShortCut URL Redirect

Body:
I suggest you redirect it all to your page encyclopedia. And then consider with php what you can do with it (like finding the first letter or change with _ or others)

You can use:

RewriteEngine on
# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ encyclopedia?term=%{REQUEST_URI} [NE,L]

With correct first letter (letter=), change the last line with:

RewriteRule ^(.) encyclopedia?letter=$1&term=%{REQUEST_URI} [NE,L]


问:
spark kinesis failing on cloudera with java.lang.AbstractMethodError
below is my POM file. I am writing a spark streaming with aws kinesis

```<code><dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>
     <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>amazon-kinesis-client</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kinesis-asl_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>
</code>```

I am facing below exception during run of spark of spark program on Cloudera 5.10

```<code>17/04/27 05:34:04 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 58.0 (TID 179, hadoop1.local, executor 5): java.lang.AbstractMethodError
at org.apache.spark.Logging$class.log(Logging.scala:50)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.log(KinesisCheckpointer.scala:39)
at org.apache.spark.Logging$class.logDebug(Logging.scala:62)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.logDebug(KinesisCheckpointer.scala:39)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.startCheckpointerThread(KinesisCheckpointer.scala:119)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.<init>(KinesisCheckpointer.scala:50)
at org.apache.spark.streaming.kinesis.KinesisReceiver.onStart(KinesisReceiver.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:148)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:130)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:575)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:565)
at org.apache.spark.SparkContext$$anonfun$38.apply(SparkContext.scala:2000)
at org.apache.spark.SparkContext$$anonfun$38.apply(SparkContext.scala:2000)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

This runs perfectly fine on EMR4.4 However CDH fails. Any suggestion

答:
The underlying problem seems to be the use of org.apache.spark.Logging:

NOTE: DO NOT USE this class outside of Spark.
  It is intended as an internal utility.
  This will likely be changed or removed in future releases.

http://spark.apache.org/docs/1.6.2/api/java/org/apache/spark/Logging.html

This is fixed in 2.0.0 as mentioned in https://issues.apache.org/jira/browse/SPARK-9307.

Body:
below is my POM file. I am writing a spark streaming with aws kinesis

<dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>
     <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>amazon-kinesis-client</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kinesis-asl_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>

I am facing below exception during run of spark of spark program on Cloudera 5.10

17/04/27 05:34:04 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 58.0 (TID 179, hadoop1.local, executor 5): java.lang.AbstractMethodError
at org.apache.spark.Logging$class.log(Logging.scala:50)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.log(KinesisCheckpointer.scala:39)
at org.apache.spark.Logging$class.logDebug(Logging.scala:62)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.logDebug(KinesisCheckpointer.scala:39)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.startCheckpointerThread(KinesisCheckpointer.scala:119)
at org.apache.spark.streaming.kinesis.KinesisCheckpointer.<init>(KinesisCheckpointer.scala:50)
at org.apache.spark.streaming.kinesis.KinesisReceiver.onStart(KinesisReceiver.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:148)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:130)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:575)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:565)
at org.apache.spark.SparkContext$$anonfun$38.apply(SparkContext.scala:2000)
at org.apache.spark.SparkContext$$anonfun$38.apply(SparkContext.scala:2000)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

This runs perfectly fine on EMR4.4 However CDH fails. Any suggestion