问:
Is there any way I can pass dynamic data to a component in Angular?

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

```<code>results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}
</code>```

ParentComponent.html

```<code><app-childComponent [dataNeeded]=results></app-childComponent>
</code>```

ChildComponent.ts

```<code>@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}
</code>```

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

答:
if you are sure that your service gets data successfully so this will work :

in the html of your parent component add the quotes  :

```<code><app-childComponent [dataNeeded]="results"></app-childComponent>
</code>```

in your child component , you will check changes of your Inputusing the OnCh:

```<code>ngOnChanges(changes: SimpleChanges) {
   for (let propName in changes) {
      // when your @Input value is changed
      if(propName === "dataNeeded"){
          console.log(dataNeeded);
      }
   }
}
</code>```

Hope this would help :)

Body:
I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComponent.ts

results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}

ParentComponent.html

<app-childComponent [dataNeeded]=results></app-childComponent>

ChildComponent.ts

@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}

So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?

Body:
if you are sure that your service gets data successfully so this will work :

in the html of your parent component add the quotes  :

<app-childComponent [dataNeeded]="results"></app-childComponent>

in your child component , you will check changes of your Inputusing the OnCh:

ngOnChanges(changes: SimpleChanges) {
   for (let propName in changes) {
      // when your @Input value is changed
      if(propName === "dataNeeded"){
          console.log(dataNeeded);
      }
   }
}

Hope this would help :)


来源: stackexchange

问:
Weekday in Haskel wtih gregorian calender formula
Thx for the first Help. Now I changed this. but still a bog error. Is my whole Code wrong or just the part with the weekdays function.
How can i call a function inside another function?

```<code>data Wochentag = Mo | Di | Mi | Do | Fr | Sa | So
deriving (Eq, Ord, Show, Enum)

data Month = Jan | Feb | März | April | Mai | Juni | Juli | Aug | Sep | Okt | Nov | Dec
deriving (Eq, Ord, Show, Enum)

weekday :: Integer -> Month -> Integer -> Wochentag
weekday day month year = weekdays day (zahlmonth month) year

y1 = year - (14 - zahlmonth) /12
x = y1 + (y1 /4) - (y1 /100) + (y1 /400)
m = zahlmonth + 12 * ((14- zahlmonth) /12) -2

weekdays day zahlmonth year
    | mod (day + x + ((31*m) / 12)) 7 == 0 = So
    | mod (day + x + ((31*m) / 12)) 7 == 1 = Mo
    | mod (day + x + ((31*m) / 12)) 7 == 2 = Di
    | mod (day + x + ((31*m) / 12)) 7 == 3 = Mi
    | mod (day + x + ((31*m) / 12)) 7 == 4 = Do
    | mod (day + x + ((31*m) / 12)) 7 == 5 = Fr
    | mod (day + x + ((31*m) / 12)) 7 == 6 = Sa
    | otherwise = error "kein Tag"

zahlmonth :: Month -> Integer
zahlmonth month = case month of
  Jan -> 1
  Feb -> 2
  März -> 3
  April -> 4
  Mai -> 5
  Juni -> 6
  Juli -> 7
  Aug -> 8
  Sep -> 9
  Okt -> 10
  Nov -> 11
  Dec -> 12
</code>```

The error Log is:

```<code> Couldn't match expected type `Month -> Integer'
                  with actual type `Integer'
    * In the first argument of `weekdays', namely `day'
      In the expression: weekdays day (zahlmonth month) year
      In an equation for `weekday':
          weekday day month year = weekdays day (zahlmonth month) year
   |
95 | weekday day month year = weekdays day (zahlmonth month) year
   |                                   ^^^

   Variable not in scope: year :: Month -> Integer
   |
97 | y1 = year - (14 - zahlmonth) /12
   |      ^^^^
</code>```

Totally strange but have no idea how to fix it. When i give weekdays an description it becomes even worse.

答:
The issue here is that you did not add the types for all your top-level bindings, so some of them are being inferred to the wrong type. If only there were a type annotation, GHC would have reported the error immediately, but in absence of that, GHC has no way to see that the inferred type is wrong and so takes it at face value.

Much later on, the wrong type will cause issues, and only then GHC will report the problem -- on irrelevant code.

More in detail, here's what happens:

```<code>m = zahlmonth + ...
</code>```

Here zahlmonth is a function Month -> Integer. Since the result type of + is the same of the arguments, m is also a function Month -> Integer.

Had m :: Integer been present, GHC would stop here with an error. But, alas, GHC can't know that this is the issue.

Then,

```<code>weekdays day zahlmonth year
    | mod (day + x + ((31*m) / 12)) 7 == 0 = So
</code>```

Since the operations +,*,/ work on the same type, we get that
day, x have the same type of m, i.e. Month -> Integer.

If weekdays had a type signature GHC would have spot the error, but without that it will happily carry on.

Finally,

```<code>weekday day month year = weekdays day (zahlmonth month) year
</code>```

Here weekday has a signature, saying that day :: Integer. But above we inferred that weekdays expects day :: Month -> Integer. This triggers the type error

```<code> Couldn't match expected type `Month -> Integer'
                  with actual type `Integer'
    * In the first argument of `weekdays', namely `day'
</code>```

which is crystal clear, after one understands what's going on above during the inference.

The key point is that, however, ... understanding what's going on during the inference is not easy at all! In general, it is very hard to follow GHC in its auto-inferring of types around the program. Fortunately, this is not needed, provided one writes code carefully, annotating the types on the bindings, so that type errors can be caught as early as possible.

ContentLicense: CC BY-SA 3.0

Body:
Thx for the first Help. Now I changed this. but still a bog error. Is my whole Code wrong or just the part with the weekdays function.
How can i call a function inside another function?

data Wochentag = Mo | Di | Mi | Do | Fr | Sa | So
deriving (Eq, Ord, Show, Enum)

data Month = Jan | Feb | März | April | Mai | Juni | Juli | Aug | Sep | Okt | Nov | Dec
deriving (Eq, Ord, Show, Enum)

weekday :: Integer -> Month -> Integer -> Wochentag
weekday day month year = weekdays day (zahlmonth month) year

y1 = year - (14 - zahlmonth) /12
x = y1 + (y1 /4) - (y1 /100) + (y1 /400)
m = zahlmonth + 12 * ((14- zahlmonth) /12) -2

weekdays day zahlmonth year
    | mod (day + x + ((31*m) / 12)) 7 == 0 = So
    | mod (day + x + ((31*m) / 12)) 7 == 1 = Mo
    | mod (day + x + ((31*m) / 12)) 7 == 2 = Di
    | mod (day + x + ((31*m) / 12)) 7 == 3 = Mi
    | mod (day + x + ((31*m) / 12)) 7 == 4 = Do
    | mod (day + x + ((31*m) / 12)) 7 == 5 = Fr
    | mod (day + x + ((31*m) / 12)) 7 == 6 = Sa
    | otherwise = error "kein Tag"

zahlmonth :: Month -> Integer
zahlmonth month = case month of
  Jan -> 1
  Feb -> 2
  März -> 3
  April -> 4
  Mai -> 5
  Juni -> 6
  Juli -> 7
  Aug -> 8
  Sep -> 9
  Okt -> 10
  Nov -> 11
  Dec -> 12

The error Log is:

 Couldn't match expected type `Month -> Integer'
                  with actual type `Integer'
    * In the first argument of `weekdays', namely `day'
      In the expression: weekdays day (zahlmonth month) year
      In an equation for `weekday':
          weekday day month year = weekdays day (zahlmonth month) year
   |
95 | weekday day month year = weekdays day (zahlmonth month) year
   |                                   ^^^

   Variable not in scope: year :: Month -> Integer
   |
97 | y1 = year - (14 - zahlmonth) /12
   |      ^^^^

Totally strange but have no idea how to fix it. When i give weekdays an description it becomes even worse.

Body:
The issue here is that you did not add the types for all your top-level bindings, so some of them are being inferred to the wrong type. If only there were a type annotation, GHC would have reported the error immediately, but in absence of that, GHC has no way to see that the inferred type is wrong and so takes it at face value.

Much later on, the wrong type will cause issues, and only then GHC will report the problem -- on irrelevant code.

More in detail, here's what happens:

m = zahlmonth + ...

Here zahlmonth is a function Month -> Integer. Since the result type of + is the same of the arguments, m is also a function Month -> Integer.

Had m :: Integer been present, GHC would stop here with an error. But, alas, GHC can't know that this is the issue.

Then,

weekdays day zahlmonth year
    | mod (day + x + ((31*m) / 12)) 7 == 0 = So

Since the operations +,*,/ work on the same type, we get that
day, x have the same type of m, i.e. Month -> Integer.

If weekdays had a type signature GHC would have spot the error, but without that it will happily carry on.

Finally,

weekday day month year = weekdays day (zahlmonth month) year

Here weekday has a signature, saying that day :: Integer. But above we inferred that weekdays expects day :: Month -> Integer. This triggers the type error

 Couldn't match expected type `Month -> Integer'
                  with actual type `Integer'
    * In the first argument of `weekdays', namely `day'

which is crystal clear, after one understands what's going on above during the inference.

The key point is that, however, ... understanding what's going on during the inference is not easy at all! In general, it is very hard to follow GHC in its auto-inferring of types around the program. Fortunately, this is not needed, provided one writes code carefully, annotating the types on the bindings, so that type errors can be caught as early as possible.


问:
dplyr | group_by vs anti_join | most efficient way
I have a big data set but here I am creating a sample data which has same data wrangling problem

data

```<code>brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('Window', 'Search', 'Iphone', 'Window', 'Network', 'Iphone', 'DB')
isExist=c('Yes', 'Yes', NA, 'No', NA, 'Yes', NA)
df= data.frame(brand, product, isExist)
</code>```

this data look like this

```<code>   brand product isExist
1     MS  Window     Yes
2 Google  Search     Yes
3  Apple  Iphone    <NA>
4     MS  Window      No
5     FB Network    <NA>
6  Apple  Iphone     Yes
7 Oracle      DB    <NA>
</code>```

now I want the rows based on brand and product (composite key) which does have NA entries for isExist and does not have any other rows for same composite key which has values i.e. it should return FB, Oracle but not Apple as one of the row (row no 6) have value in isExist

I am achieving it using anti_join, here the code

```<code>library(dplyr)
testWithData <- df %>% filter(!is.na(isExist))
testWithoutData <- df %>% filter(is.na(isExist))
final <- unique(anti_join(testWithoutData, testWithData, by = c('brand', 'product')))
</code>```

Output

```<code>   brand product isExist
1     FB Network    <NA>
2 Oracle      DB    <NA>
</code>```

This solution is working but it takes too much time, I know its not most efficient way. I feel group_by and filter can do some magic but I am not sure how I write the query, can someone please help me in this regard

答:
```<code>brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('Window', 'Search', 'Iphone', 'Window', 'Network', 'Iphone', 'DB')
isExist=c('Yes', 'Yes', NA, 'No', NA, 'Yes', NA)
df= data.frame(brand, product, isExist)

library(dplyr)

df %>%
  group_by(brand) %>%                     # for each brand
  filter(sum(!is.na(isExist)) == 0) %>%   # get sum of values that are not NA and keep rows where the sum is 0
  ungroup()

# # A tibble: 2 x 3
#      brand product isExist
#     <fctr>  <fctr>  <fctr>
#   1     FB Network    <NA>
#   2 Oracle      DB    <NA>
</code>```

The above process can be understood if you run this step by step (first 2 rows, then first 3, etc.)

```<code>df %>%
  arrange(brand) %>%                          # order brands to have a better visualisation
  group_by(brand) %>%                         # group by brand and create (on the background) 5 sub-datasets based on each brand (see the Groups: brand [5])
  mutate(Counter = sum(!is.na(isExist))) %>%  # count how many times you have non NA values, based on a brand, and add it as a column while keeping all rows (this is like counting and joining back to the original dataset at the same time)
  filter(Counter == 0) %>%                    # keep only rows with Counter = 0 (those are the ones with only NA values)
  ungroup()                                   # forget the grouping
</code>```

Body:
I have a big data set but here I am creating a sample data which has same data wrangling problem

data

brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('Window', 'Search', 'Iphone', 'Window', 'Network', 'Iphone', 'DB')
isExist=c('Yes', 'Yes', NA, 'No', NA, 'Yes', NA)
df= data.frame(brand, product, isExist)

this data look like this

   brand product isExist
1     MS  Window     Yes
2 Google  Search     Yes
3  Apple  Iphone    <NA>
4     MS  Window      No
5     FB Network    <NA>
6  Apple  Iphone     Yes
7 Oracle      DB    <NA>

now I want the rows based on brand and product (composite key) which does have NA entries for isExist and does not have any other rows for same composite key which has values i.e. it should return FB, Oracle but not Apple as one of the row (row no 6) have value in isExist

I am achieving it using anti_join, here the code

library(dplyr)
testWithData <- df %>% filter(!is.na(isExist))
testWithoutData <- df %>% filter(is.na(isExist))
final <- unique(anti_join(testWithoutData, testWithData, by = c('brand', 'product')))

Output

   brand product isExist
1     FB Network    <NA>
2 Oracle      DB    <NA>

This solution is working but it takes too much time, I know its not most efficient way. I feel group_by and filter can do some magic but I am not sure how I write the query, can someone please help me in this regard

Body:
brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('Window', 'Search', 'Iphone', 'Window', 'Network', 'Iphone', 'DB')
isExist=c('Yes', 'Yes', NA, 'No', NA, 'Yes', NA)
df= data.frame(brand, product, isExist)

library(dplyr)

df %>%
  group_by(brand) %>%                     # for each brand
  filter(sum(!is.na(isExist)) == 0) %>%   # get sum of values that are not NA and keep rows where the sum is 0
  ungroup()

# # A tibble: 2 x 3
#      brand product isExist
#     <fctr>  <fctr>  <fctr>
#   1     FB Network    <NA>
#   2 Oracle      DB    <NA>

The above process can be understood if you run this step by step (first 2 rows, then first 3, etc.)

df %>%
  arrange(brand) %>%                          # order brands to have a better visualisation
  group_by(brand) %>%                         # group by brand and create (on the background) 5 sub-datasets based on each brand (see the Groups: brand [5])
  mutate(Counter = sum(!is.na(isExist))) %>%  # count how many times you have non NA values, based on a brand, and add it as a column while keeping all rows (this is like counting and joining back to the original dataset at the same time)
  filter(Counter == 0) %>%                    # keep only rows with Counter = 0 (those are the ones with only NA values)
  ungroup()                                   # forget the grouping


问:
Get form attribute value with PHP
Is there a way to get submitted form's attribute value using PHP, when the submit button is clicked?

I have a form which has attribute data-id: someid, I need to get this value.

答:
You can achieve this in php with two ways:

1. Either pass your 'someid' in input with hidden type

```<code><input type="hidden" name="data-id" value="someid" />
</code>```

2. Just pass your 'someid' in action attribute

```<code><form name="" action="filename.php?data-id=someid">
</code>```

Title: Get form attribute value with PHP

Body:
You can achieve this in php with two ways:

1. Either pass your 'someid' in input with hidden type

<input type="hidden" name="data-id" value="someid" />

2. Just pass your 'someid' in action attribute

<form name="" action="filename.php?data-id=someid">


问:
html child element to extend over parent boundaries
Basically, as the title states, I want a child element to extend over the parent boundaries. This element is only visible when hovering its parent element.

I'm not allowed to share the whole css, so I tried to create a basic jsfiddle to demonstrate my problem here

Our layout looks something like:

```<code>   Fixed top bar
_____________________
S  |  Scrollable body
i  |
d  |
e  |
b  |
a  |
r  |
</code>```

where sidebar is also fixed. Sidebar contains multiple scrollable items.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    display: block;
    opacity: 1;
}

.help-text {
    display: none;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
    z-index: 1500;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        ```

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

```

I want to avoid having the vertical and horizontal scrollbars and when the help text is shown it should go over the parent div's limits. z-index isn't working. Is this possible?

EDIT

Was able to get rid of the scrollbars when help-text is not shown by changing visibility to display, but still the text is shown inside parent container when hovered over

答:
What you could do is to use position fixed, be careful this will put the help tool tip in relation to the window, you can use margins to set the position(because by default the fixed position item, appears next to its parent), if you use top and left, it will put the element the in relation to the view port..

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

.help:hover .help-text {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}

.help-text {
    visibility: hidden;
    opacity: 0;
    position: fixed;
    margin-top: -5px;
    margin-left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        ```

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

```

Body:
Basically, as the title states, I want a child element to extend over the parent boundaries. This element is only visible when hovering its parent element.

I'm not allowed to share the whole css, so I tried to create a basic jsfiddle to demonstrate my problem here

Our layout looks something like:

   Fixed top bar
_____________________
S  |  Scrollable body
i  |
d  |
e  |
b  |
a  |
r  |

where sidebar is also fixed. Sidebar contains multiple scrollable items.

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

span:hover + .help-text {
    transition: all 0.2s 0.4s;
    display: block;
    opacity: 1;
}

.help-text {
    display: none;
    opacity: 0;
    position: absolute;
    top: -5px;
    left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
    z-index: 1500;
}

        hover over me

          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data

      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh

I want to avoid having the vertical and horizontal scrollbars and when the help text is shown it should go over the parent div's limits. z-index isn't working. Is this possible?

EDIT

Was able to get rid of the scrollbars when help-text is not shown by changing visibility to display, but still the text is shown inside parent container when hovered over

Body:
What you could do is to use position fixed, be careful this will put the help tool tip in relation to the window, you can use margins to set the position(because by default the fixed position item, appears next to its parent), if you use top and left, it will put the element the in relation to the view port..

.sidebar {
    width: 25%;
    position: fixed;
    display: flex;
    flex-direction: column;
}

.sidebar-item {
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.body {
  overflow: auto;
}

.help {
    display: inline-block;
    position: relative;
    cursor: default;
    padding-right: 10px;
    z-index: 2;
}

.help:hover .help-text {
    transition: all 0.2s 0.4s;
    visibility: visible;
    opacity: 1;
}

.help-text {
    visibility: hidden;
    opacity: 0;
    position: fixed;
    margin-top: -5px;
    margin-left: 10px;
    width: 300px;
    padding: 5px;
    font-size: 12px;
    background-color: black;
    color: white;
    white-space: pre-wrap;
    border-radius: 5px;
}

<div class="sidebar">
  <div class="sidebar-item">
    <div class="body">
      <div class="help">
        <span>hover over me</span>
        <pre class="help-text">
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
          some test data
        </pre>
      </div>
      gvregrfvrtyewrfgvrtbh
      vgrewtghwrt
      frgerghrthbed
      hewrtgrhbrwwh
    </div>
  </div>
</div>


问:
Resource as a filename
Im using EMGUCV at Visual Studio 2017. I need to set a XML file to a cascadeClassifier like this:

```<code>CascadeClassifier cascadeClassifier = new CascadeClassifier(@"cascadeClassifier\haarcascade_frontalface_alt2.xml");
</code>```

Doing this way I need to get a copy of XML file to my Release. So I discover the resource stuff by this question here. So I add the XML to my resource and tried to access it by:

```<code>CascadeClassifier cascadeClassifier = new CascadeClassifier(Properties.Resources.haarcascade_frontalface_alt2);
</code>```

But this object resource is a string and the CascadeClassifier is expecting a filename, is there a way to do it?

答:
Well, according to the API documentation the construction takes in a filename (as you said), but the type of the filename can be a string (must be a string) so there should be no problem when you pass in a string from a resource file/dictionary:
http://www.emgu.com/wiki/files/2.4.2/document/html/b5ce78f6-d5cc-a099-d1a8-25df92564f64.htm

Constructor is:

```<code>public CascadeClassifier(
    string fileName
)
</code>```

See also this question/answer for an example (without resources used):
How to load a CascadeClassifier using Emgu c#

Title: Resource as a filename

Body:
Im using EMGUCV at Visual Studio 2017. I need to set a XML file to a cascadeClassifier like this:

CascadeClassifier cascadeClassifier = new CascadeClassifier(@"cascadeClassifier\haarcascade_frontalface_alt2.xml");

Doing this way I need to get a copy of XML file to my Release. So I discover the resource stuff by this question here. So I add the XML to my resource and tried to access it by:

CascadeClassifier cascadeClassifier = new CascadeClassifier(Properties.Resources.haarcascade_frontalface_alt2);

But this object resource is a string and the CascadeClassifier is expecting a filename, is there a way to do it?

Body:
Well, according to the API documentation the construction takes in a filename (as you said), but the type of the filename can be a string (must be a string) so there should be no problem when you pass in a string from a resource file/dictionary:
http://www.emgu.com/wiki/files/2.4.2/document/html/b5ce78f6-d5cc-a099-d1a8-25df92564f64.htm

Constructor is:

public CascadeClassifier(
    string fileName
)

See also this question/answer for an example (without resources used):
How to load a CascadeClassifier using Emgu c#


问:
mat-checkbox check only if condition is true
I have a user table list with mat-checkbox. When mat-checkbox is clicked, the checkbox should be checked only if a certain condition is true.

Here in this code, I am trying to have checkbox checked only for id=2. But as you can see, initially when checkbox of 2 is clicked, it doesn't get checked even though 2 is added to array of elements which should be checked.

On the other hand, when checkbox of 1,3 or 4 is clicked, they get checked.

component.html

```<code><tbody>
    <tr *ngFor="let user of users; let in = index">
            <td>
                <mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
            </td>
    </tr>
</tbody>
</code>```

component.ts

```<code>export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("select " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }

  }

}
</code>```

Working code: https://stackblitz.com/edit/mat-checkbox-conditional

答:
I have used event binding on ngModel in the html and also modified some code in app.component.ts. Now only the checkbox with id 2 can be checked. Please see the code below

in app.component.html

```<code><mat-checkbox (ngModel)="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
</code>```

and in app.component.ts

```<code>export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log(this.selected.includes(id));
    return this.selected.includes(id);
  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2){
         this.selected.push(id);
      }
      else{
         return false;
      }
    }
    else {
      if(id == 2){
        this.selected = [];
      }
      else
       return false;
    }
  }

}
</code>```

Here is a working link

https://stackblitz.com/edit/mat-checkbox-conditional-z8uc94

Body:
I have a user table list with mat-checkbox. When mat-checkbox is clicked, the checkbox should be checked only if a certain condition is true.

Here in this code, I am trying to have checkbox checked only for id=2. But as you can see, initially when checkbox of 2 is clicked, it doesn't get checked even though 2 is added to array of elements which should be checked.

On the other hand, when checkbox of 1,3 or 4 is clicked, they get checked.

component.html

                <mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>

component.ts

export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log("check " + id)
    console.log(this.selected)
    return this.selected.includes(id);

  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2)
        this.selected.push(id);
      console.log("select " + id)
      console.log(this.selected)
    }
    else {
      this.selected = this.selected.filter(item => item !== id)
    }

  }

}

Working code: https://stackblitz.com/edit/mat-checkbox-conditional

Body:
I have used event binding on ngModel in the html and also modified some code in app.component.ts. Now only the checkbox with id 2 can be checked. Please see the code below

in app.component.html

<mat-checkbox (ngModel)="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>

and in app.component.ts

export class AppComponent {

  users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
  checked: boolean = true
  constructor() { }
  selected: any = [];

  canbeChecked(id): boolean {
    console.log(this.selected.includes(id));
    return this.selected.includes(id);
  }

  userSelectClick(id) {

    if (!this.selected.includes(id)) {
      if (id == 2){
         this.selected.push(id);
      }
      else{
         return false;
      }
    }
    else {
      if(id == 2){
        this.selected = [];
      }
      else
       return false;
    }
  }

}

Here is a working link

https://stackblitz.com/edit/mat-checkbox-conditional-z8uc94


问:
Merge multiple sass maps returns type string not map
Similar to this idea, I created a helper method to merge multiple sass maps.
https://stackoverflow.com/a/30740182/6413673

My Helper code as follows:

```<code>@function map-merge-all($maps...) {
  $result: ();

  @each $map in $maps {
    $result: map-merge($result, $map);
  }
  @return $result;
}
</code>```

My issue is, that its not returning a map, instead its returning a string.

```<code>$params : map-merge-all($mapA,$mapB,$mapC);
@warn "$mapA type is:"+type-of($mapA);
@warn "$mapB type is:"+type-of($mapB);
@warn "$mapC type is:"+type-of($mapC);
@warn "$param type is:"+type-of($params);
</code>```

Output is :

```<code>WARNING: $mapA type is:map
WARNING: $mapB type is:map
WARNING: $mapB type is:map
WARNING: $params type is:string
</code>```

Any ideas as to what is wrong with my helper method?

答: Seems the method is fine, my issue was that I was not calling the @import method for my helper file, so it was in fact not even calling the map-merge-all method.</p>

Body:
Similar to this idea, I created a helper method to merge multiple sass maps.
https://stackoverflow.com/a/30740182/6413673

My Helper code as follows:

@function map-merge-all($maps...) {
  $result: ();

  @each $map in $maps {
    $result: map-merge($result, $map);
  }
  @return $result;
}

My issue is, that its not returning a map, instead its returning a string.

$params : map-merge-all($mapA,$mapB,$mapC);
@warn "$mapA type is:"+type-of($mapA);
@warn "$mapB type is:"+type-of($mapB);
@warn "$mapC type is:"+type-of($mapC);
@warn "$param type is:"+type-of($params);

Output is :

WARNING: $mapA type is:map
WARNING: $mapB type is:map
WARNING: $mapB type is:map
WARNING: $params type is:string

Any ideas as to what is wrong with my helper method?


问:
How to make only part of Ember route model a promise?
I have a simple template.hbs like this:

```<code>// template.hbs

<p>{{model.x}}</p>
<p>{{model.y}}</p>
</code>```

The following route.js works as expected:

```<code>// route.js

import Route from '@ember/routing/route';

export default Route.extend({

    model() {

        return {
            x: 'foo',
            y: 'bar'
        };

    }
});

// output, immediately:
// foo
// bar
</code>```

The following also works, now using a promise for the whole model:

```<code>// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return new RSVP.Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    x: 'foo',
                    y: 'bar'
                });
            }, 1000);
        });

    }
});

// output, after 1s:
// foo
// bar
</code>```

The following, where I want to make only model.x a promise - does NOT work.

```<code>// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return {
            x: new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            }),
            y: 'bar'
        };

    }
});

// output, IMMEDIATELY:
// [object Object]
// bar
</code>```

It renders output immediately, but after it enters the callback in setTimeout it doesn't change the rendered value for model.x.

I am aware of RSVP.hash(), but that will reject if any of the promises rejects. Is it possible to have independent promises for different parts of route model or only all-or-nothing?

Oddly enough, if the promise in question is returned by ember-data, e.g. x: this.get('store').findRecord('user'), it works as it should work (changing template.hbs with
{{model.x.name}}
 for instance).

答:
You could use PromiseObject or PromiseArray from ember-data:

```<code>export default Ember.Route.extend({
  model() {
        return {
            x: DS.PromiseObject.create({
              promise: new RSVP.Promise((resolve) => {
                  setTimeout(() => {
                      resolve({name: 'foo'});
                  }, 5000);
              })
            }),
            y: 'bar'
        };
    }
});
</code>```

For this to work, your promise result has to be an object (i.e. {name: 'foo'} instead of only foo). You can then use x.namein your template, which will return undefined until the promise returns.

Body:
I have a simple template.hbs like this:

// template.hbs

{{model.x}}

{{model.y}}

The following route.js works as expected:

// route.js

import Route from '@ember/routing/route';

export default Route.extend({

    model() {

        return {
            x: 'foo',
            y: 'bar'
        };

    }
});

// output, immediately:
// foo
// bar

The following also works, now using a promise for the whole model:

// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return new RSVP.Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    x: 'foo',
                    y: 'bar'
                });
            }, 1000);
        });

    }
});

// output, after 1s:
// foo
// bar

The following, where I want to make only model.x a promise - does NOT work.

// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return {
            x: new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            }),
            y: 'bar'
        };

    }
});

// output, IMMEDIATELY:
// [object Object]
// bar

It renders output immediately, but after it enters the callback in setTimeout it doesn't change the rendered value for model.x.

I am aware of RSVP.hash(), but that will reject if any of the promises rejects. Is it possible to have independent promises for different parts of route model or only all-or-nothing?

Oddly enough, if the promise in question is returned by ember-data, e.g. x: this.get('store').findRecord('user'), it works as it should work (changing template.hbs with
{{model.x.name}}
 for instance).

Body:
You could use PromiseObject or PromiseArray from ember-data:

export default Ember.Route.extend({
  model() {
        return {
            x: DS.PromiseObject.create({
              promise: new RSVP.Promise((resolve) => {
                  setTimeout(() => {
                      resolve({name: 'foo'});
                  }, 5000);
              })
            }),
            y: 'bar'
        };
    }
});

For this to work, your promise result has to be an object (i.e. {name: 'foo'} instead of only foo). You can then use x.namein your template, which will return undefined until the promise returns.


问:
How to responsively place links in a navbar
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

```

Keeping the dropdown open while in hamburger-mode is a problem for another day.

答:
This is solved. Solution was embarrassingly  simple. I wrapped profile name and img in a div and set it to width: fit-content. Then when changing the float on the profile name to right with media queries, it positioned itself right next to the img.

Thanks for the responses though!

Body:
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

Keeping the dropdown open while in hamburger-mode is a problem for another day.


问:
Unable to run mongo container with replica set using docker-compose
Here's my docker-compose file:

```<code>version: '3'
services:

  mongo:
    hostname: mongo
    container_name: search_mongo
    image: mongo:latest
    volumes:
      - ./docker/local/persist/mongo:/data/db
      - ./docker/mongo:/opt/mongo
    ports:
      - "8884:27017"
      - "8885:27018"
    entrypoint: /opt/mongo/entrypoint_mongo.sh

  agent:
    build: .
    image: myapp_search:compose
    depends_on:
      - mongo
</code>```

Here's my entrypoint_mongo.sh

```<code>#!/bin/bash
mongod --port 27018 --replSet rs0 --fork --syslog --smallfiles
mongo --port 27018 --eval "rs.initiate({_id : 'rs0', members : [{_id : 0, host : 'mongo:27018'}]})"
mongo --port 27018 --eval "while(true) {if (rs.status().ok) break;sleep(1000)};"
</code>```

The issue I am facing is :
The mongo container is executing all its steps successfully but its exiting with status 0.

```<code>mongo_1          | about to fork child process, waiting until server is ready for connections.
mongo_1          | forked process: 7
mongo_1          | child process started successfully, parent exiting
mongo_1          | MongoDB shell version v3.4.10
mongo_1          | connecting to: mongodb://127.0.0.1:27018/
mongo_1          | MongoDB server version: 3.4.10
mongo_1          | { "ok" : 1 }
mongo_1          | MongoDB shell version v3.4.10
mongo_1          | connecting to: mongodb://127.0.0.1:27018/
mongo_1          | MongoDB server version: 3.4.10
search_mongo exited with code 0
</code>```

答:
If your last command at the script will never exit (i.e. stop running), your container keeps running. So, while (true);do sleep 1; done is one fix.

If you want to have solution where you can close container when wanted, you can use something like

while (! test -e /tmp/stop); do sleep 1; done; rm /tmp/stop

So, when you say at command line touch /tmp/stop, it will stop that loop  what keeps container running.

Body:
Here's my docker-compose file:

version: '3'
services:

  mongo:
    hostname: mongo
    container_name: search_mongo
    image: mongo:latest
    volumes:
      - ./docker/local/persist/mongo:/data/db
      - ./docker/mongo:/opt/mongo
    ports:
      - "8884:27017"
      - "8885:27018"
    entrypoint: /opt/mongo/entrypoint_mongo.sh

  agent:
    build: .
    image: myapp_search:compose
    depends_on:
      - mongo

Here's my entrypoint_mongo.sh

#!/bin/bash
mongod --port 27018 --replSet rs0 --fork --syslog --smallfiles
mongo --port 27018 --eval "rs.initiate({_id : 'rs0', members : [{_id : 0, host : 'mongo:27018'}]})"
mongo --port 27018 --eval "while(true) {if (rs.status().ok) break;sleep(1000)};"

The issue I am facing is :
The mongo container is executing all its steps successfully but its exiting with status 0.

mongo_1          | about to fork child process, waiting until server is ready for connections.
mongo_1          | forked process: 7
mongo_1          | child process started successfully, parent exiting
mongo_1          | MongoDB shell version v3.4.10
mongo_1          | connecting to: mongodb://127.0.0.1:27018/
mongo_1          | MongoDB server version: 3.4.10
mongo_1          | { "ok" : 1 }
mongo_1          | MongoDB shell version v3.4.10
mongo_1          | connecting to: mongodb://127.0.0.1:27018/
mongo_1          | MongoDB server version: 3.4.10
search_mongo exited with code 0


问:
Rails: How to change the text on the submit button in a Rails Form
i have listed my _form.html.erb file below what i would like to do is change the text on the submit button i know how to do it in html but not shure how to do it in Rails 3</p>

```<code>%= form_for(@faq) do |f| %>
  <% if @faq.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@faq.errors.count, "error") %> prohibited this faq from being saved:</h2>

      <ul>
      <% @faq.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :question %><br />
    <%= f.text_field :question %>
  </div>
  <div class="field">
    <%= f.label :answer %><br />
    <%= f.text_area :answer %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
instead of

```<code><%= f.submit  %>
</code>```

put

```<code><%= f.submit "My Submit Text" %>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have listed my _form.html.erb file below what i would like to do is change the text on the submit button i know how to do it in html but not shure how to do it in Rails 3

%= form_for(@faq) do |f| %>
  <% if @faq.errors.any? %>

<%= pluralize(@faq.errors.count, "error") %> prohibited this faq from being saved:

      <% @faq.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :question %>

    <%= f.text_field :question %>

    <%= f.label :answer %>

    <%= f.text_area :answer %>

    <%= f.submit %>

<% end %>

Body:
instead of

<%= f.submit  %>

put

<%= f.submit "My Submit Text" %>

ContentLicense: CC BY-SA 2.5


问:
How can i make DatePickerFor a readonly?
i have the DatePickerFor and i want to make it readonly I want to force user to pick dates ,not being able to type them.

```<code><td>@(Html.Kendo().DatePickerFor(model => model.DateRecherche).Max(DateTime.Today))</td>
</code>```

Thanks.

答:
Is it in their docs:

```<code>//DISABLE inputs
$("#datepicker").attr("readonly", true);
$("#monthpicker").attr("readonly", true);
</code>```

So you will need a little bit of javascript along with your view code to implement this behavior

Body:
i have the DatePickerFor and i want to make it readonly I want to force user to pick dates ,not being able to type them.

@(Html.Kendo().DatePickerFor(model => model.DateRecherche).Max(DateTime.Today))

Thanks.

Body:
Is it in their docs:

//DISABLE inputs
$("#datepicker").attr("readonly", true);
$("#monthpicker").attr("readonly", true);

So you will need a little bit of javascript along with your view code to implement this behavior


问:
Why does executing Spark application fail in IntelliJ IDEA with "NoClassDefFoundError: org/apache/spark/mllib/regression/LabeledPoint"?
I've been writing a simple code using Spark MLlib and scala.
But, when I ran the code, I got the error "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/mllib/regression/LabeledPoint"
. What causes this error?

And the IDE tool (IntelliJ) told me "LinearRegressionWithSGD is deprecated"
I installed the spark version of 2.2.0 and the scala version of 2.11.
What am I supposed to do? if I want to use the "LinearRegressionWithSGD".

Please help me with this.

The code is as follows:

```<code>import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.mllib.regression.LinearRegressionWithSGD
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors

import java.io.StringWriter
import au.com.bytecode.opencsv.CSVWriter
import scala.collection.JavaConversions._
import java.io.FileWriter
import java.io.BufferedWriter

import java.io.File

// feature vector
var _00h = Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

object CacheAlgoApp {
  def main(args: Array[String]) : Unit = {

      // Load and parse the data
      var data = sc.textFile("test.log")
      var operationData = data.filter(line => line.contains("operations"))

      val adjustTime = 6

      var parsedData = operationData.map { line =>
        var parts = line.split(' ')
        LabeledPoint(parts(adjustTime+0).toDouble, Vectors.dense(_00h.take(24).map(_.toDouble)))
      }

      // Build linear regression model
      var regression = new LinearRegressionWithSGD().setIntercept(false)
      regression.optimizer.setNumIterations(200)
      regression.optimizer.setStepSize(1) //0.0, 0.20999999999999963, 0.03999999999999999
      var model00 = regression.run(parsedData)

    }
}
</code>```

And the pom.xml is as follows. Could It be the problem of the dependency?

```<code><dependencies>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.11.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-mllib -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_2.11</artifactId>
        <version>2.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

答:
tl;dr Remove provided scope for spark-mllib_2.11 dependency and start over.

The reason for the exception is that you ran the code without Spark MLlib on the application's classpath.

However you ran the code the class uses Spark MLlib's LinearRegressionWithSGD and so requires the class to be available on CLASSPATH.

Executing Spark code using Intellij IDEA can sometimes be tricky to get right, but usually just works. If it does not, it's highly advised to use the recommended way of submitting a Spark application (of any kind with or without Spark MLlib) using spark-submit as described in the Spark official documentation's Submitting Applications:

The spark-submit script in Spark’s bin directory is used to launch applications on a cluster.

Just skip "on a cluster" part as that's of no help here (and actually incorrect).

spark-mllib_2.11 dependency that represents Spark MLlib at code level is in provided scope and hence unavailable on your Spark application's CLASSPATH. Remove provided scope and start over. It's supposed to work fine.

Body:
I've been writing a simple code using Spark MLlib and scala.
But, when I ran the code, I got the error "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/mllib/regression/LabeledPoint"
. What causes this error?

And the IDE tool (IntelliJ) told me "LinearRegressionWithSGD is deprecated"
I installed the spark version of 2.2.0 and the scala version of 2.11.
What am I supposed to do? if I want to use the "LinearRegressionWithSGD".

Please help me with this.

The code is as follows:

import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.mllib.regression.LinearRegressionWithSGD
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors

import java.io.StringWriter
import au.com.bytecode.opencsv.CSVWriter
import scala.collection.JavaConversions._
import java.io.FileWriter
import java.io.BufferedWriter

import java.io.File

// feature vector
var _00h = Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

object CacheAlgoApp {
  def main(args: Array[String]) : Unit = {

      // Load and parse the data
      var data = sc.textFile("test.log")
      var operationData = data.filter(line => line.contains("operations"))

      val adjustTime = 6

      var parsedData = operationData.map { line =>
        var parts = line.split(' ')
        LabeledPoint(parts(adjustTime+0).toDouble, Vectors.dense(_00h.take(24).map(_.toDouble)))
      }

      // Build linear regression model
      var regression = new LinearRegressionWithSGD().setIntercept(false)
      regression.optimizer.setNumIterations(200)
      regression.optimizer.setStepSize(1) //0.0, 0.20999999999999963, 0.03999999999999999
      var model00 = regression.run(parsedData)

    }
}

And the pom.xml is as follows. Could It be the problem of the dependency?

<dependencies>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.11.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_2.11</artifactId>
        <version>2.1.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>


问:
Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found
Gradle file:

```<code>android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '27.0.1'
</code>```

It works perfectly in other Windows machine, but in this computer it gives this error: Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found.

I need to compile with Google APIs:23 instead of SDK 23 because I'm using some things that are in Google APIs add-on.

I checked that some solutions here in Stack Overflow tell that you can avoid this problem changing my Gradle file to compileSdkVersion 23, but it is not a good solution because if you do that you are not compiling using Google APIs add-ons.

Both AndroidStudios and AndroidSDKs are fully updated in both machines, so I can't understand why I'm getting this error only in one of them.

答:
From google's github:

If you are developing for Android and the Google API you want to use is included in the Google Play Services library, you should use that library for the best performance and experience.

So check first if the Google API you need is included in play services or not. If yes then use that. If you need to use other Google APIs, then you can find the setup instructions here.

And finally, here's an example project from google that uses the google play services library and the other Google APIs outside of play services:

```<code>dependencies {
    compile 'com.google.apis:google-api-services-calendar:v3-rev260-1.23.0' exclude module: 'httpclient'
    compile 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient'
    compile 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient'
    compile 'com.google.android.gms:play-services-identity:7.3.0'
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    .
    .
}
</code>```

Body:
Gradle file:

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '27.0.1'

It works perfectly in other Windows machine, but in this computer it gives this error: Error:Module 'app': platform 'Google Inc.:Google APIs:23' not found.

I need to compile with Google APIs:23 instead of SDK 23 because I'm using some things that are in Google APIs add-on.

I checked that some solutions here in Stack Overflow tell that you can avoid this problem changing my Gradle file to compileSdkVersion 23, but it is not a good solution because if you do that you are not compiling using Google APIs add-ons.

Both AndroidStudios and AndroidSDKs are fully updated in both machines, so I can't understand why I'm getting this error only in one of them.

Body:
From google's github:

If you are developing for Android and the Google API you want to use is included in the Google Play Services library, you should use that library for the best performance and experience.

So check first if the Google API you need is included in play services or not. If yes then use that. If you need to use other Google APIs, then you can find the setup instructions here.

And finally, here's an example project from google that uses the google play services library and the other Google APIs outside of play services:

dependencies {
    compile 'com.google.apis:google-api-services-calendar:v3-rev260-1.23.0' exclude module: 'httpclient'
    compile 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient'
    compile 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient'
    compile 'com.google.android.gms:play-services-identity:7.3.0'
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    .
    .
}


问:
How can I append a button with data-toggle attribute?
I have a button that opens a sidebar, when I click on it. When I append the same button to my box and the click on it, it is not opening the sidebar:

```<code>  <button class="btn btn-default" data-toggle="control-sidebar">Toggle Right Sidebar</button>
</code>```

$(document).off("click", ".click").on("click", ".click", function (event) {
  $(".box").append(stuff);
});

var stuff = $('<button class="btn btn-default" data-toggle="control-sidebar">This button is not opening the sidebar. Why?</button>');

$.AdminLTE = {};
$.AdminLTE.options = {
    enableControlSidebar: true,
    controlSidebarOptions: {
        toggleBtnSelector: "[data-toggle='control-sidebar']",
        selector: ".control-sidebar",
        slide: false
    },
};

$(function () {
    "use strict";

    $("body").removeClass("hold-transition");

    if (typeof AdminLTEOptions !== "undefined") {
        $.extend(true,
            $.AdminLTE.options,
            AdminLTEOptions);
    }

    var o = $.AdminLTE.options;

    _init();

    $.AdminLTE.tree('.sidebar');

    if (o.enableControlSidebar) {
        $.AdminLTE.controlSidebar.activate();
    }

    if (o.sidebarPushMenu) {
        $.AdminLTE.pushMenu.activate(o.sidebarToggleSelector);
    }

});

function _init() {
    'use strict';

    $.AdminLTE.layout = {
        activate: function () {
            var _this = this;
            _this.fix();
            _this.fixSidebar();
            $(window, ".wrapper").resize(function () {
                _this.fix();
                _this.fixSidebar();
            });
        },
        fix: function () {

            var neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight();
            var window_height = $(window).height();
            var sidebar_height = $(".sidebar").height();
            if ($("body").hasClass("fixed")) {
                $(".content-wrapper, .right-side").css('min-height', window_height - $('.main-footer').outerHeight());
            } else {
                var postSetWidth;
                if (window_height >= sidebar_height) {
                    $(".content-wrapper, .right-side").css('min-height', window_height - neg);
                    postSetWidth = window_height - neg;
                } else {
                    $(".content-wrapper, .right-side").css('min-height', sidebar_height);
                    postSetWidth = sidebar_height;
                }

                var controlSidebar = $($.AdminLTE.options.controlSidebarOptions.selector);
                if (typeof controlSidebar !== "undefined") {
                    if (controlSidebar.height() > postSetWidth)
                        $(".content-wrapper, .right-side").css('min-height', controlSidebar.height());
                }

            }
        },
        fixSidebar: function () {
            if (!$("body").hasClass("fixed")) {
                if (typeof $.fn.slimScroll != 'undefined') {
                    $(".sidebar").slimScroll({
                        destroy: true
                    }).height("auto");
                }
                return;
            } else if (typeof $.fn.slimScroll == 'undefined' && window.console) {
                window.console.error("Error: the fixed layout requires the slimscroll plugin!");
            }
            if ($.AdminLTE.options.sidebarSlimScroll) {
                if (typeof $.fn.slimScroll != 'undefined') {

                    $(".sidebar").slimScroll({
                        destroy: true
                    }).height("auto");

                    $(".sidebar").slimscroll({
                        height: ($(window).height() - $(".main-header").height()) + "px",
                        color: "rgba(0,0,0,0.2)",
                        size: "3px"
                    });
                }
            }
        }
    };

    $.AdminLTE.tree = function (menu) {
        var _this = this;
        var animationSpeed = $.AdminLTE.options.animationSpeed;
        $(document).off('click', menu + ' li a')
            .on('click', menu + ' li a', function (e) {

                var $this = $(this);
                var checkElement = $this.next();

                if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible')) && (!$('body').hasClass('sidebar-collapse'))) {

                    checkElement.slideUp(animationSpeed, function () {
                        checkElement.removeClass('menu-open');

                    });
                    checkElement.parent("li").removeClass("active");
                }

                else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {

                    var parent = $this.parents('ul').first();

                    var ul = parent.find('ul:visible').slideUp(animationSpeed);

                    ul.removeClass('menu-open');

                    var parent_li = $this.parent("li");

                    checkElement.slideDown(animationSpeed, function () {

                        checkElement.addClass('menu-open');
                        parent.find('li.active').removeClass('active');
                        parent_li.addClass('active');

                        _this.layout.fix();
                    });
                }

                if (checkElement.is('.treeview-menu')) {
                    e.preventDefault();
                }
            });
    };

    $.AdminLTE.controlSidebar = {

        activate: function () {

            var _this = this;
            var o = $.AdminLTE.options.controlSidebarOptions;
            var sidebar = $(o.selector);

            var btn = $(o.toggleBtnSelector);

            btn.on('click', function (e) {
                e.preventDefault();
                _this.open(sidebar, o.slide);

            });

            $(".close_sidebar").on('click', function (e) {
                _this.close(sidebar, o.slide);
            });

            var bg = $(".control-sidebar-bg");
            _this._fix(bg);

            if ($('body').hasClass('fixed')) {
                _this._fixForFixed(sidebar);
            } else {

                if ($('.content-wrapper, .right-side').height() < sidebar.height()) {
                    _this._fixForContent(sidebar);
                }
            }
        },
        open: function (sidebar, slide) {

            if (slide) {
                sidebar.addClass('control-sidebar-open');
            } else {

                $('body').addClass('control-sidebar-open');
            }
        },

        close: function (sidebar, slide) {
            if (slide) {
                sidebar.removeClass('control-sidebar-open');
            } else {
                $('body').removeClass('control-sidebar-open');
            }
        },
        _fix: function (sidebar) {
            var _this = this;
            if ($("body").hasClass('layout-boxed')) {
                sidebar.css('position', 'absolute');
                sidebar.height($(".wrapper").height());
                if (_this.hasBindedResize) {
                    return;
                }
                $(window).resize(function () {
                    _this._fix(sidebar);
                });
                _this.hasBindedResize = true;
            } else {
                sidebar.css({
                    'position': 'fixed',
                    'height': 'auto'
                });
            }
        },
        _fixForFixed: function (sidebar) {
            sidebar.css({
                'position': 'fixed',
                'max-height': '100%',
                'overflow': 'auto',
                'padding-bottom': '50px'
            });
        },
        _fixForContent: function (sidebar) {
            $(".content-wrapper, .right-side").css('min-height', sidebar.height());
        }
    };

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
  width:100px;
  height:50px;
  background-color:pink
}

.control-sidebar-bg {
  position: fixed;
  z-index: 1000;
  bottom: 0;
}
.control-sidebar-bg,
.control-sidebar {
  top: 0;
  right: -430px;
  width: 430px;
  -webkit-transition: right 0.3s ease-in-out;
  -o-transition: right 0.3s ease-in-out;
  transition: right 0.3s ease-in-out;
}
.control-sidebar {
  position: absolute;
  padding-top: 50px;
  z-index: 1010;
}

.control-sidebar > .tab-content {
  padding: 10px 15px;
}
.control-sidebar.control-sidebar-open,
.control-sidebar.control-sidebar-open + .control-sidebar-bg {
  right: 0;
}
.control-sidebar-open .control-sidebar-bg,
.control-sidebar-open .control-sidebar {
  right: 0;
}

.control-sidebar-heading {
  font-weight: 400;
  font-size: 16px;
  padding: 10px 0;
  margin-bottom: 10px;
}
.control-sidebar-subheading {
  display: block;
  font-weight: 400;
  font-size: 14px;
}
.control-sidebar-menu {
  list-style: none;
  padding: 0;
  margin: 0 -15px;
}
.control-sidebar-menu > li > a {
  display: block;
  padding: 10px 15px;
}
.control-sidebar-menu > li > a:before,
.control-sidebar-menu > li > a:after {
  content: " ";
  display: table;
}
.control-sidebar-menu > li > a:after {
  clear: both;
}
.control-sidebar-menu > li > a > .control-sidebar-subheading {
  margin-top: 0;
}
.control-sidebar-menu .menu-icon {
  float: left;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  text-align: center;
  line-height: 35px;
}
.control-sidebar-menu .menu-info {
  margin-left: 45px;
  margin-top: 3px;
}
.control-sidebar-menu .menu-info > .control-sidebar-subheading {
  margin: 0;
}
.control-sidebar-menu .menu-info > p {
  margin: 0;
  font-size: 11px;
}
.control-sidebar-menu .progress {
  margin: 0;
}
.control-sidebar-dark {
  color: #b8c7ce;
}
.control-sidebar-dark,
.control-sidebar-dark + .control-sidebar-bg {
  background: #222d32;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs {
  border-bottom: #1c2529;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a {
  background: #181f23;
  color: #b8c7ce;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:focus {
  border-left-color: #141a1d;
  border-bottom-color: #141a1d;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:focus,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:active {
  background: #1c2529;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover {
  color: #fff;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:focus,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:active {
  background: #222d32;
  color: #fff;
}
.control-sidebar-dark .control-sidebar-heading,
.control-sidebar-dark .control-sidebar-subheading {
  color: #fff;
}
.control-sidebar-dark .control-sidebar-menu > li > a:hover {
  background: #1e282c;
}
.control-sidebar-dark .control-sidebar-menu > li > a .menu-info > p {
  color: #b8c7ce;
}
.control-sidebar-light {
  color: #5e5e5e;
}
.control-sidebar-light,
.control-sidebar-light + .control-sidebar-bg {
  background: #f9fafc;
  border-left: 1px solid #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs {
  border-bottom: #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a {
  background: #e8ecf4;
  color: #444444;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:focus {
  border-left-color: #d2d6de;
  border-bottom-color: #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:focus,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:active {
  background: #eff1f7;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:focus,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:active {
  background: #f9fafc;
  color: #111;
}
.control-sidebar-light .control-sidebar-heading,
.control-sidebar-light .control-sidebar-subheading {
  color: #111;
}
.control-sidebar-light .control-sidebar-menu {
  margin-left: -14px;
}
.control-sidebar-light .control-sidebar-menu > li > a:hover {
  background: #f4f4f5;
}
.control-sidebar-light .control-sidebar-menu > li > a .menu-info > p {
  color: #5e5e5e;
}</code>```

<button class="btn btn-default" data-toggle="control-sidebar">This button opens the sidebar</button>

<button class="click">Add Stuff</button>

```

答:
When you are appending the button here,

```<code>$(".box").append(stuff);
</code>```

The events for the page has already been binded to the "existing" DOM elements. You are introducing a new "element" which fails to get the bind reference.
You need to bind click event to o.toggleBtnSelector directly instead of doing var btn = $(o.toggleBtnSelector);

This is the working JS Fiddle Link.

Body:
I have a button that opens a sidebar, when I click on it. When I append the same button to my box and the click on it, it is not opening the sidebar:

  <button class="btn btn-default" data-toggle="control-sidebar">Toggle Right Sidebar</button>

$(document).off("click", ".click").on("click", ".click", function (event) {
  $(".box").append(stuff);
});

var stuff = $('<button class="btn btn-default" data-toggle="control-sidebar">This button is not opening the sidebar. Why?</button>');

$.AdminLTE = {};
$.AdminLTE.options = {
    enableControlSidebar: true,
    controlSidebarOptions: {
        toggleBtnSelector: "[data-toggle='control-sidebar']",
        selector: ".control-sidebar",
        slide: false
    },
};

$(function () {
    "use strict";

    $("body").removeClass("hold-transition");

    if (typeof AdminLTEOptions !== "undefined") {
        $.extend(true,
            $.AdminLTE.options,
            AdminLTEOptions);
    }

    var o = $.AdminLTE.options;

    _init();

    $.AdminLTE.tree('.sidebar');

    if (o.enableControlSidebar) {
        $.AdminLTE.controlSidebar.activate();
    }

    if (o.sidebarPushMenu) {
        $.AdminLTE.pushMenu.activate(o.sidebarToggleSelector);
    }

});

function _init() {
    'use strict';

    $.AdminLTE.layout = {
        activate: function () {
            var _this = this;
            _this.fix();
            _this.fixSidebar();
            $(window, ".wrapper").resize(function () {
                _this.fix();
                _this.fixSidebar();
            });
        },
        fix: function () {

            var neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight();
            var window_height = $(window).height();
            var sidebar_height = $(".sidebar").height();
            if ($("body").hasClass("fixed")) {
                $(".content-wrapper, .right-side").css('min-height', window_height - $('.main-footer').outerHeight());
            } else {
                var postSetWidth;
                if (window_height >= sidebar_height) {
                    $(".content-wrapper, .right-side").css('min-height', window_height - neg);
                    postSetWidth = window_height - neg;
                } else {
                    $(".content-wrapper, .right-side").css('min-height', sidebar_height);
                    postSetWidth = sidebar_height;
                }

                var controlSidebar = $($.AdminLTE.options.controlSidebarOptions.selector);
                if (typeof controlSidebar !== "undefined") {
                    if (controlSidebar.height() > postSetWidth)
                        $(".content-wrapper, .right-side").css('min-height', controlSidebar.height());
                }

            }
        },
        fixSidebar: function () {
            if (!$("body").hasClass("fixed")) {
                if (typeof $.fn.slimScroll != 'undefined') {
                    $(".sidebar").slimScroll({
                        destroy: true
                    }).height("auto");
                }
                return;
            } else if (typeof $.fn.slimScroll == 'undefined' && window.console) {
                window.console.error("Error: the fixed layout requires the slimscroll plugin!");
            }
            if ($.AdminLTE.options.sidebarSlimScroll) {
                if (typeof $.fn.slimScroll != 'undefined') {

                    $(".sidebar").slimScroll({
                        destroy: true
                    }).height("auto");

                    $(".sidebar").slimscroll({
                        height: ($(window).height() - $(".main-header").height()) + "px",
                        color: "rgba(0,0,0,0.2)",
                        size: "3px"
                    });
                }
            }
        }
    };

    $.AdminLTE.tree = function (menu) {
        var _this = this;
        var animationSpeed = $.AdminLTE.options.animationSpeed;
        $(document).off('click', menu + ' li a')
            .on('click', menu + ' li a', function (e) {

                var $this = $(this);
                var checkElement = $this.next();

                if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible')) && (!$('body').hasClass('sidebar-collapse'))) {

                    checkElement.slideUp(animationSpeed, function () {
                        checkElement.removeClass('menu-open');

                    });
                    checkElement.parent("li").removeClass("active");
                }

                else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {

                    var parent = $this.parents('ul').first();

                    var ul = parent.find('ul:visible').slideUp(animationSpeed);

                    ul.removeClass('menu-open');

                    var parent_li = $this.parent("li");

                    checkElement.slideDown(animationSpeed, function () {

                        checkElement.addClass('menu-open');
                        parent.find('li.active').removeClass('active');
                        parent_li.addClass('active');

                        _this.layout.fix();
                    });
                }

                if (checkElement.is('.treeview-menu')) {
                    e.preventDefault();
                }
            });
    };

    $.AdminLTE.controlSidebar = {

        activate: function () {

            var _this = this;
            var o = $.AdminLTE.options.controlSidebarOptions;
            var sidebar = $(o.selector);

            var btn = $(o.toggleBtnSelector);

            btn.on('click', function (e) {
                e.preventDefault();
                _this.open(sidebar, o.slide);

            });

            $(".close_sidebar").on('click', function (e) {
                _this.close(sidebar, o.slide);
            });

            var bg = $(".control-sidebar-bg");
            _this._fix(bg);

            if ($('body').hasClass('fixed')) {
                _this._fixForFixed(sidebar);
            } else {

                if ($('.content-wrapper, .right-side').height() < sidebar.height()) {
                    _this._fixForContent(sidebar);
                }
            }
        },
        open: function (sidebar, slide) {

            if (slide) {
                sidebar.addClass('control-sidebar-open');
            } else {

                $('body').addClass('control-sidebar-open');
            }
        },

        close: function (sidebar, slide) {
            if (slide) {
                sidebar.removeClass('control-sidebar-open');
            } else {
                $('body').removeClass('control-sidebar-open');
            }
        },
        _fix: function (sidebar) {
            var _this = this;
            if ($("body").hasClass('layout-boxed')) {
                sidebar.css('position', 'absolute');
                sidebar.height($(".wrapper").height());
                if (_this.hasBindedResize) {
                    return;
                }
                $(window).resize(function () {
                    _this._fix(sidebar);
                });
                _this.hasBindedResize = true;
            } else {
                sidebar.css({
                    'position': 'fixed',
                    'height': 'auto'
                });
            }
        },
        _fixForFixed: function (sidebar) {
            sidebar.css({
                'position': 'fixed',
                'max-height': '100%',
                'overflow': 'auto',
                'padding-bottom': '50px'
            });
        },
        _fixForContent: function (sidebar) {
            $(".content-wrapper, .right-side").css('min-height', sidebar.height());
        }
    };

}

.box{
  width:100px;
  height:50px;
  background-color:pink
}

.control-sidebar-bg {
  position: fixed;
  z-index: 1000;
  bottom: 0;
}
.control-sidebar-bg,
.control-sidebar {
  top: 0;
  right: -430px;
  width: 430px;
  -webkit-transition: right 0.3s ease-in-out;
  -o-transition: right 0.3s ease-in-out;
  transition: right 0.3s ease-in-out;
}
.control-sidebar {
  position: absolute;
  padding-top: 50px;
  z-index: 1010;
}

.control-sidebar > .tab-content {
  padding: 10px 15px;
}
.control-sidebar.control-sidebar-open,
.control-sidebar.control-sidebar-open + .control-sidebar-bg {
  right: 0;
}
.control-sidebar-open .control-sidebar-bg,
.control-sidebar-open .control-sidebar {
  right: 0;
}

.control-sidebar-heading {
  font-weight: 400;
  font-size: 16px;
  padding: 10px 0;
  margin-bottom: 10px;
}
.control-sidebar-subheading {
  display: block;
  font-weight: 400;
  font-size: 14px;
}
.control-sidebar-menu {
  list-style: none;
  padding: 0;
  margin: 0 -15px;
}
.control-sidebar-menu > li > a {
  display: block;
  padding: 10px 15px;
}
.control-sidebar-menu > li > a:before,
.control-sidebar-menu > li > a:after {
  content: " ";
  display: table;
}
.control-sidebar-menu > li > a:after {
  clear: both;
}
.control-sidebar-menu > li > a > .control-sidebar-subheading {
  margin-top: 0;
}
.control-sidebar-menu .menu-icon {
  float: left;
  width: 35px;
  height: 35px;
  border-radius: 50%;
  text-align: center;
  line-height: 35px;
}
.control-sidebar-menu .menu-info {
  margin-left: 45px;
  margin-top: 3px;
}
.control-sidebar-menu .menu-info > .control-sidebar-subheading {
  margin: 0;
}
.control-sidebar-menu .menu-info > p {
  margin: 0;
  font-size: 11px;
}
.control-sidebar-menu .progress {
  margin: 0;
}
.control-sidebar-dark {
  color: #b8c7ce;
}
.control-sidebar-dark,
.control-sidebar-dark + .control-sidebar-bg {
  background: #222d32;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs {
  border-bottom: #1c2529;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a {
  background: #181f23;
  color: #b8c7ce;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:focus {
  border-left-color: #141a1d;
  border-bottom-color: #141a1d;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:focus,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:active {
  background: #1c2529;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li > a:hover {
  color: #fff;
}
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:hover,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:focus,
.control-sidebar-dark .nav-tabs.control-sidebar-tabs > li.active > a:active {
  background: #222d32;
  color: #fff;
}
.control-sidebar-dark .control-sidebar-heading,
.control-sidebar-dark .control-sidebar-subheading {
  color: #fff;
}
.control-sidebar-dark .control-sidebar-menu > li > a:hover {
  background: #1e282c;
}
.control-sidebar-dark .control-sidebar-menu > li > a .menu-info > p {
  color: #b8c7ce;
}
.control-sidebar-light {
  color: #5e5e5e;
}
.control-sidebar-light,
.control-sidebar-light + .control-sidebar-bg {
  background: #f9fafc;
  border-left: 1px solid #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs {
  border-bottom: #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a {
  background: #e8ecf4;
  color: #444444;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:focus {
  border-left-color: #d2d6de;
  border-bottom-color: #d2d6de;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:focus,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li > a:active {
  background: #eff1f7;
}
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:hover,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:focus,
.control-sidebar-light .nav-tabs.control-sidebar-tabs > li.active > a:active {
  background: #f9fafc;
  color: #111;
}
.control-sidebar-light .control-sidebar-heading,
.control-sidebar-light .control-sidebar-subheading {
  color: #111;
}
.control-sidebar-light .control-sidebar-menu {
  margin-left: -14px;
}
.control-sidebar-light .control-sidebar-menu > li > a:hover {
  background: #f4f4f5;
}
.control-sidebar-light .control-sidebar-menu > li > a .menu-info > p {
  color: #5e5e5e;
}

<button class="btn btn-default" data-toggle="control-sidebar">This button opens the sidebar</button>

<button class="click">Add Stuff</button>

Body:
When you are appending the button here,

$(".box").append(stuff);

The events for the page has already been binded to the "existing" DOM elements. You are introducing a new "element" which fails to get the bind reference.
You need to bind click event to o.toggleBtnSelector directly instead of doing var btn = $(o.toggleBtnSelector);

This is the working JS Fiddle Link.


问:
Find the the value of one field that matches the maximum value of data in another field
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

```<code>OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002
</code>```

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

```<code>CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002
</code>```

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.

答:
The trick is to use a subquery as a value, not as a join:</p>

```<code>select customerId,orderDate,locationId
  from orders o1
 where orderDate = (
           select top 1 orderdate
             from orders o2
            where o1.customerId = o2.customerId
            order by orderdate desc
       )
</code>```

Body:
I'm trying to write a query that gets the value of one field that's associated with the maximum value of another field (or fields).  Let's say I have the following table of data:

OrderID CustomerID  OrderDate   LocationID
1       4           1/1/2001    1001
2       4           1/2/2001    1003
3       4           1/3/2001    1001
4       5           1/4/2001    1001
5       5           1/5/2001    1001
6       5           1/6/2001    1003
7       5           1/7/2001    1002
8       5           1/8/2001    1003
9       5           1/8/2001    1002

Grouping by CustomerID, I want to get the maximum OrderDate and then the LocationID associated with whatever is the maximum OrderDate.  If there are several records that share the maximum order date, then take the LocationID associated with the maximum OrderID from among those records with the maximum date.

The final set of data should look like this:

CustomerID  OrderDate   LocationID
4           1/3/2001    1001
5           1/8/2001    1002

I had been trying to write a query with lots of nested subqueries and ugly joins, but I'm not really getting anywhere.  What SQL do I need to write to help me get this result.

Body:
The trick is to use a subquery as a value, not as a join:

select customerId,orderDate,locationId
  from orders o1
 where orderDate = (
           select top 1 orderdate
             from orders o2
            where o1.customerId = o2.customerId
            order by orderdate desc
       )


问:
Center coordinate of a set of CLLocationsCoordinate2D
Is there any way to get center coordinate of a set of CLLocationsCoordinate2D in iOS?

答:
You can also get both the center of an array of CLLocationCoordinate2Ds and a span.

```<code>extension MKCoordinateRegion {

  init(coordinates: [CLLocationCoordinate2D]) {
    var minLatitude: CLLocationDegrees = 90.0
    var maxLatitude: CLLocationDegrees = -90.0
    var minLongitude: CLLocationDegrees = 180.0
    var maxLongitude: CLLocationDegrees = -180.0

    for coordinate in coordinates {
      let lat = Double(coordinate.latitude)
      let long = Double(coordinate.longitude)
      if lat < minLatitude {
        minLatitude = lat
      }
      if long < minLongitude {
        minLongitude = long
      }
      if lat > maxLatitude {
        maxLatitude = lat
      }
      if long > maxLongitude {
        maxLongitude = long
      }
    }

    let span = MKCoordinateSpanMake(maxLatitude - minLatitude, maxLongitude - minLongitude)
    let center = CLLocationCoordinate2DMake((maxLatitude - span.latitudeDelta / 2), (maxLongitude - span.longitudeDelta / 2))
    self.init(center: center, span: span)
  }
}
</code>```

Usage:

```<code>let region = MKCoordinateRegion(coordinates: coordinates)
region.center
region.span
</code>```

Body:
You can also get both the center of an array of CLLocationCoordinate2Ds and a span.

extension MKCoordinateRegion {

  init(coordinates: [CLLocationCoordinate2D]) {
    var minLatitude: CLLocationDegrees = 90.0
    var maxLatitude: CLLocationDegrees = -90.0
    var minLongitude: CLLocationDegrees = 180.0
    var maxLongitude: CLLocationDegrees = -180.0

    for coordinate in coordinates {
      let lat = Double(coordinate.latitude)
      let long = Double(coordinate.longitude)
      if lat < minLatitude {
        minLatitude = lat
      }
      if long < minLongitude {
        minLongitude = long
      }
      if lat > maxLatitude {
        maxLatitude = lat
      }
      if long > maxLongitude {
        maxLongitude = long
      }
    }

    let span = MKCoordinateSpanMake(maxLatitude - minLatitude, maxLongitude - minLongitude)
    let center = CLLocationCoordinate2DMake((maxLatitude - span.latitudeDelta / 2), (maxLongitude - span.longitudeDelta / 2))
    self.init(center: center, span: span)
  }
}

Usage:

let region = MKCoordinateRegion(coordinates: coordinates)
region.center
region.span


问:
Execute a method after the completion of a block method
I am using RNFrostedSidebar for leftmenu. While dismissing the sidebar, below block of code is executing

```<code>- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
    [self dismissAnimated:YES completion:nil];
}

- (void)dismissAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion {

    void (^completionBlock)(BOOL) = ^(BOOL finished){
        [self rn_removeFromParentViewControllerCallingAppearanceMethods:YES];

        rn_frostedMenu = nil;

        if (completion) {
            completion(finished);
        }
    };

    if (animated) {
        CGFloat parentWidth = self.view.bounds.size.width;
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = self.showFromRight ? parentWidth : -_width;

        CGRect blurFrame = self.blurView.frame;
        blurFrame.origin.x = self.showFromRight ? parentWidth : 0;
        blurFrame.size.width = 0;
        self.blurView.frame = blurFrame;
        self.blurView.alpha=0.1;

        [UIView animateWithDuration:self.animationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                             self.viewForTable.frame = contentFrame;
                     }
                     completion:completionBlock];
    } else {
        completionBlock(YES);
    }
  }
</code>```

After dismissAnimated method executed i want to run a code to update the HomeViewController, That code is

```<code>[self callNavBar];

-(void) callNavBar {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                    object:self];
}
</code>```

i tried this solution, like adding the methods in queue and executing but i got exception as

"Main Thread Checker: UI API called on a background thread: -[UIView bounds]"

Then i tried this too got the same error as above.

答:
You can put the function as the completion handler here, instead of nil.
That way it will run exactly when you want it.

It would look somewhat like this.

```<code>- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
      [self dismissAnimated:YES completion:[self callNavBar]];
}
</code>```

Body:
I am using RNFrostedSidebar for leftmenu. While dismissing the sidebar, below block of code is executing

- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
    [self dismissAnimated:YES completion:nil];
}

- (void)dismissAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion {

    void (^completionBlock)(BOOL) = ^(BOOL finished){
        [self rn_removeFromParentViewControllerCallingAppearanceMethods:YES];

        rn_frostedMenu = nil;

        if (completion) {
            completion(finished);
        }
    };

    if (animated) {
        CGFloat parentWidth = self.view.bounds.size.width;
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = self.showFromRight ? parentWidth : -_width;

        CGRect blurFrame = self.blurView.frame;
        blurFrame.origin.x = self.showFromRight ? parentWidth : 0;
        blurFrame.size.width = 0;
        self.blurView.frame = blurFrame;
        self.blurView.alpha=0.1;

        [UIView animateWithDuration:self.animationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                             self.viewForTable.frame = contentFrame;
                     }
                     completion:completionBlock];
    } else {
        completionBlock(YES);
    }
  }

After dismissAnimated method executed i want to run a code to update the HomeViewController, That code is

[self callNavBar];

-(void) callNavBar {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                    object:self];
}

i tried this solution, like adding the methods in queue and executing but i got exception as

"Main Thread Checker: UI API called on a background thread: -[UIView bounds]"

Then i tried this too got the same error as above.

Body:
You can put the function as the completion handler here, instead of nil.
That way it will run exactly when you want it.

It would look somewhat like this.

- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
      [self dismissAnimated:YES completion:[self callNavBar]];
}


问:
Phoenix is ignoring csrf_token for an ajax request
I have this ajax request:

```<code>//..............
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.setRequestHeader("x-csrf-token", document.querySelector("meta[name=csrf]").content);
xhr.send(JSON.stringify(data));
</code>```

On a page there's a csrf token generated by Phoenix.

```<code><meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>" />
</code>```

It's sent on a server along with each ajax request I can see in Chrome. But my server always returns:

```<code>"403: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header"
</code>```

Why? How to fix this?

答:
name="csrf-token" id="csrf-token" value="<%= Plug.CSRFProtection.get_csrf_token() %>"
Try this . This is working for me

```<code>var xhr = new XMLHttpRequest();
 var csrf_token = document.getElementById('csrf-token').value;
 xhr.open('POST', '/api/vote');
 xhr.setRequestHeader('Content-Type', 'application/json');
 xhr.setRequestHeader("X-CSRF-Token", csrf_token);
</code>```

This is my ajax request

Body:
I have this ajax request:

//..............
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.setRequestHeader("x-csrf-token", document.querySelector("meta[name=csrf]").content);
xhr.send(JSON.stringify(data));

On a page there's a csrf token generated by Phoenix.

<meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>" />

It's sent on a server along with each ajax request I can see in Chrome. But my server always returns:

"403: invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header"

Why? How to fix this?

Body:
name="csrf-token" id="csrf-token" value="<%= Plug.CSRFProtection.get_csrf_token() %>"
Try this . This is working for me

var xhr = new XMLHttpRequest();
 var csrf_token = document.getElementById('csrf-token').value;
 xhr.open('POST', '/api/vote');
 xhr.setRequestHeader('Content-Type', 'application/json');
 xhr.setRequestHeader("X-CSRF-Token", csrf_token);

This is my ajax request